<template>
  <div class="salesReturnList-wrap">
    <!-- 搜索条件 -->
    <div class="table-page-search-wrapper">
      <div style="width:100%">
        <a-form layout="inline" @keyup.enter.native="$refs.chooseTable.refresh(true)">
          <a-row :gutter="15">
            <a-col :md="5" :sm="24">
              <a-form-item label="入库单号">
                <a-input id="salesReturnList-productCode" v-model.trim="queryParam.sparePartsNo" allowClear placeholder="请输入入库单号"/>
              </a-form-item>
            </a-col>
            <a-col :md="5" :sm="24">
              <a-form-item label="财务审核时间">
                <rangeDate ref="rangeDate" :value="warehousingDate" @change="dateChange" />
              </a-form-item>
            </a-col>
            <a-col :md="5" :sm="24">
              <a-form-item label="产品编码">
                <a-input id="salesReturnList-productCode" v-model.trim="queryParam.productCode" allowClear placeholder="请输入产品编码"/>
              </a-form-item>
            </a-col>
            <a-col :md="5" :sm="24">
              <a-form-item label="产品名称">
                <a-input id="salesReturnList-productName" v-model.trim="queryParam.productName" allowClear placeholder="请输入产品名称"/>
              </a-form-item>
            </a-col>
            <a-col :md="4" :sm="24">
              <a-button type="primary" @click="$refs.chooseTable.refresh(true)" id="salesReturnList-refresh">查询</a-button>
              <a-button style="margin-left: 5px" @click="resetSearchForm" id="salesReturnList-reset">重置</a-button>
            </a-col>
            <a-col :md="24" :sm="24" style="margin-bottom: 10px;display: flex;align-items: center;justify-content: space-between;">
              <div>
                <a-button type="primary" style="margin-right: 5px" @click="handleBatchAdd" :loading="addMoreLoading">批量添加</a-button>
                <span v-if="selNums&&selNums!=0" style="margin:0 10px;">已选中{{ selNums }}项</span>
              </div>
              <div v-if="queryParam.grabFlag==1">
                <a-checkbox @change="onChange" :checked="isChecked">
                  显示最大可退数量为0的产品
                </a-checkbox>
              </div>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </div>
    <!-- 列表 -->
    <s-table
      class="sTable"
      ref="chooseTable"
      size="small"
      :rowKey="(record) => record.no"
      rowKeyName="no"
      :row-selection="{ columnWidth: 40,getCheckboxProps: record => ({ props: { disabled: record.currentStockQty == 0 || record.isCheckedFlag} }) }"
      @rowSelection="rowSelectionFun"
      :columns="columns"
      :data="loadData"
      :defaultLoadData="false"
      :scroll="{ y: 300 }"
      bordered>
      <!-- 申请退货数量 -->
      <template slot="qty" slot-scope="text, record">
        <div @dblclick.stop>
          <a-input-number
            size="small"
            v-model="record.qty"
            :precision="0"
            :min="1"
            :disabled="record.currentStockQty == 0"
            :max="record.currentStockQty"
            style="width: 100%;"
            placeholder="请输入"/>
        </div>
      </template>
      <!-- 操作 -->
      <template slot="action" slot-scope="text, record">
        <a-button
          size="small"
          type="link"
          class="button-info"
          :loading="newLoading"
          v-if="record.currentStockQty != 0 && !record.isCheckedFlag"
          @click="handleAdd(record)"
        >添加</a-button>
        <span v-else>--</span>
      </template>
    </s-table>
  </div>
</template>

