<template>
  <div class="purchaseReturnEdit-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" class="purchaseReturnEdit-back" >
        <!-- 自定义的二级文字标题 -->
        <template slot="subTitle">
          <a id="purchaseReturnEdit-back-btn" href="javascript:;" @click="handleBack"><a-icon type="left" /> 返回列表</a>
          <span style="margin: 0 15px;color: #666;" v-if="detailData">供应商名称：{{ detailData.returnTargetName || '--' }}</span>
        </template>
        <!-- 操作区，位于 title 行的行尾 -->
        <template slot="extra" v-if="$hasPermissions('B_purchaseReturnPrint')">
          <Print :disabled="dataSource.length==0" @handlePrint="handlePrint"></Print>
        </template>
      </a-page-header>
      <!-- 选择产品 -->
      <a-card size="small" :bordered="false" class="purchaseReturnEdit-cont">
        <div class="purchaseReturnEdit-cont">
          <a-collapse :activeKey="['1']">
            <a-collapse-panel key="1" header="选择产品">
              <!-- 筛选条件 -->
              <div class="table-page-search-wrapper">
                <a-form layout="inline" @keyup.enter.native="$refs.table.refresh(true)">
                  <a-row :gutter="15">
                    <a-col :md="6" :sm="24">
                      <a-form-item label="采购单号" prop="purchaseBillNo">
                        <a-input id="purchaseReturnEdit-purchaseBillNo" v-model.trim="queryParam.purchaseBillNo" placeholder="请输入采购单号" allowClear />
                      </a-form-item>
                    </a-col>
                    <a-col :md="6" :sm="24">
                      <a-form-item label="产品编码" prop="productCode">
                        <a-input id="purchaseReturnEdit-productCode" v-model.trim="queryParam.productCode" placeholder="请输入产品编码" allowClear />
                      </a-form-item>
                    </a-col>
                    <a-col :md="6" :sm="24">
                      <a-form-item label="产品名称" prop="productName">
                        <a-input id="purchaseReturnEdit-productName" v-model.trim="queryParam.productName" placeholder="请输入产品名称" allowClear />
                      </a-form-item>
                    </a-col>
                    <a-col :md="6" :sm="24" style="margin-bottom: 10px;">
                      <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="purchaseReturnList-refresh">查询</a-button>
                      <a-button style="margin-left: 8px" @click="resetSearchForm" :disabled="disabled" id="purchaseReturnList-reset">重置</a-button>
                    </a-col>
                  </a-row>
                </a-form>
              </div>
              <!-- 列表 -->
              <s-table
                class="sTable"
                ref="table"
                size="small"
                :rowKey="(record) => record.id"
                :columns="columns"
                :data="loadData"
                :pageSize="10"
                :scroll="{ y: 149 }"
                bordered>
                <!-- 数量 -->
                <template slot="returnQty" slot-scope="text, record">
                  <a-input-number
                    size="small"
                    id="purchaseReturnEdit-returnQty"
                    v-model="record.returnQty"
                    :precision="0"
                    :min="1"
                    :max="record.refundableQty"
                    placeholder="请输入"
                    style="width: 100%;" />
                </template>
                <!-- 单价 -->
                <template slot="returnPrice" slot-scope="text, record">
                  <a-input-number
                    size="small"
                    id="purchaseReturnEdit-returnPrice"
                    v-model="record.returnPrice"
                    :precision="2"
                    :min="0"
                    :max="999999"
                    placeholder="请输入"
                    style="width: 100%;" />
                </template>
                <!-- 操作 -->
                <template slot="action" slot-scope="text, record">
                  <span v-if="record.refundableQty==0">--</span>
                  <a-button
                    v-else
                    size="small"
                    type="link"
                    class="button-primary"
                    @click="handleAdd(record)"
                    id="purchaseReturnEdit-add-btn">添加</a-button>
                </template>
              </s-table>
            </a-collapse-panel>
          </a-collapse>
        </div>
      </a-card>
      <!-- 已选产品 -->
      <a-card size="small" :bordered="false" class="purchaseReturnEdit-cont">
        <a-collapse :activeKey="['1']">
          <a-collapse-panel key="1">
            <template slot="header">
              已选产品
              <!-- <a-button
                size="small"
                type="primary"
                class="button-error"
                id="purchaseReturnEdit-delAll-btn"
                @click.stop="handleDel('', 'all')"
                style="margin-right: 10px;float: right;">整单删除</a-button> -->
            </template>
            <!-- 总计 -->
            <a-alert type="info" style="margin-bottom:10px">
              <div slot="message">
                总款数<strong>{{ (detailData&&(detailData.totalCategory || detailData.totalCategory==0)) ? detailData.totalCategory : '--' }}</strong> ，
                总数量<strong>{{ (detailData&&(detailData.totalQty || detailData.totalQty==0)) ? detailData.totalQty : '--' }}</strong> ，
                总金额<strong>{{ (detailData&&(detailData.totalAmount || detailData.totalAmount==0)) ? '￥'+detailData.totalAmount : '--' }}</strong>
              </div>
            </a-alert>
            <!-- 筛选条件 -->
            <a-row :gutter="15" justify="space-between">
              <a-col :span="17">
                <div class="table-page-search-wrapper">
                  <a-form layout="inline" @keyup.enter.native="$refs.chooseTable.refresh(true)">
                    <a-row :gutter="15">
                      <a-col :md="9" :sm="24">
                        <a-form-item label="产品编码" prop="productCode">
                          <a-input id="bulkReturnGoodsEdit-productCode" v-model.trim="chooseQueryParam.productCode" placeholder="请输入产品编码" allowClear />
                        </a-form-item>
                      </a-col>
                      <a-col :md="9" :sm="24">
                        <a-form-item label="产品名称" prop="productName">
                          <a-input id="bulkReturnGoodsEdit-productName" v-model.trim="chooseQueryParam.productName" placeholder="请输入产品名称" allowClear />
                        </a-form-item>
                      </a-col>
                      <a-col :md="6" :sm="24" style="margin-bottom: 10px;">
                        <a-button type="primary" @click="$refs.chooseTable.refresh(true)" :disabled="chooseDisabled" id="bulkReturnGoodsEdit-refresh">查询</a-button>
                        <a-button style="margin-left: 8px" @click="chooseResetSearchForm" :disabled="chooseDisabled" id="bulkReturnGoodsEdit-reset">重置</a-button>
                      </a-col>
                    </a-row>
                  </a-form>
                </div>
              </a-col>
              <a-col :span="7" style="text-align: right;"></a-col>
            </a-row>
            <!-- 列表 -->
            <s-table
              class="sTable"
              ref="chooseTable"
              size="small"
              :rowKey="(record) => record.id"
              :columns="chooseColumns"
              :data="chooseLoadData"
              :defaultLoadData="false"
              :pageSize="10"
              :scroll="{ y: 149 }"
              bordered>
              <!-- 退货数量 -->
              <template slot="qty" slot-scope="text, record">
                <a-input-number
                  size="small"
                  id="purchaseReturnEdit-qty"
                  v-model="record.qty"
                  :precision="0"
                  :min="1"
                  :max="record.refundableQty"
                  placeholder="请输入"
                  @blur="e => qtyBlur(e.target.value, record)"
                  style="width: 100%;" />
              </template>
              <!-- 退货单价 -->
              <template slot="price" slot-scope="text, record">
                <a-input-number
                  size="small"
                  id="purchaseReturnEdit-cost"
                  v-model="record.cost"
                  :precision="2"
                  :min="0"
                  :max="999999"
                  placeholder="请输入"
                  @blur="e => costBlur(e.target.value, record)"
                  style="width: 100%;" />
              </template>
              <!-- 退货金额合计 amount-->
              <template slot="amount" slot-scope="text, record">
                {{ (record.cost * record.qty).toFixed(2) }}
              </template>
              <!-- 操作 -->
              <template slot="action" slot-scope="text, record">
                <a-button size="small" type="link" class="button-error" @click="handleDel(record)" id="purchaseReturnEdit-del-btn">删除</a-button>
              </template>
            </s-table>
          </a-collapse-panel>
        </a-collapse>
      </a-card>
    </a-spin>
    <a-card size="small" :bordered="false" class="affix-cont">
      <a-button
        type="primary"
        id="purchaseReturnEdit-submit"
        size="large"
        :disabled="spinning"
        class="button-primary"
        @click="handleSubmit"
        style="padding: 0 60px;">提交</a-button>
    </a-card>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import Print from '@/views/common/print.vue'
