<template>
  <div class="salesReturnCheck-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" class="salesReturnCheck-back" >
        <!-- 自定义的二级文字标题 -->
        <template slot="subTitle">
          <a id="salesReturnCheck-back-btn" href="javascript:;" @click="handleBack"><a-icon type="left" /> 返回列表</a>
          <span style="margin: 0 15px;color: #666;">客户名称：{{ ordeDetail&&ordeDetail.buyerName || '--' }}</span>
        </template>
      </a-page-header>
      <a-card size="small" :bordered="false" class="salesReturnCheck-cont">
        <a-form layout="inline" style="margin-bottom:10px;" @keyup.enter.native="searchForm">
          <a-form-item label="产品编码" prop="productCode">
            <a-input id="salesReturnCheck-productCode" v-model.trim="queryParam.productCode" placeholder="请输入产品编码" allowClear />
          </a-form-item>
          <a-form-item label="产品名称" prop="productName">
            <a-input id="salesReturnCheck-productName" v-model.trim="queryParam.productName" placeholder="请输入产品名称" allowClear />
          </a-form-item>
          <a-form-item>
            <a-button type="primary" class="button-info" @click="searchForm" :disabled="disabled" id="salesReturnCheck-refresh">查询</a-button>
            <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="salesReturnCheck-reset">重置</a-button>
          </a-form-item>
        </a-form>
        <div style="border-top:1px solid #eee;padding-top:10px;">
          <a-button type="primary" :loading="loading" class="button-info" @click="plSetQty(1)">批量设置良品数量</a-button>
          <a-button type="primary" :loading="loading" class="button-error" @click="plSetQty(2)">批量设置返库数量</a-button>
          <div style="float:right;color:#999;margin-top:8px;">说明：红色行表示收货时新增的产品</div>
        </div>
        <!-- 已选配件列表 -->
        <s-table
          class="sTable"
          ref="table"
          :style="{ height: tableHeight+84.5+'px' }"
          :rowClassName="(record, index) => record.addFlag == '1' ? (record.addType == 'WAREHOUSE_RECEIVE'?'redBg-row':'orgBg-row'):''"
          size="small"
          :rowKey="(record) => record.id"
          :row-selection="{ columnWidth: 40 }"
          @rowSelection="rowSelectionFun"
          :columns="columns"
          :data="loadData"
          :scroll="{ y: tableHeight }"
          :defaultLoadData="false"
          bordered>
          <!-- 良品数量 -->
          <template slot="goodQty" slot-scope="text, record">
            <a-input-number
              id="salesReturn-goodQty"
              size="small"
              v-model="record.goodQty"
              :precision="0"
              :min="0"
              :max="record.receiveQty"
              placeholder="请输入"
              @blur="e => updateGoodQty(e.target.value, record)"
              style="width: 100%;" />
          </template>
          <!-- 返库数量 -->
          <template slot="backStockQty" slot-scope="text, record">
            <a-input-number
              id="salesReturn-backStockQty"
              size="small"
              v-model="record.backStockQty"
              :precision="0"
              :min="0"
              placeholder="请输入"
              @blur="e => updateBackStockQty(e.target.value, record)"
              style="width: 100%;" />
          </template>
        </s-table>
        <div class="footer-btn">
          <a-button
            size="large"
            style="padding: 0 60px;"
            :disabled="spinning"
            type="primary"
            class="button-primary"
            @click="handleSubmit()"
            id="salesReturn-handleSubmit">提交</a-button>
        </div>
      </a-card>
    </a-spin>
    <!-- 选中批量操作 -->
    <chooseTypeModal :openModal="openTypeModal" :type="actionType" @close="openTypeModal=false" @confirm="plconfirm"></chooseTypeModal>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import { salesReturnDetail, salesReturnCheck } from '@/api/salesReturn'