<script>
import { queryDetailStockPage } from '@/api/spareParts'
import { queryDetailSnListBySn } from '@/api/sparePartsReturn'
import { STable, VSelect } from '@/components'
import rangeDate from '@/views/common/rangeDate.vue'
import { toThousands } from '@/libs/tools.js'
export default {
  name: 'QueryPart',
  components: { STable, VSelect, rangeDate },
  props: {
    newLoading: Boolean,
    isShowPrice: {
      type: Boolean,
      default: true
    },
    // 是否显示仓库实收数量
    showReceiveQty: {
      type: Boolean,
      default: false
    },
    addMoreLoading: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      buyerSn: '',
      queryParam: { //  查询条件
        productName: '', // 产品名称
        productCode: '', //  产品编码
        beginDate: '',
        endDate: '',
        sparePartsNo: '',
        isZero: 0,
        createDate: undefined,
        grabFlag: ''
      },
      warehousingDate: [], // 入库时间
      rowSelectionInfo: null,
      isChecked: false,
      repeatList: null,
      warehouseSn: null,
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.queryParam.supplierSn = this.buyerSn
        this.queryParam.createDate = '2023-01-01 00:00:00'
        this.queryParam.warehouseSn = this.warehouseSn
        return queryDetailStockPage(Object.assign(parameter, this.queryParam)).then(res => {
          let data
          if (res.status == 200) {
            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].qty = data.list[i].currentStockQty
              data.list[i].isCheckedFlag = this.repeatList.findIndex(item => { return item == data.list[i].sparePartsDetailSn }) > -1
            }
          }
          return data
        })
      }
    }
  },
  computed: {
    columns () {
      const arr = [
        { title: '序号', dataIndex: 'no', width: '6%', align: 'center' },
        { title: '入库单号', dataIndex: 'sparePartsNo', width: '24%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品编码', dataIndex: 'product.code', width: '24%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'product.name', width: '24%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '单位', dataIndex: 'product.unit', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '批次号', dataIndex: 'sparePartsBatchNo', width: '13%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '入库数量', dataIndex: 'productQty', width: '9%', align: 'center', customRender: function (text) { return (text || text == 0) ? text : '--' } },
        // { title: '已退数量', dataIndex: 'returnedQty', width: '9%', align: 'center', customRender: function (text) { return (text || text == 0) ? text : '--' } },
        { title: '最大可退数量', dataIndex: 'currentStockQty', width: '9%', align: 'center', customRender: function (text) { return (text || text == 0) ? text : '--' } },
        { title: '申请退货数量', width: '10%', align: 'center', scopedSlots: { customRender: 'qty' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '10%', align: 'center' }
      ]
      if (this.$hasPermissions('B_purchaseReturnEdit_costPrice')) {
        arr.splice(6, 0, { title: '入库单价', dataIndex: 'productCost', width: '8%', align: 'right', customRender: function (text) { return ((text || text == 0) ? toThousands(text, 2) : '--') } })
      }
      if (this.queryParam.grabFlag == 1) { // 抓单
        const pos = this.$hasPermissions('B_purchaseReturnEdit_costPrice') ? 8 : 7
        arr.splice(pos, 0, { title: '已退数量', dataIndex: 'returnedQty', width: '9%', align: 'center', customRender: function (text) { return (text || text == 0) ? text : '--' } })
      }
      return arr
    },
    selNums () {
      return this.rowSelectionInfo && this.rowSelectionInfo.selectedRowKeys.length || 0
    }
  },
  methods: {
    //  重置
    resetSearchForm () {
      this.queryParam.productName = ''
      this.queryParam.productCode = ''
      this.queryParam.sparePartsNo = ''
      this.warehousingDate = []
      this.$refs.rangeDate.resetDate(this.warehousingDate)
      this.$refs.chooseTable.refresh(true)
    },
    onChange (e) {
      this.isChecked = !this.isChecked
      this.queryParam.isZero = e.target.checked ? 1 : 0
      this.$refs.chooseTable.refresh()
    },
    //  入库时间  change
    dateChange (date) {
      this.queryParam.beginDate = date[0] ? date[0] : ''
      this.queryParam.endDate = date[1] ? date[1] : ''
    },
    pageInit (buyerSn, returnSn, warehouseSn, grabFlag) {
      this.buyerSn = buyerSn
      this.queryParam.grabFlag = grabFlag
      this.warehouseSn = warehouseSn
      this.getRepeatResult(returnSn)
      this.$refs.chooseTable.refresh()
      // this.$refs.chooseTable.clearSelected()
    },
    // 添加
    handleAdd (row) {
      const selectArr = this.rowSelectionInfo ? this.rowSelectionInfo.selectedRowKeys : null
      if (selectArr && selectArr.length > 0) {
        const pot = selectArr.findIndex(item => { return item == row.id })
        selectArr.splice(pot, 1)
        const index = this.rowSelectionInfo.selectedRows.findIndex(item => { return item.sparePartsDetailSn == row.sparePartsDetailSn })
        this.rowSelectionInfo.selectedRows.splice(index, 1)
        this.$nextTick(() => { // 页面渲染完成后的回调
          this.$refs.chooseTable.setTableSelected(selectArr, this.rowSelectionInfo.selectedRows) // 设置表格选中项
        })
      }
      this.$emit('add', row)
    },
    // 删除后选中长度恢复
    refreshLength (row) {
      this.$refs.chooseTable.clearSelected()
    },
    // 表格选中项
    rowSelectionFun (obj) {
      this.rowSelectionInfo = obj || null
    },
    // 批量添加
    handleBatchAdd () {
      console.log(this.rowSelectionInfo)
      const row = this.rowSelectionInfo && this.rowSelectionInfo.selectedRowKeys
      if (!row || row.length == 0) {
        this.$message.warning('请先选择要添加的产品！')
        return
      }
      this.$emit('bachAdd', this.rowSelectionInfo.selectedRows)
    },
    getRepeatResult (sn) {
      queryDetailSnListBySn({ sn }).then(res => {
        if (res.status == 200) {
          this.repeatList = res.data
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
  .salesReturnList-wrap{
    .redBg-row{
      background-color: #f5cdc8;
    }
  }
  /deep/.sTable input:disabled{
    color:gray !important;
    -webkit-text-fill-color:gray !important;
  }
</style>
