<template>
  <div class="productInfoList-wrap" style="position: relative;">
    <!-- 搜索条件 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchTable">
        <a-row :gutter="15">
          <a-col :md="4" :sm="24">
            <a-form-item label="产品名称">
              <a-input id="productInfoList-name" v-model.trim="queryParam.productName" allowClear placeholder="请输入产品名称"/>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="24">
            <a-form-item label="产品编码">
              <a-input id="productInfoList-code" v-model.trim="queryParam.productCode" allowClear placeholder="请输入产品编码"/>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="24" v-if="hasPrompActive">
            <a-form-item label="产品类型">
              <a-select allowClear v-model.trim="queryParam.promotionFlag" :dropdownMatchSelectWidth="false" placeholder="请选择产品类型">
                <a-select-option value="0">
                  正常产品
                </a-select-option>
                <a-select-option value="REGULAR">
                  正价产品（活动）
                </a-select-option>
                <a-select-option value="DISCOUNT">
                  特价产品
                </a-select-option>
                <a-select-option value="GIFT">
                  促销产品
                </a-select-option>
                <a-select-option value="convertPromoGiftsFlag" v-if="showConvertPromoGifts">
                  促销产品（转采购额）
                </a-select-option>
                <a-select-option value="GATE">
                  门槛产品
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="24">
            <a-form-item label="下推类型">
              <a-select allowClear v-model.trim="queryParam.pushProductType" :dropdownMatchSelectWidth="false" placeholder="请选择下推类型">
                <a-select-option value="">
                  全部产品
                </a-select-option>
                <a-select-option value="ABLE">
                  剩余待下推数量＞0的产品
                </a-select-option>
                <a-select-option value="ALL">
                  可全部下推的产品
                </a-select-option>
                <a-select-option value="NOTALL">
                  不可全部下推的产品
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="24">
            <a-form-item label="出库仓库">
              <chooseWarehouse ref="warehouse" v-model="queryParam.warehouseSn"></chooseWarehouse>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="24" style="margin-bottom: 10px;">
            <a-button type="primary" @click="searchTable" :disabled="disabled" id="productInfoList-refresh">查询</a-button>
            <a-button style="margin-left: 5px" @click="resetSearchForm(null)" id="productInfoList-reset">重置</a-button>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- alert -->
    <div style="margin-bottom: 10px;display: flex;align-items: center;" v-if="detailData">
      <div style="display: flex;align-items: center;">
        <span v-if="selectedRowKeys.length">已选 {{ selectedRowKeys.length }} 项</span>
        <a-button id="dispatch-plAdd" type="primary" :disabled="newLoading" class="button-info" @click="handlePlAdd">批量添加</a-button>
        <a-button
          id="dispatch-plPurchase"
          type="primary"
          :disabled="newLoading"
          class="button-info"
          v-if="showConvertPromoGifts"
          @click="handlePlPurchase">批量转采购额</a-button>
        <a-button
          id="dispatch-plCancel"
          type="primary"
          v-if="hasNormalProduct"
          ghost
          style="margin-left:6px;"
          :disabled="newLoading"
          @click="handlePlCancel">批量取消</a-button>
        <a-button
          id="dispatch-cancelAll"
          type="primary"
          v-if="hasPrompActive&&hasNoPushedActive"
          ghost
          style="margin-left:6px;"
          :disabled="newLoading"
          @click="handleAllCancel">整单取消</a-button>
        <a-tooltip placement="top" v-if="hasPrompActive&&hasNoPushedActive" style="margin-left:6px;">
          <template slot="title">
            <span>参加促销活动的产品，不能单独取消，只能整单取消。</span>
          </template>
          <a-icon style="font-size: 14px;" type="question-circle" />
        </a-tooltip>
        <v-select
          v-if="hasJGtire"
          :disabled="stockDisabled"
          style="margin-left: 15px;width:150px;"
          v-model="stockType"
          id="dispatch-stockType"
          code="TIRE_STOCK_TYPE"
          placeholder="请选择库存类型"
          @change="stockTypeChange"
        ></v-select>
        <a-button
          v-if="hasJGtire && stockType=='LOCK_STOCK'"
          @click="confirPurchaseModal"
          :loading="loading"
          type="primary"
          style="margin-left: 6px"
          class="button-info"
          id="dispatch-updateStock">轮胎转采购单</a-button>

      </div>
      <div style="padding-left: 20px;">
        总销售数量：<strong>{{ detailData&&(detailData.totalQty || detailData.totalQty==0) ? detailData.totalQty : '--' }}</strong>；
        已取消数量：<strong>{{ detailData&&(detailData.totalCancelQty || detailData.totalCancelQty==0) ? detailData.totalCancelQty : '--' }}</strong>；
        已下推数量：<strong>{{ detailData&&(detailData.totalPushedQty || detailData.totalPushedQty==0) ? detailData.totalPushedQty : '--' }}</strong>；
        待下推数量：<strong>{{ detailData&&(detailData.totalUnpushedQty || detailData.totalUnpushedQty==0) ? detailData.totalUnpushedQty : '--' }}</strong>；
        <span v-if="$hasPermissions('B_salesDispatch_salesPrice')">总售价：<strong>{{ detailData&&(detailData.totalAmount || detailData.totalAmount==0) ? toThousands(detailData.totalAmount) : '--' }}</strong>；</span>
        <span v-if="$hasPermissions('B_salesDispatch_costPrice')">总成本：<strong>{{ detailData&&(detailData.totalCost || detailData.totalCost==0) ? toThousands(detailData.totalCost) : '--' }}</strong>；</span>
        <span v-if="$hasPermissions('B_salesDispatch_costPrice')&&$hasPermissions('B_salesDispatch_salesPrice')">总毛利：<strong>{{ detailData&&(detailData.grossProfit || detailData.grossProfit==0) ? toThousands(detailData.grossProfit) : '--' }}</strong>；</span>
        <span v-if="$hasPermissions('B_salesDispatch_salesPrice')">已取消金额：<strong>{{ detailData&&(detailData.totalCancelAmount || detailData.totalCancelAmount==0) ? toThousands(detailData.totalCancelAmount) : '--' }}</strong>；</span>
        <span v-if="$hasPermissions('B_salesDispatch_salesPrice')">已下推金额：<strong>{{ detailData&&(detailData.totalPushedAmount || detailData.totalPushedAmount==0) ? toThousands(detailData.totalPushedAmount) :'--' }}</strong>；</span>
        <span v-if="$hasPermissions('B_salesDispatch_salesPrice')">待下推金额：<strong>{{ detailData&&(detailData.totalUnpushedAmount || detailData.totalUnpushedAmount==0) ? toThousands(detailData.totalUnpushedAmount) : '--' }}</strong>；</span>
        <span v-if="$hasPermissions('B_salesDispatch_salesPrice')&&detailData&&detailData.totalConvertPromoGiftsAmount" style="color:red;">促销产品转采购额金额：<strong>{{ toThousands(detailData.totalConvertPromoGiftsAmount) }}</strong>；</span>
      </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="tableData"
        row-key-field-name="id"
        :cell-style-option="cellStyleOption"
        :cell-span-option="cellSpanOption"
        :column-width-resize-option="columnWidthResizeOption"
        :checkbox-option="checkboxOption"
      />
      <div v-show="showEmpty" class="empty-data-0"><a-empty description="暂无数据" :image="simpleImage"/></div>
      <!-- 活动规则详情 -->
      <detailModal :openModal="openDetailModal" :itemSn="detailSn" @close="closeDetailModal"></detailModal>
      <!-- 转采购单 -->
      <toPurchaseModal :openModal="openPurchaseModal" @ok="showLockStockQty = true" @close="openPurchaseModal=false" ref="purchaseModal"></toPurchaseModal>
    </a-spin>

  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import { Empty } from 'ant-design-vue'