import { salesReturnDetailList, updateBatchBackStockQty, updateBatchGoodQty } from '@/api/salesReturnDetail'
import chooseTypeModal from './chooseTypeModal.vue'
export default {
  name: 'SalesReturnCheck',
  mixins: [commonMixin],
  components: {
    STable,
    VSelect,
    chooseTypeModal
  },
  data () {
    return {
      spinning: false,
      tableHeight: 0, // 表格高度
      orderSn: null,
      openTypeModal: false,
      actionType: '',
      disabled: false,
      isInster: false, // 是否正在添加产品
      ordeDetail: { discountAmount: 0 },
      loading: false,
      // 已选产品
      dataSource: [],
      productForm: {
        salesReturnBillSn: ''
      },
      queryParam: {
        productCode: '',
        productName: ''
      },
      chooseLoadData: [],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        // 查询总计
        this.productForm.salesReturnBillSn = this.$route.params.sn
        return salesReturnDetailList(Object.assign(parameter, this.productForm, 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].goodQty = data.list[i].goodQty || 0
              data.list[i].backStockQty = data.list[i].backStockQty || 0
              data.list[i].goodQtyBackups = data.list[i].goodQty
              data.list[i].backStockQtyBackups = data.list[i].backStockQty
            }
            this.disabled = false
            this.chooseLoadData = data.list
          }
          return data
        })
      },
      rowSelectionInfo: null
    }
  },
  computed: {
    columns () {
      const arr = [
        { title: '序号', dataIndex: 'no', width: '6%', align: 'center' },
        { title: '产品编码', dataIndex: 'productEntity.code', align: 'center', width: '20%', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'productEntity.name', width: '28%', align: 'left', customRender: function (text) { return text || '--' } },
        { title: '单位', dataIndex: 'productEntity.unit', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '申请退货数量', dataIndex: 'qty', align: 'center', width: '10%', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '仓库实收数量', dataIndex: 'receiveQty', align: 'center', width: '10%', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '坏件数量', dataIndex: 'badQty', align: 'center', width: '10%', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '良品数量', dataIndex: 'goodQty', width: '10%', align: 'center', scopedSlots: { customRender: 'goodQty' } },
        { title: '返库数量', dataIndex: 'backStockQty', width: '10%', align: 'center', scopedSlots: { customRender: 'backStockQty' } },
        { title: '退货原因', dataIndex: 'returnReasonDictValue', width: '20%', align: 'center', customRender: function (text) { return text || '--' } }
      ]
      return arr
    }
  },
  methods: {
    // 表格选中项
    rowSelectionFun (obj) {
      this.rowSelectionInfo = obj || null
    },
    //  返回
    handleBack () {
      this.$router.push({ name: 'receiveCheckList' })
    },
    // 批量设置
    plSetQty (type) {
      const _this = this
      if (!_this.rowSelectionInfo || (_this.rowSelectionInfo && _this.rowSelectionInfo.selectedRowKeys.length < 1)) {
        _this.$message.warning('请先选择产品！')
        return
      }
      this.actionType = type
      this.openTypeModal = true
    },
    // 批量修改数量
    plconfirm (val) {
      const _this = this
      const obj = []
      const hasError = _this.rowSelectionInfo.selectedRows.filter(item => item.backStockQty > 0)
      _this.rowSelectionInfo && _this.rowSelectionInfo.selectedRows.map(item => {
        // 批量设置良品
        if (this.actionType == 1) {
          const pa = {
            salesReturnDetailSn: item.salesReturnDetailSn,
            goodQty: val == 1 ? item.receiveQty : 0
          }
          // 如果批量修改良品数量为0,且返库数量又不是0的情况
          if (hasError.length && val == 0) {
            pa.backStockQty = 0
          }
          obj.push(pa)
        } else {
          // 批量设置返库
          obj.push({
            salesReturnDetailSn: item.salesReturnDetailSn,
            backStockQty: val == 1 ? item.goodQty : 0
          })
        }
      })
      console.log(obj)
      // 如果批量修改良品数量为0
      if (val == 0 && this.actionType == 1 && hasError.length) {
        this.$confirm({
          title: '提示',
          content: '是否将返库数量同样设置为0？',
          centered: true,
          closable: true,
          onOk () {
            _this.plSave(obj)
          }
        })
      } else {
        _this.plSave(obj)
      }
    },
    plSave (obj) {
      const fun = this.actionType == 1 ? updateBatchGoodQty : updateBatchBackStockQty
      this.spinning = true
      fun(obj).then(res => {
        if (res.status == 200) {
          this.$refs.table.clearSelected()
          this.$refs.table.refresh()
          this.$message.success(res.message)
        }
        this.spinning = false
        this.openTypeModal = false
      })
    },
    // 修改良品数量
    updateGoodQty (val, record) {
      if (record.backStockQty > record.goodQty) {
        this.$message.info('返库数量不能大于良品数量')
        record.goodQty = record.goodQtyBackups
        return
      }
      //  光标移出，值发生改变再调用编辑接口
      if (val && val != record.goodQtyBackups) {
        this.spinning = true
        updateBatchGoodQty([{
          salesReturnDetailSn: record.salesReturnDetailSn,
          goodQty: record.goodQty
        }]).then(res => {
          if (res.status == 200) {
            this.resetSearchForm(false)
            this.$message.success(res.message)
            record.goodQtyBackups = record.goodQty
          } else {
            record.goodQty = record.goodQtyBackups
          }
          this.spinning = false
        })
      } else {
        record.goodQty = record.goodQtyBackups
      }
    },
    // 修改返库数量
    updateBackStockQty (val, record) {
      if (record.backStockQty > record.goodQty) {
        this.$message.info('返库数量不能大于良品数量')
        record.backStockQtyBackups = record.backStockQty
        return
      }
      //  光标移出，值发生改变再调用编辑接口
      if (val && val != record.backStockQtyBackups) {
        this.spinning = true
        updateBatchBackStockQty([{
          salesReturnDetailSn: record.salesReturnDetailSn,
          backStockQty: record.backStockQty
        }]).then(res => {
          if (res.status == 200) {
            this.resetSearchForm(false)
            this.$message.success(res.message)
            record.backStockQtyBackups = record.backStockQty
          } else {
            record.backStockQty = record.backStockQtyBackups
          }
          this.spinning = false
        })
      } else {
        record.backStockQty = record.backStockQtyBackups
      }
    },
    // 获取单据详细
    getOrderDetail () {
      salesReturnDetail({ sn: this.orderSn }).then(res => {
        this.ordeDetail = res.data || null
      })
    },
    //  重置
    resetSearchForm (flag) {
      if (flag) {
        this.rowSelectionInfo = null
        this.$refs.table.clearSelected()
        this.queryParam = {
          productCode: '',
          productName: ''
        }
      }
      this.$refs.table.refresh(!!flag)
    },
    searchForm () {
      this.$refs.table.refresh(true)
      this.$refs.table.clearSelected()
    },
    // 提交品检
    handleSubmit () {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '提交后将无法修改，确认提交吗？',
        centered: true,
        closable: true,
        onOk () {
          _this.spinning = true
          salesReturnCheck({ salesReturnBillSn: _this.orderSn }).then(res => {
            if (res.status == 200) {
              _this.handleBack()
              _this.$message.success(res.message)
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
      this.orderSn = this.$route.params.sn
      this.getOrderDetail()
    },
    setTableH () {
      this.tableHeight = window.innerHeight - 390
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.$refs.table.refresh(true)
      this.pageInit()
    }
  },
  activated () {
    this.$refs.table.refresh()
    this.pageInit()
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>

<style lang="less">
  .salesReturnCheck-wrap{
    position: relative;
    height: 100%;
    padding-bottom: 51px;
    box-sizing: border-box;
    >.ant-spin-nested-loading{
      height: 100%;
    }
    .footer-btn{
      text-align: center;
    }
    .salesReturnCheck-cont{
      margin-top: 10px;
      .sTable{
        margin-top: 10px;
      }
      .total-bar{
        display: flex;
        align-items: center;
        justify-content: space-between;
        > div{
          &:last-child{
            display: flex;
            align-items: center;
            justify-content: space-between;
            > div{
              padding: 0 10px;
            }
          }
        }
      }
    }
    .redBg-row{
      background-color: #f5beb4;
    }
    .orgBg-row{
      background-color: #fffca2;
    }
  }
</style>
