<template>
  <div class="transferReturnCheck-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" class="transferReturnCheck-back" >
        <!-- 自定义的二级文字标题 -->
        <template slot="subTitle">
          <a id="transferReturnCheck-back-btn" href="javascript:;" @click="handleBack"><a-icon type="left" /> 返回列表</a>
          <span style="margin: 0 15px;color: #666;">调拨退货对象名称：{{ ordeDetail&&ordeDetail.targetName || '--' }} ({{ ordeDetail&&ordeDetail.grabFlag==1 ? '抓单' : '不抓单' }})</span>
        </template>
      </a-page-header>
      <a-card size="small" :bordered="false" class="salesReturnCheck-cont">
        <div>
          <!-- 操作按钮 -->
          <a-button type="primary" id="transferReturnCheck-backStock" :loading="loading" class="button-info" @click="backStock('BATCH_BACK','批量返库')">批量返库</a-button>
          <a-button
            v-if="grabFlag==1"
            id="transferReturnCheck-badStock"
            type="default"
            :loading="loading"
            style="margin-right: 15px;"
            @click="backStock('BATCH_BAD','批量坏件')">批量坏件</a-button>
          <span>已选 {{ rowSelectionInfo&&rowSelectionInfo.selectedRows.length }} 项</span>
        </div>
        <!-- 已选配件列表 -->
        <s-table
          class="sTable"
          ref="table"
          :style="{ height: tableHeight+84.5+'px' }"
          size="small"
          rowKeyName="ids"
          :rowKey="record => record.ids"
          :row-selection="{ columnWidth: 40 }"
          @rowSelection="rowSelectionFun"
          :columns="columns"
          :data="loadData"
          :scroll="{ y: tableHeight }"
          :defaultLoadData="false"
          bordered>
          <!-- 返库数量 -->
          <template slot="backStockQty" slot-scope="text, record">
            <a-input-number
              v-if="grabFlag==0"
              size="small"
              v-model="record.backStockQty"
              :precision="0"
              :min="0"
              :id="'transferReturnCheck-returnQty'+record.ids"
              :max="record.returnQty"
              placeholder="请输入"
              @blur="e => onCellBlur(e.target.value, record)"
              style="width: 100%;" />
            <span v-else>{{ record.backStockQty }}</span>
          </template>
        </s-table>
      </a-card>
    </a-spin>
    <div class="affix-cont">
      <a-button
        size="large"
        style="padding: 0 60px;"
        :disabled="spinning"
        type="primary"
        class="button-primary"
        @click="handleSubmit()"
        id="transferReturnCheck-handleSubmit">提交</a-button>
    </div>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
