<template>
  <div>
    <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-spin :spinning="spinning" tip="Loading...">
      <a-card size="small" :bordered="false" class="pages-wrap">
        <div>
          <a-button type="primary" :loading="loading" class="button-error" @click="backStock">批量返库</a-button>
        </div>
        <!-- 已选配件列表 -->
        <s-table
          class="sTable"
          ref="table"
          size="small"
          :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onChange, onSelect: onSelectChange, onSelectAll: onSelectAllChange }"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data="loadData"
          :scroll="{ x: 1500, y: 300 }"
          bordered>
          <!-- 返库数量 -->
          <template slot="backStockQty" slot-scope="text, record">
            <editable-cell
              size="small"
              :text="record.backStockQty"
              :max="record.qty"
              :min="0"
              :precision="0"
              @change="onCellChange(record.id, 'backStockQty', $event)" />
          </template>
        </s-table>
      </a-card>
      <a-affix :offset-bottom="0">
        <div
          style="text-align: center;width: 100%;background-color: #fff;padding: 0 0 40px;box-shadow: 0 0 20px #dcdee2;">
          <a-button
            size="large"
            style="width: 150px;"
            type="primary"
            class="button-primary"
            @click="handleSubmit()"
            id="salesReturn-handleSubmit">提交</a-button>
        </div>
      </a-affix>
    </a-spin>
  </div>
</template>

<script>
import { STable, VSelect } from '@/components'
import queryPart from './queryPart.vue'
import EditableCell from '@/views/common/editInput.js'
import { salesReturnDetail, salesReturnCheck } from '@/api/salesReturn'
import {
  salesReturnDetailList,
  updateBackStockQty
} from '@/api/salesReturnDetail'
export default {
  name: 'SalesReturnEdit',
  components: {
    STable,
    VSelect,
    queryPart,
    EditableCell
  },
  data () {
    return {
      spinning: false,
      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: ''
      },
      // 表头
      columns: [
        { title: '序号', dataIndex: 'no', width: 80, align: 'center' },
        { title: '产品编码', dataIndex: 'productEntity.code', align: 'center', width: 160 },
        { title: '产品名称', dataIndex: 'productEntity.name', align: 'center', width: 200 },
        { title: '退货数量', dataIndex: 'qty', align: 'center', width: 150 },
        { title: '坏件数量', dataIndex: 'badQty', align: 'center', width: 150 },
        { title: '返库数量', dataIndex: 'backStockQty', width: 150, align: 'center', scopedSlots: { customRender: 'backStockQty' } },
        { title: '单位', dataIndex: 'productEntity.unit', align: 'center', customRender: function (text) { return text || '--' }, width: 100 },
        { title: '售价', dataIndex: 'price', customRender: function (text) { return '￥' + (text || 0) }, align: 'center', width: 150 }
      ],
      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
          }
          this.disabled = false
          this.chooseLoadData = data.list
          return data
        })
      }
    }
  },
  methods: {
    onChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
    },
    onSelectChange (record, selected, selectedRows, nativeEvent) {
      const _this = this
      if (selected) { //  选择
        this.selectedRows.push(record)
      } else { //  取消
        this.selectedRows.map((item, index) => {
          if (item.id == record.id) {
            _this.selectedRows.splice(index, 1)
          }
        })
      }
    },
    // 本页全选/取消全选
    onSelectAllChange (selected, selectedRows, changeRows) {
      const _this = this
      if (selected) { //  选择
        this.selectedRows = [...this.selectedRows, ...changeRows]
      } else { //  取消
        this.selectedRows.map((item, index) => {
          this.selectedRows.map((subItem, ind) => {
            if (item.id == subItem.id) {
              _this.selectedRows.splice(index, 1)
            }
          })
        })
      }
    },
    //  返回
    handleBack () {
      this.$router.push({ name: 'salesReturnList' })
    },
    // 批量返库
    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)
        }
      })
    },
    // 修改返库数量
    onCellChange (id, key, value) {
      const chooseLoadData = [...this.chooseLoadData]
      const row = chooseLoadData.find(item => item.id === id)
      if (row) {
        row[key] = Number(value)
        this.submitCheck([{
          salesReturnDetailSn: row.salesReturnDetailSn,
          backStockQty: row.backStockQty
        }])
      }
    },
    // 品检
    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
        }
      })
    }
  },
  mounted () {
    this.orderSn = this.$route.params.sn
    this.buyerSn = this.$route.params.buyerSn
    this.getOrderDetail()
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      console.log('beforeRouteEnter')
    })
  }
}
</script>

<style lang="less">
  .pages-wrap{
    margin-top: 15px;
    .sTable{
      margin-top: 15px;
    }
    .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>
