<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">
        <div>
          <a-button type="primary" :loading="loading" class="button-error" @click="backStock">批量返库</a-button>
        </div>
        <!-- 已选配件列表 -->
        <s-table
          class="sTable"
          ref="table"
          :style="{ height: tableHeight+84.5+'px' }"
          size="small"
          :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onChange, onSelect: onSelectChange, onSelectAll: onSelectAllChange }"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data="loadData"
          :scroll="{ y: tableHeight }"
          :defaultLoadData="false"
          bordered>
          <!-- 返库数量 -->
          <template slot="backStockQty" slot-scope="text, record">
            <a-input-number
              id="salesReturn-backStockQty"
              size="small"
              v-model="record.backStockQty"
              :precision="0"
              :min="0"
              :max="record.qty"
              placeholder="请输入"
              @blur="e => onCellBlur(e.target.value, record)"
              style="width: 100%;" />
          </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 queryPart from './queryPart.vue'
import { salesReturnDetail, salesReturnCheck } from '@/api/salesReturn'
import {
  salesReturnDetailList,
  updateBackStockQty
} from '@/api/salesReturnDetail'
export default {
  name: 'SalesReturnEdit',
  components: {
    STable,
    VSelect,
    queryPart
  },
  data () {
    return {
      spinning: false,
      tableHeight: 0, // 表格高度
      orderId: null,
      orderSn: null,
      buyerSn: null,
      disabled: false,
      isInster: false, // 是否正在添加产品
      ordeDetail: { discountAmount: 0 },
      loading: false,
      selectedRowKeys: [], // Check here to configure the default column
      selectedRows: [],
      // 已选产品
      dataSource: [],
      productForm: {
        salesReturnBillSn: ''
      },
      chooseLoadData: [],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        // 查询总计
        this.productForm.salesReturnBillSn = this.$route.params.sn
        return salesReturnDetailList(Object.assign(parameter, this.productForm)).then(res => {
          const 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].backStockQtyBackups = data.list[i].backStockQty
          }
          this.disabled = false
          this.chooseLoadData = data.list
          return data
        })
      }
    }
  },
  computed: {
    columns () {
      const arr = [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '产品编码', dataIndex: 'productEntity.code', align: 'center', width: '23%', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'productEntity.name', width: '25%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '退货数量', dataIndex: 'qty', 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: 'productEntity.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 : '--') } }
      ]
      if (this.$hasPermissions('B_isShowPrice')) { //  售价权限
        arr.splice(7, 0, { title: '售价', dataIndex: 'price', align: 'center', width: '10%', customRender: function (text) { return ((text || text == 0) ? text : '--') } })
      }
      return arr
    }
  },
  methods: {
    onChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
    },
    onSelectChange (record, selected, selectedRows, nativeEvent) {
      if (selected) { //  选择
        this.selectedRows.push(record)
      } else { //  取消
        this.selectedRows = selectedRows
      }
    },
    // 本页全选/取消全选
    onSelectAllChange (selected, selectedRows, changeRows) {
      const _this = this
      if (selected) { //  选择
        this.selectedRows = [...this.selectedRows, ...changeRows]
      } else { //  取消
        const arrId = []
        this.selectedRows.map((item, index) => {
          this.selectedRows.map((subItem, ind) => {
            if (item.id == subItem.id) {
              arrId.push(index)
            }
          })
        })
        arrId.map((item, index) => {
          _this.selectedRows = _this.selectedRows.slice(item, item + 1)
        })
      }
    },
    //  返回
    handleBack () {
      this.$router.push({ path: '/salesManagement/salesReturn/list', query: { closeLastOldTab: true } })
    },
    // 批量返库
    backStock () {
      const _this = this
      if (_this.selectedRowKeys.length < 1) {
        _this.$message.warning('请在选择产品！')
        return
      }
      this.$confirm({
        title: '提示',
        content: '确认要批量返库吗？',
        centered: true,
        onOk () {
          const obj = []
          _this.selectedRows.map(item => {
            obj.push({
              salesReturnDetailSn: item.salesReturnDetailSn,
              backStockQty: item.qty
            })
          })
          _this.submitCheck(obj)
        }
      })
    },
    // 已选产品  blur
    onCellBlur (val, record) {
      //  光标移出，值发生改变再调用编辑接口
      if (val && val != record.backStockQtyBackups) {
        this.submitCheck([{
          salesReturnDetailSn: record.salesReturnDetailSn,
          backStockQty: record.backStockQty
        }])
      } else {
        record.backStockQty = record.backStockQtyBackups
      }
    },
    // 品检
    submitCheck (data) {
      this.loading = true
      this.spinning = true
      updateBackStockQty(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 () {
      salesReturnDetail({ sn: this.orderSn }).then(res => {
        this.ordeDetail = res.data || null
      })
    },
    //  重置
    resetSearchForm (flag) {
      this.$refs.table.refresh(!!flag)
      this.getOrderDetail()
    },
    // 提交销售单
    handleSubmit () {
      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.buyerSn = this.$route.params.buyerSn
      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>
