<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;font-weight: bold;">单号：{{ detailData&&detailData.salesBillNo }}</span>
          <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"
          :activeList="activeList"
          @cancelProduct="cancelProduct"
          @cancelAll="cancelAll"
          @convertPromoGifts="convertPromoGifts"
          @addProduct="insterProduct"
          @updateStockType="updateStockType"></queryPart>
      </a-card>
      <a-card size="small" :bordered="false" class="waitDispatch-cont">
        <div slot="title">
          <div class="p-title">
            待下推产品
          </div>
        </div>
        <!-- 已选配件列表 -->
        <detailProductList ref="waitProduct" @refashTable="refashTable" @upStockType="upStockType">
          <!-- 统计数据 -->
          <template slot="total">
            本次下推款数：<strong>{{ totalData&&(totalData.totalCategory || totalData.totalCategory==0) ? totalData.totalCategory : '--' }}</strong>；
            本次下推数量：<strong>{{ totalData&&(totalData.totalQty || totalData.totalQty==0) ? totalData.totalQty : '--' }}</strong>；
          </template>
        </detailProductList>
      </a-card>
    </a-spin>
    <div class="affix-cont">
      <a-button
        style="padding: 0 50px;"
        :disabled="spinning"
        type="primary"
        size="large"
        class="button-primary"
        @click="handleDispatch()"
        :loading="loading"
        id="waitDispatch-handleSubmit">下推</a-button>
    </div>
    <!-- 下推 -->
    <dsModal ref="dsModal" :openModal="showDsModal" @close="showDsModal=false" @ok="handleSubmit" />
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { VSelect } from '@/components'
import queryPart from './queryPart.vue'
import detailProductList from './detailProductList.vue'
import dsModal from './dsModal.vue'
// 接口
import { salesDetailBySn, salesPromoQueryList } from '@/api/salesNew'
import { insertBatchOfWaitDispatch, salesDetailUpdateCancelQty, salesDetailCancleOfAll, batchTransferOfPurchaseAmount } from '@/api/salesDetailNew'
import { pushDown } from '@/api/waitDispatchDetail'
import { findBySalesBillSn, dispatchUpdateStockType } from '@/api/dispatch'

export default {
  name: 'WaitDispatch',
  mixins: [commonMixin],
  components: { detailProductList, 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: '' }, // 订单基础数据
      productForm: {
        dispatchBillSn: '' // 下推单sn
      },
      totalData: null, // 统计数据
      activeList: [] // 参与活动列表
    }
  },
  methods: {
    //  返回
    handleBack () {
      this.$router.push({ name: 'salesQueryNewList', query: { closeLastOldTab: true } })
    },
    // 统计查询
    getTotalData (flag) {
      findBySalesBillSn({ salesBillSn: this.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
            if (flag) {
              _this.$refs.waitProduct.pageInit(this.productForm, this.detailData, this.activeList)
            } else {
              _this.$refs.waitProduct.resetSearchForm()
            }
          }
        } else {
          this.totalData = null
        }
      })
    },
    // 更新轮胎库存类型
    updateStockType (val) {
      this.spinning = true
      dispatchUpdateStockType({ stockType: val, dispatchBillSn: this.productForm.dispatchBillSn }).then(res => {
        if (res.status != 200) {
          this.$refs.partQuery.stockType = val == 'LOCK_STOCK' ? 'CURRENT_STOCK' : 'LOCK_STOCK'
        }
        this.spinning = false
      })
    },
    // 禁用库存类型选项
    upStockType (hasLt) {
      this.$refs.partQuery.stockDisabled = hasLt
      if (hasLt) {
        this.$refs.partQuery.stockType = this.totalData.stockType
      }
    },
    // 添加产品
    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.refashTable(true)
          this.$refs.partQuery.clearSelectTable()
          this.$message.success('添加成功', 2.5)
          this.spinning = false
        } else {
          this.spinning = false
        }
        this.isInster = false
      })
    },
    // 整单取消
    cancelAll () {
      salesDetailCancleOfAll({ salesBillSn: this.salesBillSn }).then(res => {
        if (res.status == 200) {
          this.handleBack()
          this.$message.success(res.message)
        }
      })
    },
    // 批量转采购额
    convertPromoGifts (list) {
      const _this = this
      this.$message.loading('正在批量转采购额...', 1)
      this.isInster = true
      this.spinning = true
      batchTransferOfPurchaseAmount({
        salesBillDetailList: list,
        salesBillSn: this.salesBillSn
      }).then(res => {
        if (res.status == 200) {
          if (res.data == 'OUTING_WAREHOUSE' || res.data == 'FINISH') {
            _this.$info({
              title: '提示',
              content: '当前销售单已被更新为【' + (res.data == 'OUTING_WAREHOUSE' ? '出库中' : '已完结') + '】，将返回列表',
              centered: true,
              closable: false,
              onOk () {
                _this.handleBack()
              }
            })
          } else {
            _this.getOrderDetail()
            _this.$message.success(res.message, 2.5)
          }
        }
        this.spinning = false
        this.isInster = false
      })
    },
    // 批量取消产品
    cancelProduct (list) {
      // 防止多次添加产品
      this.$message.loading('正在批量取消产品...', 1)
      this.isInster = true
      this.spinning = true
      salesDetailUpdateCancelQty({
        salesBillDetailList: list,
        salesBillSn: this.salesBillSn
      }).then(res => {
        if (res.status == 200) {
          this.getOrderDetail()
          this.$message.success(res.message, 2.5)
          this.spinning = false
        } else {
          this.spinning = false
        }
        this.isInster = false
      })
    },
    // 刷新表格
    refashTable (flag) {
      this.getTotalData()
      if (flag) {
        this.getOrderDetail(false)
      }
    },
    //  销售单详情
    getOrderDetail (flag) {
      salesDetailBySn({ salesBillSn: this.salesBillSn }).then(res => {
        if (res.status == 200) {
          this.detailData = res.data
          this.$refs.waitProduct.detailData = res.data
          if (flag) {
            // 初始化表格
            this.$refs.partQuery.pageInit(this.salesBillSn, this.detailData)
          } else {
            // 刷新表格
            this.$refs.partQuery.resetSearchForm(this.detailData)
          }
        }
      })
    },
    // 提交下推
    handleDispatch () {
      const dataSource = this.$refs.waitProduct.dataSource
      if (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
      })
    },
    // 页面初始化
    async pageInit () {
      this.salesBillSn = this.$route.params.salesBillSn
      // 已参与活动列表
      this.spinning = true
      const list = await salesPromoQueryList({ salesBillSn: this.salesBillSn || this.bizSn }).then(res => res.data || [])
      this.activeList = list.filter(item => item.promotion && item.promotionRule)
      this.spinning = false
      // 查询表格数据
      this.$refs.partQuery.clearSelectTable()
      this.getOrderDetail(true)
      this.getTotalData(true)
    }
  },
  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-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>