// 组件
import { STable, VSelect } from '@/components'
import { allocReturnDetailQueryPage, allocateReturnQueryBySn, allocateReturnCheckSubmit, allocateReturnCheck } from '@/api/allocateReturn'
export default {
  name: 'TransferReturnCheck',
  mixins: [commonMixin],
  components: { STable, VSelect },
  data () {
    return {
      spinning: false,
      tableHeight: 0, // 表格高度
      orderSn: null, // 调拨退货sn
      grabFlag: null, // 是否抓单 0否 1是
      disabled: false, // 查询、重置按钮是否可操作
      isInster: false, // 是否正在添加产品
      ordeDetail: {
        discountAmount: 0 // 折扣金额
      }, // 单据详细数据
      loading: false, // 操作按钮加载状态
      dataSource: [], // 已选产品
      // 产品信息数据
      productForm: {
        allocateReturnSn: '' // 调拨退货sn
      },
      chooseLoadData: [], // 已选列表数据
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        // 获取列表数据 有分页
        this.productForm.allocateReturnSn = this.$route.params.sn
        return allocReturnDetailQueryPage(Object.assign(parameter, this.productForm)).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].ids = data.list[i].no + '-' + data.list[i].productSn
              data.list[i].badQty = (data.list[i].badQty || data.list[i].badQty == 0) ? data.list[i].badQty : data.list[i].returnQty
              data.list[i].backStockQty = data.list[i].backStockQty || 0
              data.list[i].backStockQtyBackups = data.list[i].backStockQty
            }
            this.disabled = false
            this.chooseLoadData = data.list
          }
          return data
        })
      },
      rowSelectionInfo: null// 已选数据
    }
  },
  computed: {
    // 表头
    columns () {
      const _this = this
      const arr = [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '产品编码', dataIndex: 'product.code', align: 'center', width: '23%', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'product.name', width: '25%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '退货数量', dataIndex: 'returnQty', 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: 'backStockQty', width: '10%', align: 'center', scopedSlots: { customRender: 'backStockQty' } },
        { title: '单位', dataIndex: 'product.unit', width: '8%', align: 'center', customRender: function (text) { return text || '--' } }
      ]
      console.log(this.grabFlag)
      if (this.grabFlag == 1) { //  抓单
        arr.splice(1, 0, { title: '调拨单号', dataIndex: 'allocateNo', width: '12%', align: 'center', customRender: function (text) { return text || '--' } })
      }
      if (this.$hasPermissions('M_transferReturnCheck_salesPrice')) {
        arr.splice(this.grabFlag == 1 ? 8 : 7, 0, { title: '退货单价', dataIndex: 'price', align: 'right', width: '10%', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      }
      return arr
    }
  },
  methods: {
    // 表格选中项
    rowSelectionFun (obj) {
      this.rowSelectionInfo = obj || null
    },
    //  返回列表
    handleBack () {
      this.$router.push({ name: 'transferReturnList', query: { closeLastOldTab: true } })
    },
    // 批量返库
    backStock (type, msg) {
      const _this = this
      if (!_this.rowSelectionInfo || (_this.rowSelectionInfo && _this.rowSelectionInfo.selectedRowKeys.length < 1)) {
        _this.$message.warning('请先选择产品！')
        return
      }
      this.$confirm({
        title: '提示',
        content: '确认要' + msg + '吗？',
        centered: true,
        onOk () {
          const obj = []
          _this.rowSelectionInfo && _this.rowSelectionInfo.selectedRows.map(item => {
            // 抓单
            if (_this.grabFlag == 1) {
              obj.push({
                allocateSn: item.allocateSn,
                productSn: item.productSn,
                price: item.price
              })
            } else {
              obj.push({
                allocateReturnDetailSn: item.allocateReturnDetailSn
              })
            }
          })
          _this.submitCheck(obj, type)
        }
      })
    },
    // 不抓单，修改返库数量
    onCellBlur (val, record) {
      //  光标移出，值发生改变再调用编辑接口
      if (val && val != record.backStockQtyBackups) {
        this.submitCheck([{
          allocateReturnDetailSn: record.allocateReturnDetailSn,
          backStockQty: record.backStockQty
        }], 'CUSTOM')
      } else {
        record.backStockQty = record.backStockQtyBackups
      }
    },
    // 修改坏件或退货数量
    submitCheck (data, allocateCheckType) {
      this.loading = true
      this.spinning = true
      allocateReturnCheck({
        allocateReturnSn: this.orderSn,
        allocateCheckType: allocateCheckType,
        list: data
      }).then(res => {
        if (res.status == 200) {
          this.$refs.table.clearSelected()
          this.resetSearchForm(false)
          this.$message.success(res.message)
        }
        this.loading = false
        this.spinning = false
      })
    },
    // 获取单据详细
    getOrderDetail () {
      allocateReturnQueryBySn({ allocateReturnSn: this.orderSn }).then(res => {
        this.ordeDetail = res.data || null
      })
    },
    //  重置
    resetSearchForm (flag) {
      this.$refs.table.refresh(!!flag)
      this.getOrderDetail()
    },
    // 品检提交
    handleSubmit () {
      this.spinning = true
      allocateReturnCheckSubmit({ allocateReturnSn: 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.grabFlag = this.$route.params.grabFlag
      this.$refs.table.clearTable()
      this.getOrderDetail()
    },
    // 计算表格高度
    setTableH () {
      this.tableHeight = window.innerHeight - 340
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.$refs.table.refresh(true)
      this.pageInit()
    }
  },
  activated () {
    // 如果是新页签打开或者进入新的子页（例：存在列表第2条数据编辑页页签时再打开第4条数据的编辑页），则重置当前页面
    if (this.$store.state.app.isNewTab || !this.$store.state.app.isNewSubTab) {
      this.$refs.table.refresh(true)
      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{
      overflow-y: scroll;
      height: 100%;
    }
    .salesReturnCheck-cont{
      margin-top: 6px;
      .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;
            }
          }
        }
      }
    }
  }
</style>
