<template>
  <div class="salesReturnReceive-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" class="salesReturnReceive-back" >
        <!-- 自定义的二级文字标题 -->
        <template slot="subTitle">
          <a id="salesReturnReceive-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="salesReturnReceive-cont">
        <a-form layout="inline" style="margin-bottom:10px;" @keyup.enter.native="searchForm">
          <a-form-item label="产品编码" prop="productCode">
            <a-input id="salesReturnReceive-productCode" v-model.trim="queryParam.productCode" placeholder="请输入产品编码" allowClear />
          </a-form-item>
          <a-form-item label="产品名称" prop="productName">
            <a-input id="salesReturnReceive-productName" v-model.trim="queryParam.productName" placeholder="请输入产品名称" allowClear />
          </a-form-item>
          <a-form-item>
            <a-button type="primary" @click="searchForm" :disabled="disabled" id="salesReturnReceive-refresh">查询</a-button>
            <a-button style="margin-left: 10px" @click="resetSearchForm" :disabled="disabled" id="salesReturnReceive-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="openModal = true">新增产品</a-button>
          <a-button
            type="primary"
            :loading="loading"
            @click="openGuideModal=true"
          >导入产品</a-button>
          <a-button style="margin-left:10px;" type="primary" ghost :loading="loading" @click="handlePlss">批量实收</a-button>
          <span style="margin-left:10px;" v-if="rowSelectionInfo&&rowSelectionInfo.selectedRowKeys&&rowSelectionInfo.selectedRowKeys.length">已选{{ rowSelectionInfo.selectedRowKeys.length }}项</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, getCheckboxProps:record =>({props: { disabled: record.addFlag == '1' }}) }"
          @rowSelection="rowSelectionFun"
          :columns="columns"
          :data="loadData"
          :pagination="{pageSizeOptions: ['50','100','200','300','400']}"
          :pageSize="50"
          :scroll="{ y: tableHeight }"
          :defaultLoadData="false"
          bordered>
          <!-- 申请退货数量 -->
          <template slot="initialQty" slot-scope="text, record">
            <a-input-number
              size="small"
              v-if="record.addFlag == '1'&&record.addType == 'WAREHOUSE_RECEIVE'"
              v-model="record.initialQty"
              :precision="0"
              :min="0"
              :max="99999999"
              @blur="e => onCellBlurInitialQty(e.target.value, record)"
              placeholder="请输入"
              style="width: 100%;" />
            <span v-else>{{ record.initialQty }}</span>
          </template>
          <!-- 仓库实收数量 -->
          <template slot="receiveQty" slot-scope="text, record">
            <a-input-number
              size="small"
              v-model="record.receiveQty"
              :precision="0"
              :min="0"
              :max="99999999"
              @blur="e => onCellBlurReceiveQty(e.target.value, record)"
              placeholder="请输入"
              style="width: 100%;" />
          </template>
          <!-- 退货原因 -->
          <template slot="returnReason" slot-scope="text, record">
            <returnReason
              v-model="record.returnReasonCode"
              :goodFlag="goodFlag"
              v-if="record.addFlag == '1'&&record.addType == 'WAREHOUSE_RECEIVE'"
              @change="e => onCellBlurReturnReason(e, record, 0)"></returnReason>
            <span v-else>{{ record.returnReason }}</span>
          </template>
          <!-- 备注 -->
          <template slot="remarks" slot-scope="text, record">
            <div @dblclick.stop>
              <a-input :maxLength="50" size="small" v-model="record.returnReasonRemarks" @blur="e => onCellBlurReturnReason(e, record, 1)" placeholder="请输入备注(最多50字符)"/>
            </div>
          </template>
          <!-- 操作 -->
          <template slot="action" slot-scope="text, record">
            <div>
              <a-button
                v-if="record.addFlag == '1'&&record.addType == 'WAREHOUSE_RECEIVE'"
                size="small"
                type="link"
                class="button-warning"
                @click="handleDel(record)"
              >删除</a-button>
            </div>
          </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>
    <!-- 添加产品 -->
    <chooseProductsModal
      ref="chooseProduct"
      :goodFlag="goodFlag"
      :isShowPrice="false"
      :openModal="openModal"
      :warehouseSn="ordeDetail?ordeDetail.warehouseSn:''"
      :buyerSn="$route.params.buyerSn"
      @close="openModal=false"
      @addProduct="addProduct"></chooseProductsModal>
    <!-- 导入产品 -->
    <importGuideModal :goodFlag="goodFlag == 'GOOD_PRODUCT_RETURN' ? 1 : 0" :params="{salesReturnBillSn: $route.params.sn}" :openModal="openGuideModal" @close="openGuideModal=false" @ok="importOk" />
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import chooseProductsModal from './chooseProductsModal.vue'
import returnReason from '@/views/common/returnReason'
import importGuideModal from './importGuideModal.vue'
import { salesReturnDetail, salesReturnReceive, salesReturnDetailBatchByReceive } from '@/api/salesReturn'
import {
  salesReturnDetailList, salesReturnDetailReceiveBatch, salesReturnDetailUpdateReceiveQty, salesReturnDetailUpdateReason, insertByReceive, deleteByReceiver
} from '@/api/salesReturnDetail'
export default {
  name: 'Receiving',
  mixins: [commonMixin],
  components: {
    STable,
    VSelect,
    chooseProductsModal,
    returnReason,
    importGuideModal
  },
  data () {
    return {
      openGuideModal: false,
      spinning: false,
      tableHeight: 0, // 表格高度
      orderSn: null,
      disabled: false,
      openModal: false, // 添加产品
      ordeDetail: null,
      loading: false,
      // 已选产品
      dataSource: [],
      productForm: {
        salesReturnBillSn: ''
      },
      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].receiveQtyBackups = data.list[i].receiveQty
              data.list[i].initialQtyBackups = data.list[i].initialQty
              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,
      queryParam: {
        productCode: '',
        productName: ''
      },
      returnReasonlist: []
    }
  },
  computed: {
    goodFlag () {
      return this.ordeDetail && this.ordeDetail.goodFlag || ''
    },
    columns () {
      const arr = [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '产品编码', dataIndex: 'productEntity.code', align: 'center', width: '10%', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'productEntity.name', width: '16%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '申请退货数量', dataIndex: 'initialQty', align: 'center', width: '8%', scopedSlots: { customRender: 'initialQty' } },
        { title: '仓库实收数量', dataIndex: 'receiveQty', align: 'center', width: '8%', scopedSlots: { customRender: 'receiveQty' } },
        { title: '单位', dataIndex: 'productEntity.unit', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        // { title: '退货单价', dataIndex: 'price', align: 'center', width: '10%', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '退货原因', dataIndex: 'returnReason', width: '19%', align: 'center', scopedSlots: { customRender: 'returnReason' } },
        { title: '备注', dataIndex: 'remarks', width: '19%', align: 'center', scopedSlots: { customRender: 'remarks' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '10%', align: 'center' }
      ]
      return arr
    }
  },
  methods: {
    // 表格选中项
    rowSelectionFun (obj) {
      this.rowSelectionInfo = obj || null
    },
    //  返回
    handleBack () {
      this.$router.push({ name: 'receiveCheckList' })
    },
    // 确认导入明细
    importOk (data) {
      this.spinning = true
      salesReturnDetailBatchByReceive({ detailList: data, salesReturnBillSn: this.orderSn }).then(res => {
        if (res.status == 200) {
          this.resetSearchForm()
          this.$message.info(res.message)
        }
        this.spinning = false
      })
    },
    // 添加产品
    addProduct (data) {
      const params = {
        'salesReturnBillSn': this.orderSn,
        'salesReturnBillNo': this.ordeDetail.salesReturnBillNo,
        'goodFlag': this.goodFlag,
        ...data
      }
      insertByReceive(params).then(res => {
        if (res.status == 200) {
          this.resetSearchForm(true)
          this.$message.info(res.message)
        }
        this.$refs.chooseProduct.resetLoading()
      })
    },
    // 删除产品
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认要删除吗？',
        centered: true,
        closable: true,
        onOk () {
          _this.loading = true
          _this.spinning = true
          deleteByReceiver({ salesReturnDetailSn: row.salesReturnDetailSn, salesReturnBillSn: _this.orderSn }).then(res => {
            if (res.status == 200) {
              _this.resetSearchForm(false)
            }
            _this.$message.info(res.message)
            _this.loading = false
            _this.spinning = false
          })
        }
      })
    },
    // 批量实收
    handlePlss () {
      const _this = this
      const snList = []
      _this.rowSelectionInfo && _this.rowSelectionInfo.selectedRows.map(item => {
        snList.push(item.salesReturnDetailSn)
      })
      if (snList.length == 0) {
        _this.$message.warning('请先选择产品！')
        return
      }
      _this.$confirm({
        title: '提示',
        content: '确认要批量实收吗？',
        centered: true,
        onOk () {
          _this.loading = true
          _this.spinning = true
          salesReturnDetailReceiveBatch(snList).then(res => {
            if (res.status == 200) {
              _this.$refs.table.clearSelected()
              _this.resetSearchForm(false)
              _this.$message.success(res.message)
            }
            _this.loading = false
            _this.spinning = false
          })
        }
      })
    },
    // 申请退货数量修改
    onCellBlurInitialQty (val, record) {
      //  光标移出，值发生改变再调用编辑接口
      if (val && val != record.initialQtyBackups) {
        this.loading = true
        this.spinning = true
        salesReturnDetailUpdateReceiveQty({
          salesReturnDetailSn: record.salesReturnDetailSn,
          initialQty: val
        }).then(res => {
          if (res.status == 200) {
            this.resetSearchForm(false)
            this.$message.success(res.message)
          } else {
            record.initialQty = record.initialQtyBackups
          }
          this.loading = false
          this.spinning = false
        })
      } else {
        record.initialQty = record.initialQtyBackups
      }
    },
    // 仓库实收数量修改
    onCellBlurReceiveQty (val, record) {
      //  光标移出，值发生改变再调用编辑接口
      if (val && val != record.receiveQtyBackups) {
        this.loading = true
        this.spinning = true
        salesReturnDetailUpdateReceiveQty({
          salesReturnDetailSn: record.salesReturnDetailSn,
          receiveQty: val
        }).then(res => {
          if (res.status == 200) {
            this.resetSearchForm(false)
            this.$message.success(res.message)
          } else {
            record.receiveQty = record.receiveQtyBackups
          }
          this.loading = false
          this.spinning = false
        })
      } else {
        record.receiveQty = record.receiveQtyBackups
      }
    },
    // 修改退货原因
    onCellBlurReturnReason (val, record, type) {
      const params = {
        salesReturnDetailSn: record.salesReturnDetailSn,
        goodFlag: this.goodFlag
      }
      // 退货原因
      if (type == 0) {
        const rows = this.returnReasonlist.find(item => item.code == val)
        params.returnReasonCode = val || ''
        params.returnReason = rows ? rows.dispName : ''
      } else {
        // 备注
        params.returnReasonRemarks = val.target.value
        if (params.returnReasonRemarks == record.bakReamrks) {
          return
        }
      }

      this.loading = true
      this.spinning = true
      salesReturnDetailUpdateReason(params).then(res => {
        if (res.status == 200) {
          this.resetSearchForm(false)
          this.$message.success(res.message)
        } else {
          record.returnReason = record.returnReasonBackups
        }
        this.loading = false
        this.spinning = false
      })
    },
    // 获取单据详细
    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]
        }
      })
    },
    // 审核销售单
    handleSubmit () {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '提交后将进入品检环节，确认提交吗？',
        centered: true,
        closable: true,
        onOk () {
          _this.spinning = true
          salesReturnReceive({ salesReturnBillSn: _this.orderSn }).then(res => {
            if (res.status == 200) {
              _this.handleBack()
              _this.$message.success(res.message)
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    //  重置
    resetSearchForm (flag) {
      if (flag) {
        this.queryParam.productName = ''
        this.queryParam.productCode = ''
        this.rowSelectionInfo = null
        this.$refs.table.clearSelected()
      }
      this.$refs.table.refresh(flag)
      this.getOrderDetail()
    },
    searchForm () {
      this.$refs.table.refresh(true)
      this.$refs.table.clearSelected()
    },
    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">
  .salesReturnReceive-wrap{
    position: relative;
    height: 100%;
    padding-bottom: 51px;
    box-sizing: border-box;
    >.ant-spin-nested-loading{
      height: 100%;
    }
    .footer-btn{
      text-align: center;
    }
    .salesReturnReceive-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>
