<template>
  <div class="waitDispatch-wrap">
    <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>
        <!-- <a-button id="waitDispatch-edit-btn" size="small" @click="handleEdit" style="margin-left:10px" key="0">编辑</a-button> -->
      </template>
      <!-- 操作区，位于 title 行的行尾 -->
      <!-- <template slot="extra">
        <a-button key="2" id="waitDispatch-preview-btn">打印预览</a-button>
        <a-button key="1" type="primary" id="waitDispatch-print-btn">快速打印</a-button>
      </template> -->
    </a-page-header>
    <a-spin :spinning="spinning" tip="Loading...">
      <a-card :bordered="false" class="waitDispatch-cont" v-if="salesBillSn">
        <!-- 查询配件列表 -->
        <queryPart
          ref="partQuery"
          :salesBillSn="salesBillSn"
          :detailData="detailData"
          :newLoading="isInster"
          @oneDispatch="oneDispatch"
          @cancelProduct="cancelProduct"
          @addProduct="insterProduct"></queryPart>
      </a-card>
      <a-card :bordered="false" class="waitDispatch-cont">
        <div slot="title">
          <div class="p-title">
            待下推产品
          </div>
        </div>
        <div style="margin: 0 0 10px 0;">
          <a-button
            type="primary"
            @click="delSalerDetailAll"
            :loading="delLoading"
            id="waitDispatch-del-all">批量移除</a-button>
        </div>
        <!-- 总计 -->
        <a-alert type="info">
          <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"
          :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onChange, onSelect: onSelectChange, onSelectAll: onSelectAllChange }"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data="loadData"
          :showPagination="false"
          :scroll="{ x:1150, y: 300 }"
          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">
            <editable-cell
              size="small"
              :text="record.qty"
              :max="999999"
              :min="1"
              :precision="0"
              @change="onCellChange(record.id, 'qty', $event)" />
          </template>
          <!-- 操作 -->
          <template slot="action" slot-scope="text, record">
            <a-button
              size="small"
              type="primary"
              :loading="delLoading"
              class="button-error"
              @click="handleDel(record)"
            >移除</a-button>
          </template>
        </s-table>
      </a-card>
      <a-affix :offset-bottom="0">
        <div
          style="text-align: center;width: 100%;background-color: #fff;padding: 12px 0;box-shadow: 0 0 20px #dcdee2;">
          <a-button
            size="large"
            style="width: 150px;"
            type="primary"
            class="button-primary"
            v-if="dataSource.length>0"
            @click="handleSubmit()"
            :loading="loading"
            id="productInfoList-handleSubmit">下推</a-button>
        </div>
      </a-affix>
    </a-spin>
  </div>
</template>