import detailModal from '@/views/promotionRulesManagement/dealerPromotions/detailModal.vue'
import toPurchaseModal from './toPurchaseModal'
import chooseWarehouse from '@/views/common/chooseWarehouse'
// 接口
import { queryAwaitDispatch } from '@/api/salesDetailNew'
import { getCreatePurchaseFlag } from '@/api/salesNew'

export default {
  name: 'QueryPart',
  mixins: [commonMixin],
  components: { STable, VSelect, chooseWarehouse, detailModal, toPurchaseModal },
  props: {
    newLoading: { // loading
      type: Boolean,
      default: false
    },
    maxHeight: { // 最大高度
      type: [String, Number],
      default: '300'
    },
    showHeader: { // 是否显示表格头部
      type: Boolean,
      default: true
    },
    activeList: { // 参与的活动列表
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      loading: false,
      advanced: true, // 高级搜索 展开/关闭
      openDetailModal: false, // 活动规则详情弹框
      openPurchaseModal: false, // 转采购单弹框
      simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,
      detailSn: null, // 活动详情sn
      productType: [], // 产品类型
      salesBillSn: '', // 销售单sn
      detailData: null, // 详情数据
      queryParam: {
        pushProductType: '', // 类型
        productCode: '', //  产品编码
        productName: '', //  产品名称
        promotionFlag: undefined, //  是否促销品
        brandSn: undefined, //  产品品牌
        productTypeSn1: '', //  产品一级分类
        productTypeSn2: '', //  产品二级分类
        productTypeSn3: '', //  产品三级分类
        salesBillSn: '', // 销售单sn
        warehouseSn: undefined, // 仓库sn
        convertPromoGiftsFlag: undefined // 转采购额
      },
      disabled: false, //  查询、重置按钮是否可操作
      spinning: false,
      dataSource: [], // 原始数据
      tableData: [], // 表格数据
      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: [], // 已选数据
      colspanNums: 16, // 列合并数量
      hasNormalProduct: false, // 是否有正常产品
      showLockStockQty: false, // 是否显示锁定库存列
      stockType: undefined, // 默认锁定库存
      hasJGtire: false, // 是否轮胎产品
      stockDisabled: false
    }
  },
  computed: {
    // 表格高度
    tableHeight () {
      return (this.showEmpty ? 200 : this.maxHeight) + 'px'
    },
    // 是否有促销活动产品
    hasPrompActive () {
      return this.detailData && this.detailData.promoFlag == 1
    },
    // 是否有下推产品
    hasNoPushedActive () {
      return this.detailData && this.detailData.totalPushedQty == 0 || !this.detailData.totalPushedQty
    },
    // 是否有转采购额
    hasConvertPromoGifts () {
      return this.detailData && this.detailData.totalConvertPromoGiftsAmount > 0
    },
    // 是否显示转采购额选项
    showConvertPromoGifts () {
      return this.activeList && this.activeList.find(item => item.enabledFlag == 1 && item.promotionRule && item.promotionRule.convertExpenseFlag == 1 && item.promotionRule.promotionRuleType == 'BUY_PROD_GIVE_PROD')
    },
    // 表格复选框
    checkboxOption () {
      return {
        disableSelectedRowKeys: this.disableSelectedRowKeys,
        selectedRowKeys: this.selectedRowKeys,
        hideSelectAll: this.disableSelectedRowKeys.length == this.tableData.length,
        // 行选择改变事件
        selectedRowChange: ({ row, isSelected, selectedRowKeys }) => {
          this.selectedRowChange({ row, isSelected, selectedRowKeys })
        },
        // 全选改变事件
        selectedAllChange: ({ isSelected, selectedRowKeys }) => {
          this.selectedAllChange({ isSelected, selectedRowKeys })
        }
      }
    },
    columns () {
      const _this = this
      // 价格
      const priceFormat = function (record, data, h) {
        return (
          <div>
            {_this.toThousands(data)}
            {record.promotionFlag.indexOf('GIFT') >= 0 || record.promotionFlag.indexOf('DISCOUNT') >= 0 ? (
              <span title="原价">（{ _this.toThousands(record.origPrice)}）</span>
            ) : ''}
          </div>
        )
      }
      // 数字
      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('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' }}/> : ''}
            {record.promotionFlag.indexOf('DISCOUNT') >= 0 ? <a-badge count="特" numberStyle={{ backgroundColor: '#faad14', zoom: '0.7' }}/> : ''}
            {Number((record.tireFlag != 0 ? record.lockStockQty : record.stockQty) || 0) < Number(record.unpushedQty || 0) && record.borrowFlag != '1' ? (<a-badge count="缺" numberStyle={{ zoom: '0.7' }}></a-badge>) : ''}
            {record.bakConvertPromoGiftsQty ? (<a-badge count="转" numberStyle={{ backgroundColor: '#0055ff', zoom: '0.7' }}></a-badge>) : ''}
          </div>
        )
      }
      // 取消数量输入框
      const inputFormat = function (record, data, h) {
        if (record.unpushedQty > 0) {
          return (
            <div>
              <a-input-number
                id={'dispacth-cancelNums-' + record.productSn}
                size="small"
                value={record.cancelNums}
                onChange={e => _this.cancelNumsChange(e, record)}
                precision={0}
                min={0}
                max={record.unpushedQty}
                style="width: 100%;"
                placeholder="请输入" />
            </div>
          )
        }
        return '--'
      }
      // 转采购额数量输入框
      const inputFormat1 = function (record, data, h) {
        if (record.unpushedQty >= 0 && record.convertPromoGiftsFlag == 1) {
          // 已选
          if (_this.selectedRowKeys.includes(record.id)) {
            return (
              <div>
                <a-input-number
                  id={'dispacth-maxConvertNums-' + record.productSn}
                  size="small"
                  value={record.convertPromoGiftsQty}
                  onChange={e => _this.convertPromoGiftsChange(e, record)}
                  precision={0}
                  min={0}
                  max={record.maxConvertNums}
                  style="width: 100%;"
                  placeholder="请输入" />
              </div>
            )
          } else {
            return record.convertPromoGiftsQty || 0
          }
        }
        return '--'
      }
      // 操作按钮
      const actionFormat = function (record, data, h) {
        if (record.unpushedQty > 0) {
          return (
            <div>
              <a-button
                id={'dispacth-handleAdd-' + record.productSn}
                size="small"
                type="link"
                class="button-info"
                onClick={() => _this.handleAdd(record)}
              >添加</a-button>
            </div>
          )
        }
        return '--'
      }
      // 编号，并且格式化活动分类行
      const noFormat = function (record, data, h) {
        return (
          <div>
            {record.id.indexOf('promo-active') >= 0 ? (
              <div class="active-title">参与促销的产品</div>
            ) : (<span>{data}</span>)}
          </div>
        )
      }

      let arr = [
        { title: '', field: 'acheck', key: 'acheck', width: 50, type: 'checkbox', align: 'center' },
        { title: '序号', field: 'no', key: 'a', width: 50, align: 'center', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return noFormat(row, row[column.field], h) } },
        { title: '产品编码', field: 'productCode', key: 'b', width: 150, align: 'left', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return codeFormat(row, row[column.field], h) } },
        { title: '产品名称', field: 'productName', key: 'c', width: 220, align: 'left', operationColumn: false, ellipsis: { showTitle: true }, renderBodyCell: ({ row, column, rowIndex }, h) => { return row[column.field] || '--' } },
        { title: '原厂编码', field: 'productOrigCode', key: 'd', width: 150, align: 'left', operationColumn: false, ellipsis: { showTitle: true }, renderBodyCell: ({ row, column, rowIndex }, h) => { return row[column.field] || '--' } },
        { title: '出库仓库', field: 'warehouseName', key: 'e', width: 100, align: 'center', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return row[column.field] || '--' } }
      ]
      // 单元格合并数量
      this.colspanNums = this.showConvertPromoGifts ? 7 : 6
      if (this.hasPrompActive) {
        this.colspanNums = this.colspanNums + 1
        arr.splice(4, 0, {
          title: '规则数量',
          field: 'rulesNums',
          key: '4',
          width: 60,
          align: 'center',
          operationColumn: false,
          renderBodyCell: ({ row, column, rowIndex }, h) => {
            return (
              row.useRuleQty || row.promoRuleSnList && row.promoRuleSnList.length
                ? <a-popover placement="right">
                  <template slot="content">
                    {row.promoRuleSnList.map(item => {
                      return (
                        <div
                          id={'dispacth-ruleDetail-' + row.productSn}
                          title="点击查看详情"
                          style="padding:5px 0;cursor: pointer;"
                          onClick={() => _this.showRuleDetail(item)}
                        >{ _this.activeRuleFilter(item) }</div>
                      )
                    })}
                  </template>
                  <a-button type="link" id={'dispacth-ruleSn-' + row.productSn} size="small" class="button-info">{row.useRuleQty || row.promoRuleSnList && row.promoRuleSnList.length}<span style="zoom:0.6;color: #666;">个 ∨</span></a-button>
                </a-popover> : '--'
            )
          }
        })
      }
      if (this.$hasPermissions('B_salesDispatch_salesPrice')) { //  售价权限
        this.colspanNums = this.colspanNums + 1
        arr.push({ title: '销售价', field: 'price', width: 80, key: 'f', align: 'right', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return priceFormat(row, row[column.field], h) } })
      }
      if (this.$hasPermissions('B_salesDispatch_costPrice')) { // 成本价权限
        this.colspanNums = this.colspanNums + 1
        arr.push({ title: '成本价', field: 'showCost', width: 80, key: 'g', align: 'right', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return _this.toThousands(row[column.field]) || '--' } })
      }
      this.colspanNums = this.colspanNums + 8
      arr = arr.concat([
        { title: '单位', field: 'productOrigUnit', key: 'i', width: 80, align: 'center', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return row[column.field] || '--' } },
        { title: '可用库存', field: 'stockQty', width: 80, key: 'j', align: 'center', fixed: 'right', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return numsFormat(row[column.field]) } }
      ])
      if (this.showLockStockQty) {
        this.colspanNums = this.colspanNums + 1
        arr.push({ title: '锁定库存', field: 'lockStockQty', width: 80, key: 'jk', align: 'center', fixed: 'right', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return numsFormat(row[column.field]) } })
      }
      arr = arr.concat([
        { title: '销售数量', field: 'qty', width: 80, key: 'k', align: 'center', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return numsFormat(row[column.field]) } },
        { title: '已取消', field: 'cancelQty', width: 80, key: 'o', align: 'center', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return numsFormat(row[column.field]) } },
        { title: '已下推', field: 'pushedQty', width: 80, key: 'p', align: 'center', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return numsFormat(row[column.field]) } },
        { title: '待下推', field: 'unpushedQty', width: 80, key: 'q', align: 'center', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return numsFormat(row[column.field]) } },
        { title: '取消数量', field: 'cancelNums', width: 80, key: 'r', align: 'center', fixed: 'right', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return inputFormat(row, row[column.field], h) } }
      ])
      // 是否显示转采购额
      if (this.showConvertPromoGifts) {
        arr.push({ title: '转采购额数量',
          field: 'convertPromoGiftsQty',
          width: 80,
          key: 'z',
          align: 'center',
          fixed: 'right',
          operationColumn: false,
          renderBodyCell: ({ row, column, rowIndex }, h) => {
            return inputFormat1(row, row[column.field], h)
          } })
      }
      arr.push({ title: '操作', field: 'action', width: 80, key: 's', align: 'center', fixed: 'right', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return actionFormat(row, row[column.field], h) } })

      return arr
    }
  },
  methods: {
    // 关闭详情弹窗
    closeDetailModal () {
      this.detailSn = null
      this.openDetailModal = false
    },
    // 参与规则名称
    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
    },
    // 合并活动分类单元格
    bodyCellSpan ({ row, column, rowIndex }) {
      if (row.id.indexOf('promo-') >= 0) {
        if (column.field == 'no') {
          return {
            rowspan: 1,
            colspan: this.colspanNums
          }
        } else {
          return {
            rowspan: 0,
            colspan: 0
          }
        }
      }
    },
    // 取消数量变更
    cancelNumsChange (v, record) {
      record.cancelNums = v
      this.dataSource.splice()
    },
    // 转采购数量变更
    convertPromoGiftsChange (v, record) {
      record.convertPromoGiftsQty = v
      this.dataSource.splice()
    },
    // 选择单元格
    selectedRowChange ({ row, isSelected, selectedRowKeys }) {
      // console.log(row, isSelected, selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys
      if (!isSelected) {
        row.convertPromoGiftsQty = row.bakConvertPromoGiftsQty
      }
    },
    // 全选行
    selectedAllChange ({ isSelected, selectedRowKeys }) {
      this.selectedRowKeys = selectedRowKeys
      // 取消全选后，重置数量
      if (!isSelected && this.showConvertPromoGifts) {
        this.dataSource.filter(item => item.convertPromoGiftsQty).map(item => {
          item.convertPromoGiftsQty = item.bakConvertPromoGiftsQty
        })
      }
    },
    // 查询列表
    async searchTable () {
      this.selectedRowKeys = []
      this.disableSelectedRowKeys = []
      this.dataSource = []
      this.disabled = true
      this.spinning = true
      this.queryParam.salesBillSn = this.salesBillSn
      this.queryParam.showStock = true
      const params = this.queryParam
      // 所有活动接口
      const active = this.activeList
      // 是否查询正常产品
      const hasSearchNormal = !params.promotionFlag || params.promotionFlag == 0
      const proList = hasSearchNormal ? await queryAwaitDispatch({ ...params, detailPromoFlag: 0 }).then(res => res.data) : []
      this.hasNormalProduct = proList.length > 0 // 是否有正常产品
      // 没有活动时不显示正常产品标题行
      let listData = proList

      // 获取活动产品列表，查询条件未选正常产品
      if (params.promotionFlag != 0) {
        const acparams = { ...params, detailPromoFlag: 1, promoProductClz: params.promotionFlag }
        acparams.promotionFlag = undefined
        const aclist = await queryAwaitDispatch(acparams).then(res => res.data)
        // 没用活动产品，不显示
        const retList = aclist.length ? [{
          id: 'promo-active'
        }, ...aclist] : []
        // 将活动产品数据拼接
        listData = aclist && aclist.length ? listData.concat(retList) : listData
      }
      this.dataSource = listData

      // 格式化数据
      let f = 0
      this.dataSource.map((item, i) => {
        const isTjRow = item.id.indexOf('promo-') >= 0
        if (isTjRow) { 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)
        item.productCode = productCode || '--'
        item.productName = productName || '--'
        item.productOrigCode = productOrigCode == ' ' ? '--' : productOrigCode
        item.productOrigUnit = productOrigUnit || '--'
        item.promoRuleSnList = item.promotionRuleList && item.promotionRuleList.map(item => item.promotionRuleSn) // 规则sn
        item.cancelNums = item.unpushedQty // 取消数量
        // 转采购额最大数量
        if (item.convertPromoGiftsFlag == 1) {
          item.maxConvertNums = item.unpushedQty + item.convertPromoGiftsQty
        } else {
          item.maxConvertNums = 0
        }

        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) {
          this.hasJGtire = true
          // 默认锁定库存类型
          if (!this.stockType) {
            this.stockType = 'LOCK_STOCK'
            this.stockTypeChange('LOCK_STOCK')
          }
        }
        // 转采购额数量
        item.bakConvertPromoGiftsQty = item.convertPromoGiftsQty

        // 库存为0或待下推数为0，不可添加
        if (!item.convertPromoGiftsQty && (!item.unpushedQty || item.unpushedQty < 0) || isTjRow) {
          this.disableSelectedRowKeys.push(item.id)
        }
      })
      this.showEmpty = this.dataSource.length <= 0
      this.tableData = this.dataSource
      this.spinning = false
      this.disabled = false
    },
    //  重置
    resetSearchForm (detailData) {
      this.queryParam.pushProductType = ''
      this.queryParam.productCode = ''
      this.queryParam.productName = ''
      this.queryParam.promotionFlag = undefined
      this.queryParam.brandSn = undefined
      this.queryParam.productTypeSn1 = ''
      this.queryParam.productTypeSn2 = ''
      this.queryParam.productTypeSn3 = ''
      this.queryParam.warehouseSn = undefined
      this.queryParam.convertPromoGiftsFlag = undefined
      this.productType = []
      this.dataSource = []
      this.clearSelectTable()
      this.searchTable()

      if (detailData) {
        this.detailData = detailData
      }
    },
    pageInit (salesBillSn, detailData) {
      this.salesBillSn = salesBillSn
      this.detailData = detailData
      // 是否转过采购单
      this.hasCreatePurchaseFlag()
      this.searchTable()
    },
    // 清空选项
    clearSelectTable () {
      this.selectedRowKeys = []
    },
    // 修改库存类型
    stockTypeChange (val) {
      this.$emit('updateStockType', val)
    },
    // 添加
    handleAdd (row) {
      const isLt = row && row.productEntity && row.productEntity.productBrandName == '箭冠' && row.productEntity.productTypeName3 == '轮胎'
      // 如果库存类型是锁定库存 且 轮胎产品
      if (this.stockType && this.stockType == 'LOCK_STOCK' && isLt) {
        if (!row.lockStockQty) {
          this.$message.warning('锁定库存为0，不可添加！')
        } else {
          this.$emit('addProduct', [row.salesBillDetailSn])
        }
      } else {
        // 库存类型可用库存或非轮胎产品
        if (row.stockQty > 0) { //  可用库存大于0才可添加
          this.$emit('addProduct', [row.salesBillDetailSn])
        } else {
          this.$message.warning('库存为0，不可添加！')
        }
      }
    },
    // 批量转采购额
    handlePlPurchase () {
      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.convertPromoGiftsFlag == 1)
      const noChooseRow = this.dataSource.filter(item => chooseList.includes(item.id) && !item.convertPromoGiftsFlag)
      const obj = []
      const noObj = []
      noChooseRow && noChooseRow.map(item => {
        noObj.push(item.productCode)
      })
      chooseRow && chooseRow.map(item => {
        obj.push({
          'convertPromoGiftsQty': item.convertPromoGiftsQty,
          'salesBillDetailSn': item.salesBillDetailSn
        })
      })

      if (obj.length) {
        this.$confirm({
          title: '提示',
          content: <div><div style="text-align:center;padding:10px 0;font-weight:bold;">确定将选中的促销产品转成采购额吗？</div>{noObj.length ? <div style="text-align:center;"><div>总共选择了 {chooseList.length} 个产品，其中 {obj.length} 个产品可转采购额。</div><div style="color:red;"> 产品 ({noObj.toString()}) 不可转采购额!</div></div> : ''}<div style="font-size:12px;color:#999;padding:10px 0;text-align:center;">
当该销售单完结后，可将采购额转成费用报销单。</div></div>,
          centered: true,
          closable: true,
          class: 'confirm-center',
          onOk () {
            _this.$emit('convertPromoGifts', obj)
          }
        })
      } else {
        _this.$message.warning('所选产品都不可转采购额！')
      }
    },
    // 批量添加
    handlePlAdd () {
      const _this = this
      const chooseList = this.selectedRowKeys
      if (chooseList.length == 0) {
        _this.$message.warning('请先选择产品！')
        return
      }

      let noStockRow = []
      let noLockStockRow = []
      // 库存类型是 锁定库存
      if (this.stockType && this.stockType == 'LOCK_STOCK') {
        // 库存为0的产品，不包括箭冠轮胎产品
        noStockRow = this.dataSource.filter(item => chooseList.includes(item.id) && !item.stockQty && item.productEntity && item.productEntity.productBrandName != '箭冠' && item.productEntity.productTypeName3 != '轮胎')
        // 锁定库存为0的产品，只判断箭冠轮胎产品
        noLockStockRow = this.dataSource.filter(item => chooseList.includes(item.id) && item.productEntity && item.productEntity.productBrandName == '箭冠' && item.productEntity.productTypeName3 == '轮胎' && !item.lockStockQty)
      } else {
        // 库存类型是 可用库存
        noStockRow = this.dataSource.filter(item => chooseList.includes(item.id) && !item.stockQty)
      }

      // 库存为0产品编码列表
      const noObj = []
      const noObjSn = []
      noStockRow && noStockRow.map(item => {
        noObj.push(item.productCode)
        noObjSn.push(item.salesBillDetailSn)
      })
      // 锁定库存为0的产品
      const noLockObj = []
      const noLockObjSn = []
      noLockStockRow && noLockStockRow.map(item => {
        noLockObj.push(item.productCode)
        noLockObjSn.push(item.salesBillDetailSn)
      })

      // 可添加产品，不包括库存未0和箭冠轮胎锁定库存为0的产品
      const chooseRow = this.dataSource.filter(item => {
        return chooseList.includes(item.id) && !noObjSn.includes(item.salesBillDetailSn) && !noLockObjSn.includes(item.salesBillDetailSn)
      })
      // 可添加产品sn列表
      const obj = []
      chooseRow && chooseRow.map(item => {
        obj.push(item.salesBillDetailSn)
      })
      if (obj.length) {
        this.$confirm({
          title: '提示',
          content: <div><div style="text-align:center;padding:10px 0;font-weight:bold;">确认要批量添加到待下推列表吗？</div>{(noObj.length || noLockObj.length) ? <div><div>总共选择了 {chooseList.length} 个产品，其中 {obj.length} 个产品可添加。</div>{noObj.length ? <div>产品 ({noObj.toString()}) 因库存为0不可添加!</div> : ''}</div> : ''}<div>{noLockObj.length ? <div>产品 ({noLockObj.toString()}) 因锁定库存为0不可添加!</div> : ''}</div></div>,
          centered: true,
          closable: true,
          class: 'confirm-center',
          onOk () {
            _this.$emit('addProduct', obj)
          }
        })
      } else {
        _this.$message.warning(noLockObj.length ? '所选产品锁定库存都为0，不可添加！' : '所选产品库存都为0，不可添加！')
      }
    },
    // 整单取消
    handleAllCancel () {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确定整单取消订单？',
        centered: true,
        closable: true,
        onOk () {
          _this.$emit('cancelAll')
        }
      })
    },
    // 批量取消
    handlePlCancel () {
      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 hasActive = chooseRow && chooseRow.filter(item => item.promotionFlag != 0)
      if (hasActive.length > 0) {
        _this.$message.warning('参与促销的产品只可进行整单取消！')
        return
      }
      const obj = []
      chooseRow && chooseRow.map(item => {
        obj.push({
          'cancelQty': item.cancelNums,
          'salesBillDetailSn': item.salesBillDetailSn
        })
      })

      this.$emit('cancelProduct', obj)
    },
    // 确认整单转采购单
    confirPurchaseModal () {
      this.loading = true
      getCreatePurchaseFlag({ salesBillSn: this.salesBillSn }).then(res => {
        if (res.status == '200') {
          // 没有转过
          if (res.data == 0) {
            this.showPurchaseModal()
          } else {
            // 转过，弹确认框
            const _this = this
            this.$confirm({
              title: '提示',
              content: '已转过采购单，是否再次转单？',
              centered: true,
              closable: true,
              onOk () {
                _this.showPurchaseModal()
              }
            })
          }
        }
        this.loading = false
      })
    },
    // 打开转采购单弹框
    showPurchaseModal () {
      this.openPurchaseModal = true
      this.$refs.purchaseModal.setDetail(this.detailData)
    },
    // 是否转过采购单
    hasCreatePurchaseFlag () {
      getCreatePurchaseFlag({ salesBillSn: this.salesBillSn }).then(res => {
        this.showLockStockQty = res.data && res.data == 1
      })
    }
  }
}
</script>
<style lang="less">
    .empty-data-0{
        color: #999;
        text-align: center;
        padding: 10px;
        position: absolute;
        bottom: 0;
        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>