import { hdPrint } from '@/libs/JGPrint'
import {
  purchaseReturnPurchaseBillNoSyncList,
  purchaseReturnDetailList,
  purchaseReturnDetailSave,
  purchaseReturnDetailDel,
  purchaseReturnSubmit,
  purchaseReturnDelAll,
  purchaseReturnDetailPrint,
  purchaseReturnDetailExport,
  purchaseReturnDetailSn } from '@/api/purchaseReturn'
export default {
  name: 'PurchaseReturnEdit',
  components: { STable, VSelect, Print },
  mixins: [commonMixin],
  data () {
    return {
      spinning: false,
      detailData: null,
      queryParam: {
        purchaseBillNo: '',
        productCode: '',
        productName: ''
      },
      dataSource: [],
      disabled: false, //  查询、重置按钮是否可操作
      advanced: false, // 高级搜索 展开/关闭
      // 表头
      columns: [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '采购单号', dataIndex: 'purchaseBillNo', width: '14%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品编码', dataIndex: 'dealerProductEntity.code', width: '13%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'dealerProductEntity.name', width: '13%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '采购价格', dataIndex: 'price', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '采购数量', dataIndex: 'qty', width: '7%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '已退数量', dataIndex: 'refundableQty', width: '9%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '可退数量', dataIndex: 'refundableQty', width: '7%', align: 'center' },
        { title: '库存数量', dataIndex: 'stock.currentStockQty', width: '7%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '单位', dataIndex: 'dealerProductEntity.unit', width: '5%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '退货单价', scopedSlots: { customRender: 'returnPrice' }, width: '8%', align: 'center' },
        { title: '退货数量', scopedSlots: { customRender: 'returnQty' }, width: '8%', align: 'center' },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '7%', align: 'center' }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.queryParam.returnTargetType = this.$route.params.returnTargetType
        return purchaseReturnPurchaseBillNoSyncList(Object.assign(parameter, this.queryParam)).then(res => {
          const data = res.data
          const no = (data.pageNo - 1) * data.pageSize
          for (var i = 0; i < data.list.length; i++) {
            data.list[i].no = no + i + 1
          }
          this.disabled = false
          return data
        })
      },
      chooseDisabled: false,
      chooseQueryParam: {
        productCode: '',
        productName: ''
      },
      // 表头
      chooseColumns: [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '采购单号', dataIndex: 'purchaseBillNo', width: '15%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品编码', dataIndex: 'dealerProductEntity.code', width: '14%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'dealerProductEntity.name', width: '15%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '单位', dataIndex: 'dealerProductEntity.unit', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '退货单价', scopedSlots: { customRender: 'price' }, width: '10%', align: 'center' },
        { title: '退货数量', scopedSlots: { customRender: 'qty' }, width: '10%', align: 'center' },
        { title: '退货金额', scopedSlots: { customRender: 'amount' }, width: '6%', align: 'center' },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '8%', align: 'center' }
      ],
      // 加载数据方法 必须为 Promise 对象
      chooseLoadData: parameter => {
        return purchaseReturnDetailList(Object.assign(parameter,
          this.chooseQueryParam,
          {
            purchaseReturnSn: this.$route.params.sn,
            orderBy: 'qpls_purchase_return_bill_detail.CREATE_DATE desc'
          })).then(res => {
          const data = res.data
          const no = (data.pageNo - 1) * data.pageSize
          for (var i = 0; i < data.list.length; i++) {
            data.list[i].no = no + i + 1
            data.list[i].qtyBackups = data.list[i].qty
            data.list[i].costBackups = data.list[i].cost
            data.list[i].refundableQty = data.list[i].purchaseBillRefundableQty
          }
          this.dataSource = data.list
          return data
        })
      }
    }
  },
  methods: {
    // 打印预览/快捷打印
    handlePrint (type, printerType) {
      const _this = this
      _this.spinning = true
      let url = purchaseReturnDetailPrint
      const params = { sn: this.$route.params.sn }
      if (type == 'export') { //  导出
        url = purchaseReturnDetailExport
      }
      // 打印或导出
      hdPrint(printerType, type, url, params, '采购退货单', function () {
        _this.spinning = false
      })
    },
    //  重置
    resetSearchForm () {
      this.queryParam.purchaseBillNo = ''
      this.queryParam.productCode = ''
      this.queryParam.productName = ''
      this.$refs.table.refresh(true)
    },
    // 已选产品  重置
    chooseResetSearchForm () {
      this.chooseQueryParam.productCode = ''
      this.chooseQueryParam.productName = ''
      this.$refs.chooseTable.refresh(true)
    },
    //  添加/编辑
    handleAdd (row, isEdit) {
      // 添加时退货数量字段名为returnQty,编辑时退货数量字段名为qty
      if (!isEdit && !row.returnPrice) {
        this.$message.warning('请输入退货价格')
        return
      }
      if (!isEdit && !row.returnQty) {
        this.$message.warning('请输入退货数量')
        return
      }
      const params = {
        id: isEdit ? row.id : undefined,
        purchaseReturnSn: this.$route.params.sn,
        purchaseBillSn: row.purchaseBillSn,
        purchaseBillNo: row.purchaseBillNo,
        purchaseBillDetailSn: row.purchaseBillDetailSn,
        qty: isEdit ? row.qty : row.returnQty, //  退货数量
        productSn: row.productSn,
        cost: isEdit ? row.cost : row.returnPrice,
        remarks: row.remarks,
        promotionFlag: row.promotionFlag
      }
      if (isEdit) { // 编辑
        // 清空退货数量时,值应保持未清空前的值，因退货数量都不可为空
        if (!row.qty) {
          row.qty = row.qtyBackups
          return
        }
        if (!row.cost) {
          row.cost = row.costBackups
          return
        }
      }
      this.spinning = true
      purchaseReturnDetailSave(params).then(res => {
        if (res.status == 200) {
          this.$message.success(res.message)

          this.getDetail(true, true)
          this.$refs.chooseTable.refresh()
          this.spinning = false
        } else {
          this.spinning = false
        }
      })
    },
    // 双击快速添加
    handleClickRow (record) {
      return {
        on: {
          dblclick: (event) => {
            this.handleAdd(record)
          }
        }
      }
    },
    // 导入明细
    handleImport () {},
    //  删除
    handleDel (row, isAll) {
      const _this = this
      const content = isAll ? '删除后不可恢复，确定要进行整单删除吗？' : '删除后不可恢复，确定要进行删除吗？'
      this.$confirm({
        title: '提示',
        content: content,
        centered: true,
        onOk () {
          if (isAll) { //  整单删除
            _this.spinning = true
            purchaseReturnDelAll({ purchaseReturnSn: _this.$route.params.sn }).then(res => {
              if (res.status == 200) {
                _this.$message.success(res.message)
                _this.getDetail(true, true)
                _this.$refs.chooseTable.refresh()
                _this.spinning = false
              } else {
                _this.spinning = false
              }
            })
          } else { //  单个删除
            _this.spinning = true
            purchaseReturnDetailDel({ id: row.id }).then(res => {
              if (res.status == 200) {
                _this.$message.success(res.message)
                _this.getDetail(true, true)
                _this.$refs.chooseTable.refresh()
                _this.spinning = false
              } else {
                _this.spinning = false
              }
            })
          }
        }
      })
    },
    //  提交
    handleSubmit () {
      const _this = this
      _this.spinning = true
      purchaseReturnSubmit({ id: _this.detailData.id }).then(res => {
        if (res.status == 200) {
          this.$message.success(res.message)
          setTimeout(() => {
            _this.handleBack()
            _this.spinning = false
          }, 1000)
        } else {
          _this.spinning = false
        }
      })
    },
    //  返回列表
    handleBack () {
      this.$router.push({ name: 'purchaseReturnOutSyncList' })
    },
    // 已选产品 退货数量  blur
    qtyBlur (val, record) {
      //  光标移出，值发生改变再调用编辑接口
      if (val != record.qtyBackups) {
        this.handleAdd(record, 'edit')
      }
    },
    // 已选产品 退货单价  blur
    costBlur (val, record) {
      if (val && (val != record.costBackups)) {
        this.handleAdd(record, 'edit')
      }
    },
    // 获取详情
    getDetail (type, refresh) {
      purchaseReturnDetailSn({ sn: this.$route.params.sn }).then(res => {
        this.detailData = res.data || null
        if (!type) {
          this.resetSearchForm()
        } else {
          if (!refresh) {
            this.$refs.table.refresh(true)
          }
        }
      })
    },
    pageInit () {
      this.getDetail(true, true)
      this.$refs.chooseTable.refresh(true)
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
    }
  },
  activated () {
    // 如果是新页签打开或者进入新的子页（例：存在列表第2条数据编辑页页签时再打开第4条数据的编辑页），则重置当前页面
    if (this.$store.state.app.isNewTab || !this.$store.state.app.isNewSubTab) {
      this.pageInit()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>

<style lang="less">
  .purchaseReturnEdit-wrap{
    position: relative;
    height: 100%;
    padding-bottom: 51px;
    box-sizing: border-box;
    >.ant-spin-nested-loading{
      overflow-y: auto;
      height: 100%;
    }
    .purchaseReturnEdit-back, .purchaseReturnEdit-cont{
      margin-bottom: 10px;
    }
  }
</style>
