<template>
  <div class="waitDispatch-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" @back="handleBack" >
        <!-- 自定义的二级文字标题 -->
        <template slot="subTitle">
          <a id="waitDispatch-back-btn" href="javascript:;" @click="handleBack"><a-icon type="left" /> 返回列表</a>
          <span style="margin: 0 15px;color: #666;">客户名称：{{ detailData&&detailData.buyerName || '--' }}</span>
        </template>
      </a-page-header>
      <a-card size="small" :bordered="false" class="waitDispatch-cont">
        <!-- 查询配件列表 -->
        <queryPart
          ref="partQuery"
          :newLoading="isInster"
          @oneDispatch="oneDispatch"
          @cancelProduct="cancelProduct"
          @addProduct="insterProduct"></queryPart>
      </a-card>
      <a-card size="small" :bordered="false" class="waitDispatch-cont">
        <div slot="title">
          <div class="p-title">
            待下推产品
          </div>
        </div>
        <div style="margin: 0 0 10px 0;">
          <a-button
            type="danger"
            @click="delSalerDetailAll"
            :loading="delLoading"
            id="waitDispatch-del-all">批量移除</a-button>
        </div>
        <!-- 总计 -->
        <a-alert type="info" style="margin-bottom: 10px;">
          <div slot="message" class="total-bar">
            <div>
              本次下推款数：<strong>{{ totalData&&(totalData.totalCategory || totalData.totalCategory==0) ? totalData.totalCategory : '--' }}</strong>；
              本次下推数量：<strong>{{ totalData&&(totalData.totalQty || totalData.totalQty==0) ? totalData.totalQty : '--' }}</strong>；
            </div>
            <div>
            </div>
          </div>
        </a-alert>
        <!-- 已选配件列表 -->
        <s-table
          class="sTable"
          ref="table"
          size="small"
          :rowKey="(record) => record.id"
          :row-selection="{ columnWidth: 40 }"
          @rowSelection="rowSelectionFun"
          :columns="columns"
          :data="loadData"
          :showPagination="false"
          :scroll="{ y: 300 }"
          :defaultLoadData="false"
          bordered>
          <!-- 产品编码 -->
          <template slot="productCode" slot-scope="text, record">
            <a-badge count="促" v-if="record.promotionFlag == 1">
              <div style="padding-right: 15px;">{{ text }}</div>
            </a-badge>
            <span v-else>{{ text }}</span>
          </template>
          <!-- 本次下推数 -->
          <template slot="salesNums" slot-scope="text, record">
            <a-input-number
              id="salesReturn-qty"
              size="small"
              v-model="record.qty"
              :precision="0"
              :min="1"
              :max="record.surplusQty"
              placeholder="请输入"
              @blur="e => onCellBlur(e.target.value, record)"
              style="width: 100%;" />
          </template>
          <!-- 操作 -->
          <template slot="action" slot-scope="text, record">
            <a-button
              size="small"
              type="link"
              :loading="delLoading"
              class="button-error"
              @click="handleDel(record)"
            >移除</a-button>
          </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="handleDispatch()"
        :loading="loading"
        id="productInfoList-handleSubmit">下推</a-button>
    </div>
    <!-- 下推 -->
    <dsModal ref="dsModal" :openModal="showDsModal" @close="showDsModal=false" @ok="handleSubmit" />
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import queryPart from './queryPart.vue'
import dsModal from './dsModal.vue'
import { salesDetailBySn } from '@/api/sales'
import { salesDetailDispatchByOneKey, insertBatchOfWaitDispatch, salesDetailUpdateCancelQty } from '@/api/salesDetail'
import { deleteBatch, pushDown, waitDispatchDetailAllList, updateQty } from '@/api/waitDispatchDetail'
import { findBySalesBillSn } from '@/api/dispatch'
import { keys } from 'core-js/fn/array'
export default {
  name: 'WaitDispatch',
  mixins: [commonMixin],
  components: { STable, VSelect, queryPart, dsModal },
  data () {
    return {
      showDsModal: false,
      spinning: false,
      salesBillSn: null, // 销售单sn
      disabled: false, //  查询、重置按钮是否可操作
      isInster: false, // 是否正在添加产品
      delLoading: false, // 是否正在移除产品
      loading: false, // 是否下推中
      detailData: { discountAmount: 0, id: null, salesBillSn: '' }, // 订单基础数据
      dataSource: [],
      productForm: {
        dispatchBillSn: ''
      },
      // 表头
      columns: [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '产品编码', dataIndex: 'productEntity.code', scopedSlots: { customRender: 'productCode' }, width: '26%', align: 'center' },
        { title: '产品名称', dataIndex: 'productEntity.name', width: '29%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '出库仓库', dataIndex: 'dispatchBill.warehouseName', width: '8%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '待下推数量', dataIndex: 'surplusQty', width: '10%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '本次下推数', scopedSlots: { customRender: 'salesNums' }, width: '11%', align: 'center' },
        { title: '单位', dataIndex: 'productEntity.unit', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '10%', align: 'center' }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        // 查询统计
        return waitDispatchDetailAllList(Object.assign(parameter, this.productForm)).then(res => {
          let data
          if (res.status == 200) {
            data = res.data
            const no = 0
            for (var i = 0; i < data.length; i++) {
              data[i].no = no + i + 1
              data[i].qtyBackups = data[i].qty
            }
            this.disabled = false
            this.dataSource = data
          }
          return data
        })
      },
      totalData: null,
      rowSelectionInfo: null
    }
  },
  methods: {
    // 表格选中项
    rowSelectionFun (obj) {
      this.rowSelectionInfo = obj || null
    },
    // 统计查询
    getTotalData () {
      findBySalesBillSn({ salesBillSn: this.$route.params.salesBillSn }).then(res => {
        if (res.status == 200) {
          this.totalData = res.data || null
          if (res.data && Object.keys(res.data).length > 0) {
            this.productForm.dispatchBillSn = res.data.dispatchBillSn
            const _this = this
            this.$nextTick(() => {
              _this.$refs.table.refresh()
            })
          } else {
            this.dataSource = []
            this.$refs.table.clearTable()
          }
        } else {
          this.totalData = null
        }
      })
    },
    // 已选产品  blur
    onCellBlur (val, record) {
      const _this = this
      if (val && val != record.qtyBackups) {
        _this.spinning = true
        updateQty({
          dispatchBillDetailSn: record.dispatchBillDetailSn,
          qty: record.qty,
          salesBillSn: _this.salesBillSn,
          dispatchBillSn: _this.productForm.dispatchBillSn
        }).then(res => {
          if (res.status == 200) {
            _this.$refs.partQuery.resetCurForm()
            _this.$message.success(res.message)
            _this.spinning = false
            _this.resetSearchForm()
          } else {
            _this.spinning = false
          }
        })
      } else {
        record.qty = record.qtyBackups
      }
    },
    //  重置
    resetSearchForm () {
      this.getTotalData()
      this.getOrderDetail()
    },
    //  返回
    handleBack () {
      this.$router.push({ path: '/salesManagement/salesQuery/list', query: { closeLastOldTab: true } })
    },
    // 批量删除
    delSalerDetailAll () {
      const _this = this
      if (!_this.rowSelectionInfo || (_this.rowSelectionInfo && _this.rowSelectionInfo.selectedRowKeys.length < 1)) {
        _this.$message.warning('请在选择待下推产品！')
        return
      }
      const obj = []
      _this.rowSelectionInfo && _this.rowSelectionInfo.selectedRows.map(item => {
        if (_this.rowSelectionInfo && _this.rowSelectionInfo.selectedRowKeys.indexOf(item.id) != -1) {
          obj.push(item.dispatchBillDetailSn)
        }
      })
      this.$confirm({
        title: '提示',
        content: '确认要批量删除吗？',
        centered: true,
        closable: true,
        onOk () {
          _this.deleteFun(obj, 1)
        }
      })
    },
    // 删除产品
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认要删除吗？',
        centered: true,
        closable: true,
        onOk () {
          _this.deleteFun(row, 0)
        }
      })
    },
    // 移除操作
    deleteFun (row, type) {
      const _this = this
      _this.delLoading = true
      _this.spinning = true
      deleteBatch({
        dispatchBillSn: this.productForm.dispatchBillSn,
        dispatchBillDetailList : type == 0 ? [row.dispatchBillDetailSn] : row
      }).then(res => {
        if (res.status == 200) {
          _this.resetSearchForm()
          _this.$refs.partQuery.resetCurForm()
          if (type == 1) { //  批量操作
            _this.$refs.table.clearSelected() // 清空表格选中项
          } else if (type == 0) { //  单条
            const ind = _this.rowSelectionInfo && _this.rowSelectionInfo.selectedRowKeys.findIndex(item => item == row.id)
            _this.rowSelectionInfo && _this.rowSelectionInfo.selectedRowKeys.splice(ind, 1)
          }
          _this.$message.success(res.message)
          _this.spinning = false
        } else {
          _this.spinning = false
        }
        _this.delLoading = false
      })
    },
    // 添加产品
    insterProduct (list) {
      // 防止多次添加产品
      if (this.isInster) { return }
      this.saveNewProduct(list)
    },
    // 保存添加的产品到下推列表
    saveNewProduct (list) {
      this.$message.loading('正在添加产品...', 1)
      this.isInster = true
      this.spinning = true
      insertBatchOfWaitDispatch({
        salesBillDetailSnList: list,
        salesBillSn: this.salesBillSn
      }).then(res => {
        if (res.status == 200) {
          this.resetSearchForm()
          this.$refs.partQuery.resetCurForm()
          this.$message.success('添加成功', 2.5)
          this.spinning = false
        } else {
          this.spinning = false
        }
        this.isInster = false
      })
    },
    // 批量取消产品
    cancelProduct (list) {
      // 防止多次添加产品
      this.$message.loading('正在批量取消产品...', 1)
      this.isInster = true
      this.spinning = true
      salesDetailUpdateCancelQty(list).then(res => {
        if (res.status == 200) {
          this.resetSearchForm()
          this.$refs.partQuery.resetCurForm()
          this.$message.success(res.message, 2.5)
          this.spinning = false
        } else {
          this.spinning = false
        }
        this.isInster = false
      })
    },
    // 一键下推
    oneDispatch () {
      this.isInster = true
      this.spinning = true
      salesDetailDispatchByOneKey({ salesBillSn: this.$route.params.salesBillSn }).then(res => {
        if (res.status == 200) {
          this.resetSearchForm()
          this.$refs.partQuery.resetCurForm()
          this.spinning = false
        } else {
          this.spinning = false
        }
        this.isInster = false
      })
    },
    //  销售单详情
    getOrderDetail () {
      salesDetailBySn({ salesBillSn: this.$route.params.salesBillSn }).then(res => {
        if (res.status == 200) {
          this.detailData = res.data
          this.$refs.partQuery.pageInit(this.$route.params.salesBillSn, this.detailData)
        }
      })
    },
    // 提交下推
    handleDispatch () {
      if (this.dataSource.length) {
        this.showDsModal = true
        this.detailData.dispatchBillCount = this.totalData.dispatchBillCount
        this.detailData.receiverName = this.totalData.receiverName ? this.totalData.receiverName : ''
        this.detailData.receiverSn = this.totalData.receiverSn ? this.totalData.receiverSn : ''
        this.$refs.dsModal.setDetail(this.detailData)
      } else {
        this.$message.warning('请选择待下推产品')
      }
    },
    handleSubmit (data) {
      this.delLoading = true
      this.isInster = true
      this.loading = true
      this.spinning = true
      const params = Object.assign({ dispatchBillSn: this.productForm.dispatchBillSn }, data)
      pushDown(params).then(res => {
        if (res.status == 200) {
          this.handleBack()
          this.$message.success(res.message)
        }
        this.delLoading = false
        this.isInster = false
        this.loading = false
        this.spinning = false
      })
    },
    pageInit () {
      this.rowSelectionInfo = null
      // this.$refs.table.clearTable()
      this.$refs.partQuery.clearTable()
      this.salesBillSn = this.$route.params.salesBillSn
      this.getOrderDetail()
      this.getTotalData()
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
    }
  },
  activated () {
    // 如果是新页签打开或者进入新的子页（例：存在列表第2条数据编辑页页签时再打开第4条数据的编辑页），则重置当前页面
    if (this.$store.state.app.isNewTab || !this.$store.state.app.isNewSubTab) {
      this.pageInit()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>

<style lang="less">
  .waitDispatch-wrap{
    position: relative;
    height: 100%;
    padding-bottom: 51px;
    box-sizing: border-box;
    >.ant-spin-nested-loading{
      overflow-y: scroll;
      height: 100%;
    }
    .waitDispatch-cont{
      margin-top: 10px;
    }
    .p-title{
      font-size: 16px;
      font-weight: bold;
    }
    .p-notes{
      span{
        color: #FF9900;
      }
    }
    .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: #f5cdc8;
    }
  }

</style>
