<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.targetName || '--' }} ({{ ordeDetail&&ordeDetail.grabFlag==1 ? '抓单' : '不抓单' }})</span>
        </template>
      </a-page-header>
      <a-card size="small" :bordered="false" class="salesReturnCheck-cont">
        <div>
          <a-button type="primary" :loading="loading" class="button-info" @click="backStock('BATCH_BACK','批量返库')">批量返库</a-button>
          <a-button v-if="grabFlag==1" type="default" :loading="loading" class="button-info" @click="backStock('BATCH_BAD','批量坏件')">批量坏件</a-button>
        </div>
        <!-- 已选配件列表 -->
        <s-table
          class="sTable"
          ref="table"
          :style="{ height: tableHeight+84.5+'px' }"
          size="small"
          :rowKey="(record) => record.id"
          :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"
              :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="salesReturn-handleSubmit">提交</a-button>
    </div>
  </div>
</template>

<script>
import { STable, VSelect } from '@/components'
import {
  allocReturnDetailQueryPage,
  allocateReturnQueryBySn,
  allocateReturnSubmit,
  allocateReturnCheck
} from '@/api/allocateReturn'
export default {
  name: 'SalesReturnEdit',
  components: {
    STable,
    VSelect
  },
  data () {
    return {
      spinning: false,
      tableHeight: 0, // 表格高度
      orderSn: null,
      grabFlag: null,
      disabled: false,
      isInster: false, // 是否正在添加产品
      ordeDetail: { discountAmount: 0 },
      loading: false,
      // 已选产品
      dataSource: [],
      productForm: {
        allocateReturnSn: ''
      },
      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].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 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 || '--' } },
        { title: '退货单价', dataIndex: 'price', align: 'center', width: '10%', customRender: function (text) { return ((text || text == 0) ? 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 || '--' } })
      }
      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.resetSearchForm(true)
          this.$message.success(res.message)
        }
        this.loading = false
        this.spinning = false
      })
    },
    // 重置列表
    resetForm () {
      this.$refs.table.refresh(true)
    },
    // 获取单据详细
    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
      allocateReturnSubmit({ 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: 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;
            }
          }
        }
      }
    }
  }
</style>
