<template>
  <div class="productInfoList-wrap" style="position: relative;">
    <!-- 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
        :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"
        :checkbox-option="checkboxOption"
      />
      <div v-show="showEmpty" class="empty-data3"><a-empty description="暂无产品" :image="simpleImage"/></div>
    </a-spin>
    <!-- 活动规则详情 -->
    <detailModal :openModal="openDetailModal" :itemSn="detailSn" @close="closeDetailModal"></detailModal>
  </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 detailModal from '@/views/promotionRulesManagement/dealerPromotions/detailModal.vue'
import chooseWarehouse from '@/views/common/chooseWarehouse'
export default {
  name: 'DetailProductList',
  mixins: [commonMixin],
  components: { STable, VSelect, chooseWarehouse, detailModal },
  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, // 表格高度
      // 可拖曳调整列宽
      columnWidthResizeOption: {
        enable: true,
        minWidth: 50
      },
      showEmpty: false, // 是否显示暂无数据
      showTableHead: true, // 是否显示表格头部
      disableSelectedRowKeys: [], // 禁用的行
      selectedRowKeys: [], // 已选行
      detailData: null, // 详情数据
      activeList: [], // 参与活动列表
      openDetailModal: false, // 活动规则详情弹框
      detailSn: null // 活动详情sn
    }
  },
  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 })
        }
      }
    },
    // 是否有促销活动产品
    hasPrompActive () {
      return this.detailData && this.detailData.promoFlag == 1
    },
    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) {
        return (
          <div>
            <span style="padding-right: 10px;">{data}</span>
            {record.promotionFlag.indexOf('GIFT') >= 0 ? <a-badge count="促" numberStyle={{ backgroundColor: '#52c41a', zoom: '0.7' }}/> : ''}
            {record.promotionFlag.indexOf('DISCOUNT') >= 0 ? <a-badge count="特" numberStyle={{ backgroundColor: '#faad14', zoom: '0.7' }}/> : ''}
            {record.promotionFlag.indexOf('GATE') >= 0 ? <a-badge count="槛" numberStyle={{ backgroundColor: '#108ee9', zoom: '0.7' }}/> : ''}
            {record.promotionFlag.indexOf('REGULAR') >= 0 ? <a-badge count="正" numberStyle={{ backgroundColor: '#ff5500', zoom: '0.7' }}/> : ''}
            {Number(record.stockQty || 0) < Number(record.unpushedQty || 0) && record.borrowFlag != '1' ? (<a-badge count="缺" number-style={{ zoom: '0.7' }}></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', width: 350, 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.hasPrompActive) {
        arr.splice(2, 0, {
          title: '规则数量',
          field: 'prompName',
          key: 'm',
          align: 'center',
          width: 80,
          operationColumn: false,
          ellipsis: { showTitle: false },
          renderBodyCell: ({ row, column, rowIndex }, h) => {
            return (
              row.promoRuleSnList && row.promoRuleSnList.length > 0
                ? <a-popover placement="right">
                  <template slot="content">
                    {row.promoRuleSnList.map(item => {
                      return (
                        <div
                          id={'ruleDetail-' + row.productSn}
                          title="点击查看详情"
                          style="padding:5px 0;cursor: pointer;"
                          onClick={() => _this.showRuleDetail(item)}
                        >{ _this.activeRuleFilter(item) }</div>
                      )
                    })}
                  </template>
                  <a-button type="link" id={'ruleSn-' + row.productSn} size="small" class="button-info">
                    {row.promoRuleSnList.length}<span style="zoom:0.6;color: #666;">个 ∨</span>
                  </a-button>
                </a-popover>
                : <div>--</div>
            )
          } })
        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: {
    // 参与规则名称
    activeRuleFilter (val) {
      const row = this.activeList.length && this.activeList.find(item => item.promoRuleSn == val)
      return row ? row.promotionRule.description + '-' + row.promotion.description : ''
    },
    // 查看参与规则详情
    showRuleDetail (promoRuleSn) {
      this.detailSn = promoRuleSn
      this.openDetailModal = true
    },
    // 关闭详情弹窗
    closeDetailModal () {
      this.detailSn = null
      this.openDetailModal = false
    },
    // 选择单元格
    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
      let hasLt = false
      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.promoRuleSnList = item.promotionRuleList && item.promotionRuleList.map(item => item.promotionRuleSn) // 规则sn
        item.qtyBackups = item.qty
        item.prompName = prompName || '--'
        const productBrand = (item.productEntity && item.productEntity.productBrandName) || (item.dealerProductEntity && item.dealerProductEntity.productBrandName)
        const productType3 = (item.productEntity && item.productEntity.productTypeName3) || (item.dealerProductEntity && item.dealerProductEntity.productTypeName3)
        if (productBrand && productBrand.indexOf('箭冠') >= 0 && productBrand && productType3.indexOf('轮胎') >= 0) {
          hasLt = true
        }
      })
      this.showEmpty = this.dataSource.length <= 0
      const len = this.dataSource.length
      if (len < 8) {
        this.tableHeight = this.showEmpty ? 200 : (len + 1) * 34 - 1 + 'px'
      } else {
        this.tableHeight = this.maxHeight + 'px'
      }
      this.$emit('upStockType', hasLt)
      this.spinning = false
      this.disabled = false
    },
    //  重置
    resetSearchForm () {
      this.dataSource = []
      this.clearSelectTable()
      this.searchTable()
    },
    // 页面初始化
    pageInit (productForm, detailData, activeList) {
      console.log(detailData, 'detailData')
      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-data3{
        color: #999;
        text-align: center;
        padding: 20px;
        position: absolute;
        top: 30px;
        width: 100%;
    }
    .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>
