<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>
          <span style="margin: 0 10px;color: #666;">
            退货类别：{{ ordeDetail&&ordeDetail.goodFlagDictValue }}
          </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" @click="searchForm" :disabled="disabled" id="salesReturnCheck-refresh">查询</a-button>
            <a-button style="margin-left: 10px" @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" ghost class="button-info" :loading="loading" @click="plSetQty(1)">批量设置良品数量</a-button>
          <a-button type="primary" ghost class="button-info" style="margin-left:5px;" :loading="loading" @click="plSetQty(2)">批量设置返库数量</a-button>
          <a-button type="primary" ghost style="margin-left:5px;" :loading="loading" @click="openPlSetReason">批量设置退货原因</a-button>
          <span style="margin-left:10px;" v-if="selNums">已选{{ selNums }}项</span>
          <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"
          :pagination="{pageSizeOptions: ['50','100','200','300','400']}"
          :pageSize="50"
          :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>
          <!-- 退货原因 -->
          <template slot="returnReason" slot-scope="text, record">
            <returnReason v-model="record.returnReasonCode" @change="e => updateReason(e, record, 0)"></returnReason>
          </template>
          <!-- 备注 -->
          <template slot="remarksInfo" slot-scope="text, record">
            <a-input
              size="small"
              v-model.trim="record.returnReasonRemarks"
              @blur="e => updateReason(e, record, 1)"
              :maxLength="50"
              placeholder="请输入备注信息(最多50字符)"/>
          </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>
    <!-- 批量设置退货原因 -->
    <commonModal modalTit="批量设置退货原因" :openModal="showPlModal" @cancel="showPlModal=false" @ok="setPlReturnReason">
      <div style="text-align: left;">
        <div style="line-height: 24px;">
          <div><span style="color:red;">*</span>退货原因</div>
          <div><returnReason size="large" v-model="plReturnReason"></returnReason></div>
        </div>
        <div style="line-height: 24px;margin-top:10px;">
          <a-checkbox :checked="showEditRemarks" @change="e => showEditRemarks=!showEditRemarks">是否设置备注</a-checkbox>
        </div>
        <div style="line-height: 24px;margin-top:10px;" v-if="showEditRemarks">
          <div>备注</div>
          <div><a-input size="large" :maxLength="50" placeholder="请输入备注(最多50字符)" v-model="plReturnRemark"></a-input></div>
        </div>
      </div>
    </commonModal>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import commonModal from '@/views/common/commonModal.vue'
import returnReason from '@/views/common/returnReason'
import { salesReturnDetail, salesReturnCheck } from '@/api/salesReturn'
import { salesReturnDetailList, updateBatchBackStockQty, updateBatchGoodQty, salesReturnDetailSetReason, salesReturnDetailUpdateReason } from '@/api/salesReturnDetail'
import chooseTypeModal from './chooseTypeModal.vue'
export default {
  name: 'SalesReturnCheck',
  mixins: [commonMixin],
  components: {
    STable,
    VSelect,
    chooseTypeModal,
    returnReason,
    commonModal
  },
  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: [],
      labelCol: { span: 8 },
      wrapperCol: { span: 14 },
      // 加载数据方法 必须为 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
              data.list[i].returnReasonBackups = data.list[i].returnReason
              data.list[i].bakReamrks = data.list[i].returnReasonRemarks
            }
            this.disabled = false
            this.chooseLoadData = data.list
          }
          return data
        })
      },
      rowSelectionInfo: null,
      plReturnReason: undefined,
      plReturnRemark: undefined,
      showPlModal: false,
      showEditRemarks: false,
      returnReasonlist: []
    }
  },
  watch: {
    showPlModal (newValue, oldValue) {
      if (!newValue) {
        this.plReturnReason = undefined
        this.plReturnRemark = undefined
        this.showEditRemarks = false
      }
    }
  },
  computed: {
    goodFlag () {
      return this.ordeDetail && this.ordeDetail.goodFlag || ''
    },
    selNums () {
      return this.rowSelectionInfo && this.rowSelectionInfo.selectedRowKeys.length || 0
    },
    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: 'initialQty', 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: 'returnReason', width: '20%', align: 'center', scopedSlots: { customRender: 'returnReason' } },
        { title: '备注', dataIndex: ' remarksInfo', width: '20%', align: 'center', scopedSlots: { customRender: 'remarksInfo' } }
      ]
      return arr
    }
  },
  methods: {
    // 表格选中项
    rowSelectionFun (obj) {
      this.rowSelectionInfo = obj || null
    },
    //  返回
    handleBack () {
      this.$router.push({ name: 'receiveCheckList' })
    },
    // 批量设置
    plSetQty (type) {
      const _this = this
      if (!this.selNums) {
        _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
      })
    },
    // 批量设置退货原因
    openPlSetReason () {
      if (this.selNums) {
        this.showPlModal = true
      } else {
        this.$message.warning('请先选择产品！')
      }
    },
    setPlReturnReason () {
      if (!this.plReturnReason) {
        this.$message.warning('请选择退货原因！')
      } else {
        this.spinning = true
        const snList = []
        const arr = this.rowSelectionInfo && this.rowSelectionInfo.selectedRows || []
        const rows = this.returnReasonlist.find(item => item.code == this.plReturnReason)
        arr.map(item => {
          snList.push(item.salesReturnDetailSn)
        })
        salesReturnDetailSetReason({
          salesReturnBillDetailSnList: snList,
          salesReturnBillSn: this.orderSn,
          returnReason: rows ? rows.dispName : '',
          returnReasonCode: this.plReturnReason,
          returnReasonRemarks: this.showEditRemarks ? this.plReturnRemark || '' : undefined,
          goodFlag: rows.lookupCode
        }).then(res => {
          if (res.status == 200) {
            this.showPlModal = false
            this.$refs.table.clearSelected()
            this.$refs.table.refresh()
          }
          this.spinning = false
        })
      }
    },
    // 修改退货原因
    updateReason (val, record, type) {
      const params = {
        salesReturnDetailSn: record.salesReturnDetailSn
      }
      // 退货原因
      if (type == 0) {
        const rows = this.returnReasonlist.find(item => item.code == val)
        params.returnReasonCode = val || ''
        params.returnReason = rows ? rows.dispName : ''
        params.goodFlag = rows.lookupCode
      } else {
        // 备注
        params.returnReasonRemarks = val.target.value
        if (params.returnReasonRemarks == record.bakReamrks) {
          return
        }
      }
      this.spinning = true
      salesReturnDetailUpdateReason(params).then(res => {
        if (res.status == 200) {
          this.$refs.table.refresh()
          this.$message.success(res.message)
        } else {
          row.returnReason = row.returnReasonBackups
        }
        this.spinning = 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.backStockQty = record.backStockQtyBackups
        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)
          } 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
        if (res.data) {
          this.returnReasonlist = [...this.$store.state.app.goodReturnReason, ...this.$store.state.app.defectiveReturnReason]
        }
      })
    },
    //  重置
    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>
