<template>
  <div class="productInfoList-wrap">
    <!-- alert -->
    <div style="margin-bottom: 10px;display: flex;align-items: center;" v-if="!showEmpty">
      <div style="display: flex;align-items: center;">
        <a-button id="dispatch-delAll" type="danger" :disabled="newLoading" @click="delSalerDetailAll">批量删除</a-button>
        <span style="margin-left: 10px;" v-if="selectedRowKeys.length">已选 {{ selectedRowKeys.length }} 项</span>
      </div>
      <div style="padding-left: 20px;">
        <slot name="total"></slot>
      </div>
    </div>

    <a-spin :spinning="spinning" tip="Loading...">
      <ve-table
        border-y
        v-show="!showEmpty"
        :scroll-width="0"
        :max-height="tableHeight"
        :show-header="showTableHead"
        :row-style-option="{clickHighlight: true}"
        :cellSelectionOption="{enable: false}"
        :virtual-scroll-option="{enable: true}"
        :columns="columns"
        :table-data="dataSource"
        row-key-field-name="id"
        :cell-style-option="cellStyleOption"
        :cell-span-option="cellSpanOption"
        :checkbox-option="checkboxOption"
      />
      <div v-show="showEmpty" class="empty-data"><a-empty description="暂无产品" :image="simpleImage"/></div>
    </a-spin>

  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { deleteBatch, waitDispatchDetailAllList, updateQty } from '@/api/waitDispatchDetail'