<script>
import { STable, VSelect } from '@/components'
import queryPart from './queryPart.vue'
import { salesDetailBySn } from '@/api/sales'
import { salesDetailDispatchByOneKey, insertBatchOfWaitDispatch, salesDetailUpdateCancelQty } from '@/api/salesDetail'
import EditableCell from '@/views/common/editInput.js'
import { deleteBatch, pushDown, dispatchDetail, waitDispatchDetailAllList, updateQty } from '@/api/waitDispatchDetail'
export default {
  name: 'SalesDetail',
  components: { STable, VSelect, queryPart, EditableCell },
  data () {
    return {
      spinning: false,
      salesBillSn: null, // 销售单sn
      disabled: false, //  查询、重置按钮是否可操作
      isInster: false, // 是否正在添加产品
      delLoading: false, // 是否正在移除产品
      loading: false, // 是否下推中
      detailData: { discountAmount: 0, id: null, salesBillSn: '' }, // 订单基础数据
      dataSource: [],
      productForm: {
        dispatchBillSn: ''
      },
      selectedRowKeys: [], // Check here to configure the default column
      selectedRows: [],
      // 表头
      columns: [
        { title: '序号', dataIndex: 'no', width: 80, align: 'center' },
        { title: '产品编码', dataIndex: 'productEntity.code', scopedSlots: { customRender: 'productCode' }, width: 220, align: 'center' },
        { title: '产品名称', dataIndex: 'productEntity.name', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '剩余待下推', dataIndex: 'surplusQty', width: 150, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '本次下推数', scopedSlots: { customRender: 'salesNums' }, width: 150, align: 'center' },
        { title: '单位', dataIndex: 'productEntity.unit', width: 100, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: 150, align: 'center', fixed: 'right' }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.productForm.dispatchBillSn = this.$route.params.dispatchBillSn

        // 查询统计
        this.getTotalData()
        return waitDispatchDetailAllList(Object.assign(parameter, this.productForm)).then(res => {
          const data = res.data
          const no = 0
          for (var i = 0; i < data.length; i++) {
            data[i].no = no + i + 1
          }
          this.disabled = false
          this.dataSource = data
          return data
        })
      },
      totalData: null
    }
  },
  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)
            }
          })
        })
      }
    },
    // 统计查询
    getTotalData () {
      dispatchDetail({ dispatchBillSn: this.$route.params.dispatchBillSn }).then(res => {
        if (res.status == 200) {
          this.totalData = res.data || null
        } else {
          this.totalData = null
        }
      })
    },
    // 修改数量
    onCellChange (id, key, value) {
      console.log(id, key, value)
      const dataSource = [...this.dataSource]
      const row = dataSource.find(item => item.id === id)
      if (row) {
        row[key] = Number(value)
        this.dataSource = dataSource
      }
      if (key == 'qty') {
        this.spinning = true
        updateQty({
          dispatchBillDetailSn: row.dispatchBillDetailSn,
          qty: row.qty,
          salesBillSn: this.salesBillSn
        }).then(res => {
          this.resetSearchForm(true)
          if (res.status == 200) {
            this.$refs.partQuery.resetCurForm()
            this.$message.success(res.message)
            this.spinning = false
          } else {
            this.spinning = false
          }
        })
      }
    },
    //  重置
    resetSearchForm (flag) {
      this.$refs.table.refresh(!!flag)
      this.getOrderDetail()
    },
    // 重置列表
    resetForm () {
      this.$refs.table.refresh()
    },
    //  返回
    handleBack () {
      this.$router.push({ name: 'salesQueryList' })
    },
    // 批量删除
    delSalerDetailAll () {
      const _this = this
      if (_this.selectedRowKeys.length < 1) {
        _this.$message.warning('请在选择待下推产品！')
        return
      }
      const obj = []
      _this.selectedRows.map(item => {
        if (_this.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(type == 0 ? [row.dispatchBillDetailSn] : row).then(res => {
        if (res.status == 200) {
          _this.resetSearchForm(true)
          _this.$refs.partQuery.resetCurForm()
          if (type == 1) { //  批量操作
            _this.selectedRowKeys = []
            _this.selectedRows = []
          } else if (type == 0) { //  单条
            const ind = _this.selectedRowKeys.findIndex(item => item == row.id)
            _this.selectedRowKeys.splice(ind, 1)
          }
          _this.$message.success(res.message)
          _this.spinning = false
        } else {
          _this.spinning = false
        }
        _this.delLoading = false
      })
    },
    // 添加产品
    insterProduct (list) {
      console.log(list)
      // 防止多次添加产品
      if (this.isInster) { return }
      this.saveNewProduct(list)
    },
    // 保存添加的产品到下推列表
    saveNewProduct (list) {
      this.$message.loading('正在添加产品...', 1)
      this.isInster = true
      this.spinning = true
      insertBatchOfWaitDispatch(list).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 => {
        console.log('getOrderDetail')
        if (res.status == 200) {
          this.detailData = res.data
          console.log(this.detailData)
        }
      })
    },
    // 提交下推
    handleSubmit () {
      this.delLoading = true
      this.isInster = true
      this.loading = true
      this.spinning = true
      pushDown({ dispatchBillSn: this.$route.params.dispatchBillSn }).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
      })
    }
  },
  mounted () {
    this.getOrderDetail()
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      console.log('beforeRouteEnter')
      vm.salesBillSn = vm.$route.params.salesBillSn
    })
  }
}
</script>

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