import { Empty } from 'ant-design-vue'
import { STable, VSelect } from '@/components'
import chooseWarehouse from '@/views/common/chooseWarehouse'
export default {
  name: 'DetailProductList',
  mixins: [commonMixin],
  components: { STable, VSelect, chooseWarehouse },
  props: {
    newLoading: {
      type: Boolean,
      default: false
    },
    maxHeight: { // 表格高度
      type: [String, Number],
      default: '300'
    },
    showHeader: { // 是否显示表格头部
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      productForm: {
        dispatchBillSn: '' // 下推单sn
      },
      disabled: false, //  查询、重置按钮是否可操作
      spinning: false,
      simpleImage: Empty.PRESENTED_IMAGE_SIMPLE, // 无数据图片
      dataSource: [], // 原始数据
      tableHeight: this.maxHeight, // 表格高度
      cellStyleOption: {
        bodyCellClass: ({ row, column, rowIndex }) => {
          if (row.id.indexOf('promo-') >= 0 && column.field === 'no') {
            return 'table-body-cell-no'
          }
        }
      },
      // 可拖曳调整列宽
      columnWidthResizeOption: {
        enable: true,
        minWidth: 50
      },
      cellSpanOption: {
        bodyCellSpan: this.bodyCellSpan
      },
      showEmpty: false, // 是否显示暂无数据
      showTableHead: true, // 是否显示表格头部
      disableSelectedRowKeys: [], // 禁用的行
      selectedRowKeys: [], // 已选行
      detailData: null, // 详情数据
      activeList: [] // 参与活动列表
    }
  },
  computed: {
    // 表格复选框设置
    checkboxOption () {
      return {
        disableSelectedRowKeys: this.disableSelectedRowKeys,
        selectedRowKeys: this.selectedRowKeys,
        // 行选择改变事件
        selectedRowChange: ({ row, isSelected, selectedRowKeys }) => {
          this.selectedRowChange({ row, isSelected, selectedRowKeys })
        },
        // 全选改变事件
        selectedAllChange: ({ isSelected, selectedRowKeys }) => {
          this.selectedAllChange({ isSelected, selectedRowKeys })
        }
      }
    },
    columns () {
      const _this = this
      // 价格
      const priceFormat = function (data) {
        return _this.toThousands(data) || '--'
      }
      // 数字
      const numsFormat = function (data) {
        return data || data == 0 ? data : '--'
      }
      // 单号
      const codeFormat = function (record, data, h) {
        let ftext = ''
        let fcolor = ''
        if (record.promotionFlag == 'GIFT') {
          ftext = '促'
          fcolor = '#52c41a'
        }
        if (record.promotionFlag == 'GATE') {
          ftext = '槛'
          fcolor = '#108ee9'
        }

        return (
          <div>
            <span style="padding-right: 15px;">{data}</span>
            {ftext ? (<a-badge count={ftext} number-style={{ backgroundColor: fcolor, zoom: '80%' }}></a-badge>) : ''}
            {Number(record.stockQty || 0) < Number(record.unpushedQty || 0) ? (<a-badge count="缺" number-style={{ zoom: '80%' }}></a-badge>) : ''}
          </div>
        )
      }
      // 输入框
      const inputFormat = function (record, data, h) {
        if (record.surplusQty > 0) {
          return (
            <div>
              <a-input-number
                id={'dispatch-qty-' + record.productSn}
                size="small"
                value={record.qty}
                onChange={e => record.qty = e}
                onBlur={e => _this.cancelNumsChange(e, record)}
                precision={0}
                min={1}
                max={record.surplusQty}
                style="width: 100%;"
                placeholder="请输入" />
            </div>
          )
        }
        return '--'
      }
      // 操作按钮
      const actionFormat = function (record, data, h) {
        if (record.surplusQty > 0) {
          return (
            <div>
              <a-button
                id={'dispatch-delBtn-' + record.productSn}
                size="small"
                type="link"
                class="button-error"
                onClick={() => _this.handleDel(record)}
              >删除</a-button>
            </div>
          )
        }
        return '--'
      }

      const arr = [
        { title: '', field: '', key: 'acheck', width: 60, type: 'checkbox', align: 'center' },
        { title: '序号', field: 'no', key: 'a', width: 60, align: 'center', operationColumn: false },
        { title: '产品编码', field: 'productCode', key: 'b', align: 'left', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return codeFormat(row, row[column.field], h) } },
        { title: '出库仓库', field: 'warehouseName', key: 'e', width: 150, align: 'center', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return row[column.field] || '--' } },
        { title: '待下推数量', field: 'surplusQty', key: 'o', width: 150, align: 'center', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return numsFormat(row[column.field]) } },
        { title: '本次下推数', field: 'qty', key: 'r', width: 150, align: 'center', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return inputFormat(row, row[column.field], h) } },
        { title: '单位', field: 'productOrigUnit', width: 100, key: 'i', align: 'center', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return row[column.field] || '--' } },
        { title: '操作', field: 'action', width: 100, key: 's', align: 'center', fixed: 'right', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return actionFormat(row, row[column.field], h) } }
      ]

      if (this.detailData && this.detailData.promoFlag == 1) {
        arr.splice(2, 0, { title: '活动规则', field: 'prompName', key: 'm', align: 'center', operationColumn: false })
        arr.splice(3, 0, { title: '产品名称', field: 'productName', key: 'c', align: 'left', operationColumn: false, ellipsis: { showTitle: true }, renderBodyCell: ({ row, column, rowIndex }, h) => { return row[column.field] || '--' } })
      } else {
        arr.splice(2, 0, { title: '产品名称', field: 'productName', key: 'c', align: 'left', operationColumn: false, ellipsis: { showTitle: true }, renderBodyCell: ({ row, column, rowIndex }, h) => { return row[column.field] || '--' } })
      }

      return arr
    }
  },
  methods: {
    // 合并活动分类单元格
    bodyCellSpan ({ row, column, rowIndex }) {
      if (row.id.indexOf('promo-') >= 0) {
        if (column.field == 'no') {
          return {
            rowspan: 1,
            colspan: 17
          }
        } else {
          return {
            rowspan: 0,
            colspan: 0
          }
        }
      }
    },
    // 选择单元格
    selectedRowChange ({ row, isSelected, selectedRowKeys }) {
      this.selectedRowKeys = selectedRowKeys
    },
    // 全选行
    selectedAllChange ({ isSelected, selectedRowKeys }) {
      this.selectedRowKeys = selectedRowKeys
    },
    // 数据查询
    async searchTable () {
      this.selectedRowKeys = []
      this.disableSelectedRowKeys = []
      this.dataSource = []
      this.disabled = true
      this.spinning = true
      const params = this.productForm
      // 带下推产品
      const listData = await waitDispatchDetailAllList(params).then(res => res.data)
      this.dataSource = listData

      // 格式化数据
      let f = 0
      this.dataSource.map((item, i) => {
        if (item.id.indexOf('promo-') >= 0) { f = f - 1 }
        item.no = i + 1 + f
        const productCode = (item.productEntity && item.productEntity.code) || (item.dealerProductEntity && item.dealerProductEntity.code)
        const productName = (item.productEntity && item.productEntity.name) || (item.dealerProductEntity && item.dealerProductEntity.name)
        const productOrigCode = (item.productEntity && item.productEntity.origCode) || (item.dealerProductEntity && item.dealerProductEntity.origCode)
        const productOrigUnit = (item.productEntity && item.productEntity.unit) || (item.dealerProductEntity && item.dealerProductEntity.unit)
        const warehouseName = item.dispatchBill && item.dispatchBill.warehouseName || ''
        const prompName = item.promotionRule ? (item.promotionRule.promotion && item.promotionRule.promotion.description) + '(' + item.promotionRule.description + ')' : '--'
        item.productCode = productCode || '--'
        item.productName = productName || '--'
        item.productOrigCode = productOrigCode == ' ' ? '--' : productOrigCode
        item.productOrigUnit = productOrigUnit || '--'
        item.warehouseName = warehouseName || '--'
        item.qtyBackups = item.qty
        item.prompName = prompName || '--'
      })
      this.showEmpty = this.dataSource.length <= 0
      this.tableHeight = (this.showEmpty ? 300 : this.maxHeight) + 'px'
      this.spinning = false
      this.disabled = false
    },
    //  重置
    resetSearchForm () {
      this.dataSource = []
      this.clearSelectTable()
      this.searchTable()
    },
    // 页面初始化
    pageInit (productForm, detailData, activeList) {
      this.productForm = Object.assign(this.productForm, productForm)
      this.detailData = detailData
      this.activeList = activeList
      // 查询列表
      this.resetSearchForm()
    },
    // 清空选项
    clearSelectTable () {
      this.selectedRowKeys = []
    },
    // 取消数量修改
    cancelNumsChange (e, record) {
      const _this = this
      const val = e.target.value
      if (val && val != record.qtyBackups && val <= record.surplusQty) {
        _this.spinning = true
        updateQty({
          dispatchBillDetailSn: record.dispatchBillDetailSn,
          qty: record.qty,
          salesBillSn: _this.detailData.salesBillSn,
          dispatchBillSn: _this.productForm.dispatchBillSn
        }).then(res => {
          if (res.status == 200) {
            _this.$message.success(res.message)
            _this.spinning = false
            _this.$emit('refashTable', true)
          } else {
            record.qty = record.qtyBackups
            _this.spinning = false
          }
        })
      } else {
        record.qty = record.qtyBackups
      }
    },
    // 删除产品
    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.spinning = true
      deleteBatch({
        dispatchBillSn: this.productForm.dispatchBillSn,
        dispatchBillDetailList: type == 0 ? [row.dispatchBillDetailSn] : row
      }).then(res => {
        if (res.status == 200) {
          _this.$emit('refashTable', true)
          _this.$message.success(res.message)
          _this.spinning = false
        } else {
          _this.spinning = false
        }
      })
    },
    // 批量删除
    delSalerDetailAll () {
      const _this = this
      const chooseList = this.selectedRowKeys
      if (chooseList.length == 0) {
        _this.$message.warning('请选择待下推产品！')
        return
      }
      const chooseRow = this.dataSource.filter(item => chooseList.includes(item.id) && item.id.indexOf('promo-') < 0)
      const obj = []
      chooseRow && chooseRow.map(item => {
        obj.push(item.dispatchBillDetailSn)
      })

      this.$confirm({
        title: '提示',
        content: '确认要批量删除吗？',
        centered: true,
        closable: true,
        onOk () {
          _this.deleteFun(obj, 1)
        }
      })
    }
  }
}
</script>
  <style lang="less">
  .empty-data{
        color: #999;
        text-align: center;
        padding: 20px;
    }
    .ve-table-body-td{
      .active-title{
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 10px;
        background: #f3f8fa;
      }
    }
    .ve-table .ve-table-container .ve-table-content-wrapper table.ve-table-content tbody.ve-table-body tr.ve-table-body-tr td.table-body-cell-no,
    .ve-table .ve-table-container .ve-table-content-wrapper table.ve-table-content tbody.ve-table-body tr.ve-table-expand-tr td.table-body-cell-no{
      padding: 0;
    }
    .ve-table .ve-table-container .ve-table-content-wrapper{
      border-bottom: 1px solid #ddd;
    }
  </style>
