<template>
  <div style="position: relative;">
    <!-- 已选配件列表 -->
    <a-spin :spinning="spinning" tip="Loading...">
      <!-- 筛选条件 -->
      <div class="table-page-search-wrapper" style="margin:0" v-show="showSearchBox">
        <a-form layout="inline" @keyup.enter.native="searchProduct">
          <a-row :gutter="15" type="flex">
            <a-col flex="1">
              <a-form-item label="出库仓库" prop="warehouseSn">
                <chooseWarehouse
                  style="width:100%;"
                  :id="'salesEdit-warehouseSn-'+id"
                  ref="warehouse"
                  v-model="queryParam.warehouseSn"
                  @load="warehouseLoad"></chooseWarehouse>
              </a-form-item>
            </a-col>
            <a-col flex="1">
              <a-form-item label="产品编码" prop="productCode">
                <a-input
                  style="width:100%;"
                  :id="'salesEdit-productCode-'+id"
                  v-model.trim="queryParam.productCode"
                  placeholder="请输入产品编码"
                  allowClear />
              </a-form-item>
            </a-col>
            <a-col flex="1">
              <a-form-item label="产品名称" prop="productName">
                <a-input
                  style="width:100%;"
                  :id="'salesEdit-productName-'+id"
                  v-model.trim="queryParam.productName"
                  placeholder="请输入产品名称"
                  allowClear />
              </a-form-item>
            </a-col>
            <a-col flex="1">
              <a-form-item label="品牌">
                <ProductBrand :id="'salesEdit-productBrandSn-'+id" v-model="queryParam.productBrandSn"></ProductBrand>
              </a-form-item>
            </a-col>
            <a-col flex="1">
              <a-form-item label="产品分类">
                <productTypeAll
                  style="width:100%;"
                  :id="'salesEdit-productType-'+id"
                  size="small"
                  placeholder="请选择产品分类"
                  @change="changeProductType"
                  v-model="productType"></productTypeAll>
              </a-form-item>
            </a-col>
            <a-col flex="1">
              <a-form-item label="满足起订量">
                <v-select code="FLAG" v-model="queryParam.unitFlag" allowClear placeholder="请选择是否满足起订量"></v-select>
              </a-form-item>
            </a-col>
            <a-col flex="1">
              <a-form-item label="产品类型">
                <a-select
                  v-model="queryParam.promoProductClz"
                  id="salesEdit-promoFlag"
                  allowClear
                  :dropdownMatchSelectWidth="false"
                  placeholder="请选择产品类型">
                  <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="GATE">
                    门槛产品
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col flex="1">
              <a-form-item label="累计产品">
                <v-select code="FLAG" v-model="queryParam.borrowFlag" allowClear placeholder="请选择是否累计产品"></v-select>
              </a-form-item>
            </a-col>
            <a-col flex="2" style="margin-bottom: 10px;">
              <a-button type="primary" @click="searchProduct" :disabled="disabled" :id="'salesEdit-refresh-'+id">查询</a-button>
              <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" :id="'salesEdit-reset-'+id">重置</a-button>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class="table-page-search-wrapper">
        <a-row :gutter="15" type="flex" justify="space-between" align="middle">
          <a-col :md="8" :sm="24" style="text-align:left;">
            <a-dropdown>
              <a-menu slot="overlay" @click="handleMenuClick" :id="'salesEdit-menu-'+id">
                <!-- <a-menu-item key="3" :id="'salesEdit-menu-3-'+id">
                全部仓库设置
              </a-menu-item>
              <a-menu-item key="2" :id="'salesEdit-menu-2-'+id">
                全部删除
              </a-menu-item>
              <a-menu-divider /> -->
                <a-menu-item key="0" :id="'salesEdit-menu-0-'+id">
                  部分仓库设置
                </a-menu-item>
                <a-menu-item key="1" :id="'salesEdit-menu-1-'+id">
                  删除已选项
                </a-menu-item>
                <a-menu-item key="4" :id="'salesEdit-menu-4-'+id">
                  批量取消促销
                </a-menu-item>
              </a-menu>
              <a-button
                :id="'salesEdit-plaction-'+id"
                type="default"
                class="button-info"
                size="small"
              >批量操作<a-icon type="down" /> </a-button>
            </a-dropdown>
            <span v-if="selectTotal" style="margin:0 10px;">已选 {{ selectTotal }} 项</span>
            <a-button
              :id="'salesEdit-allSetWare-'+id"
              type="link"
              class="button-info"
              size="small"
              @click="handleMenuClick({key:3})"
            ><a-icon type="setting"/> 全部仓库设置</a-button>
            <a-button
              :id="'salesEdit-allDel-'+id"
              type="link"
              class="button-error"
              size="small"
              @click="handleMenuClick({key:2})"
            ><a-icon type="delete"/> 全部删除</a-button>
          </a-col>
          <a-col :md="12" :sm="24" style="text-align:right;">
            <a-button
              :id="'salesEdit-searchBox-'+id"
              type="link"
              class="button-info"
              @click="showSearchBox=!showSearchBox" ><a-icon :type="showSearchBox?'close':'search'"/> 筛选</a-button>
          </a-col>
        </a-row>
      </div>

      <ve-table
        style="width:100%"
        border-y
        border-x
        border-around
        :max-height="tableHeight"
        :scroll-width="0"
        :column-width-resize-option="columnWidthResizeOption"
        :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"
        :cell-style-option="cellStyleOption"
      />
      <div v-show="dataSource.length==0" class="empty-data2"><a-empty description="暂无数据" :image="simpleImage"/></div>
    </a-spin>
    <!-- 仓库设置 -->
    <setWarehouse :title="warehouseTit" :show="openWarehouseModal" @ok="chooseWarehouseOk" @cancel="openWarehouseModal=false"></setWarehouse>
    <!-- 换促销 -->
    <updateActiveModal ref="updateActive" :pageType="true" :show="openUpActiveModal" @ok="upActiveOk" @cancel="openUpActiveModal=false"></updateActiveModal>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { Empty } from 'ant-design-vue'
import { VSelect } from '@/components'
import setWarehouse from './setWarehouse.vue'
import updateActiveModal from './updateActiveModal.vue'
import chooseWarehouse from '@/views/common/chooseWarehouse'
import ProductBrand from '@/views/common/productBrand.js'
import productTypeAll from '@/views/common/productTypeAll.js'
import {
  salesDetailExtPromoList,
  salesDetailUpdateQty,
  salesDetailInsert,
  salesDetailInsertBatchBorrow,
  salesDetailDel,
  salesDetailBatchDel,
  deletePromoAll,
  updateWarehouse
} from '@/api/salesDetailNew'

export default {
  name: 'ProductList',
  mixins: [commonMixin],
  components: {
    VSelect,
    chooseWarehouse,
    setWarehouse, // 设置仓库组件
    ProductBrand, // 产品品牌组件
    productTypeAll, // 产品分类组件
    updateActiveModal// 更换活动弹框组件
  },
  props: {
    openModal: { //  弹框显示状态
      type: Boolean,
      default: false
    },
    newLoading: Boolean,
    // 详情数据
    detailData: {
      type: Object,
      default: function () { return null }
    },
    // 表格id
    id: {
      type: String,
      default: '0'
    },
    activeList: {
      type: Array,
      default: () => []
    },
    // 已勾选的活动sn
    salesPromoSnSet: {
      type: Array,
      default: () => []
    },
    // 销售单sn
    salesBillSn: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      spinning: false,
      simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,
      // 表格列宽拖到
      columnWidthResizeOption: {
        // default false
        enable: true,
        // column resize min width
        minWidth: 50
      },
      cellStyleOption: {
        headerCellClass: ({ column, rowIndex }) => {
          if (column.align != 'center') {
            return 'table-header-cell-center'
          }
        }
      },
      dataSource: [],
      showSearchBox: true, // 是否显示筛选条件
      openWarehouseModal: false, // 打开仓库设置
      delLoading: false, // 删除logding
      disabled: false, //  查询、重置按钮是否可操作
      queryParam: {
        warehouseSn: undefined, // 仓库
        productCode: '', // 产品编码
        productName: '', // 产品名称
        productBrandSn: undefined, // 产品品牌
        productTypeSn1: '', //  产品一级分类
        productTypeSn2: '', //  产品二级分类
        productTypeSn3: '', //  产品三级分类
        promoProductClz: undefined, // 产品类型
        promoFlag: undefined,
        borrowFlag: undefined, // 是否累计
        unitFlag: undefined // 是否满足起订量
      },
      productType: [], // 已选产品分类
      disableSelectedRowKeys: [], // 禁用的行
      selectedRowKeys: [], // 已选行
      warehouseDataList: [], // 仓库列表数据
      openUpActiveModal: false, // 更换促销活动弹框
      descDetail: null, // 规则详细数据
      countData: null, // 统计信息
      warehouseTit: '', // 仓库设置唐卡标题
      showStockCol: false, // 第三方库存是否显示
      promo: null
    }
  },
  computed: {
    // 已选产品数量
    selectTotal () {
      return this.selectedRowKeys.length || 0
    },
    tableHeight () {
      const len = this.dataSource.length
      if (len == 0) return 300
      return len <= 10 ? ((len + 1) * 36) + 'px' : '360px'
    },
    // 表格复选框设置
    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 discountPriceFormat = 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 arr = [
        { title: '', field: '', key: '0', width: 20, type: 'checkbox', align: 'center' },
        { title: '序号', field: 'no', key: '1', width: 30, align: 'center', operationColumn: false },
        {
          title: '产品编码',
          field: 'productCode',
          key: '2',
          align: 'left',
          width: 100,
          operationColumn: false,
          renderBodyCell: ({ row, column, rowIndex }, h) => {
            return (
              <div>
                <span style="padding-right: 10px;">{row.productEntity.code}</span>
                {row.promotionFlag.indexOf('GIFT') >= 0 ? <a-badge count="促" numberStyle={{ backgroundColor: '#52c41a', zoom: '0.7' }}/> : ''}
                {row.promotionFlag.indexOf('GATE') >= 0 ? <a-badge count="槛" numberStyle={{ backgroundColor: '#108ee9', zoom: '0.7' }}/> : ''}
                {row.promotionFlag.indexOf('REGULAR') >= 0 ? <a-badge count="正" numberStyle={{ backgroundColor: '#ff5500', zoom: '0.7' }}/> : ''}
                {row.promotionFlag.indexOf('DISCOUNT') >= 0 ? <a-badge count="特" numberStyle={{ backgroundColor: '#faad14', zoom: '0.7' }}/> : ''}
                {row.borrowFlag == '1' ? <a-badge count="累" numberStyle={{ backgroundColor: '#aa55ff', zoom: '0.7' }}/> : ''}
                {Number(row.stockQty || 0) < Number(row.unpushedQty || 0) && row.borrowFlag != '1' ? <a-badge count="缺" numberStyle={{ zoom: '0.7' }}/> : ''}
              </div>
            )
          }
        },
        {
          title: '产品名称',
          field: 'productName',
          key: '3',
          width: 150,
          align: 'left',
          operationColumn: false,
          ellipsis: { showTitle: true },
          renderBodyCell: ({ row, column, rowIndex }, h) => {
            return (
              <div class="ellipsisCon">
                <a-tooltip placement="rightBottom">
                  <template slot="title">
                    <span>{ row.productEntity.name || '--' }</span>
                  </template>
                  <span class="ellipsisText">{ row.productEntity.name || '--' }</span>
                </a-tooltip>
              </div>
            )
          }
        },
        {
          title: '规则数量',
          field: 'rulesNums',
          key: '4',
          width: 50,
          align: 'center',
          operationColumn: false,
          renderBodyCell: ({ row, column, rowIndex }, h) => {
            return (
              row.promoRuleSnList
                ? <a-popover placement="right">
                  <template slot="content">
                    {row.promoRuleSnList.map(item => {
                      return (
                        <div
                          id={'salesEdit-gzitem-' + row.id}
                          title="点击查看详情"
                          style="padding:5px 0;cursor: pointer;"
                          onClick={() => _this.showRuleDetail(item)}
                        >{ _this.activeRuleFilter(item, row) }</div>
                      )
                    })}
                  </template>
                  <a-button type="link" id={'salesEdit-gzqty-' + row.id} size="small" class="button-info">{row.promoRuleNum}<span style="zoom:0.6;color: #666;">个∨</span></a-button>
                </a-popover> : '--'
            )
          } },
        { title: '起订量', field: 'promoUnit', key: '5', width: 60, align: 'center', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return (row.borrowFlag != '1' ? (row[column.field] || '--') : '--') } },
        {
          title: '销售数量',
          field: 'salesNums',
          key: '6',
          width: 80,
          align: 'center',
          operationColumn: false,
          renderBodyCell: ({ row, column, rowIndex }, h) => {
            return (
              !(row.promotionFlag.indexOf('GIFT') >= 0 && row.sameGiteFlag == '1') && row.borrowFlag != '1'
                ? <a-input-number
                  id={'salesEdit-qty-' + row.id}
                  size="small"
                  style="width: 100%;"
                  vModel={row.qty}
                  precision={0}
                  min={1}
                  max={99999999}
                  placeholder="请输入"
                  onBlur={(e) => _this.onCellBlur(e.target.value, row)}
                />
                : <span>{ row.qty }</span>
            )
          }
        },
        {
          title: '库存',
          field: 'stockQty',
          width: 80,
          key: '7',
          align: 'center',
          operationColumn: false,
          renderBodyCell: ({ row, column, rowIndex }, h) => {
            return (
              (row.stockQty || row.stockQty == 0) && row.borrowFlag != '1'
                ? <div>
                  {
                    Number(row.stockQty) < Number(row.unpushedQty)
                      ? <p style="margin: 0;">{ row.stockQty }(<span class="redStyle">缺{ Number(row.unpushedQty || 0) - Number(row.stockQty || 0) }</span>)</p>
                      : <p style="margin: 0;">{ row.stockQty }</p>
                  }
                </div>
                : <span>--</span>
            )
          }
        },
        {
          title: '出库仓库',
          field: 'warehouseBox',
          width: 80,
          key: '8',
          align: 'center',
          operationColumn: false,
          renderBodyCell: ({ row, column, rowIndex }, h) => {
            return (
              row.borrowFlag != '1'
                ? <a-select
                  id={'salesEdit-warehouse-' + row.id}
                  size="small"
                  style="width:100%;"
                  placeholder="请选择仓库"
                  vModel={row.warehouseSn}
                  showSearch={true}
                  onChange={() => _this.handleWarehouseBox(row)}
                  mode="default"
                  filter-option={_this.filterOption}>
                  {
                    _this.warehouseDataList.map(item => {
                      return <a-select-option key={item.warehouseSn} value={item.warehouseSn}>{ item.name }</a-select-option>
                    })
                  }
                </a-select> : <span>{ row.warehouseName }</span>
            )
          }
        },
        { title: '单位', field: 'productOrigUnit', width: 50, key: 'unit', align: 'center', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return row.productEntity.unit || '--' } },
        {
          title: '操作',
          field: 'action',
          width: 80,
          key: 'action',
          align: 'center',
          fixed: 'right',
          operationColumn: false,
          // sameGiteFlag 是否正促一致
          renderBodyCell: ({ row, column, rowIndex }, h) => {
            return (
              <div>
                {
                  row.promotionFlag.indexOf('GIFT') < 0 && row.borrowFlag != '1'
                    ? <a-button
                      id={'salesEdit-upactive-' + row.id}
                      size="small"
                      type="link"
                      disabled={_this.delLoading}
                      class="button-primary"
                      onClick={() => _this.handleUpdateActive(row)}
                    >换促销</a-button> : ''
                }
                {
                  !(row.promotionFlag.indexOf('GIFT') >= 0 && row.sameGiteFlag == '1')
                    ? <a-button
                      id={'salesEdit-del-' + row.id}
                      size="small"
                      type="link"
                      disabled={_this.delLoading}
                      class="button-error"
                      onClick={() => _this.handleDel(row)}
                    >删除</a-button> : '--'
                }
              </div>

            )
          }
        }
      ]
      // 售价权限
      if (_this.$hasPermissions('B_salesEdit_salesPrice')) {
        arr.splice(4, 0, {
          title: '售价(原价)',
          field: 'price',
          width: 100,
          key: 'price',
          align: 'right',
          operationColumn: false,
          renderBodyCell: ({ row, column, rowIndex }, h) => { return discountPriceFormat(row, row[column.field], h) }
        })
        arr.splice(5, 0, { title: '价格级别', field: 'priceLevelDictValue', width: 60, key: 'priceLevel', align: 'center', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return row[column.field] || '--' } })
        if (_this.showStockCol) {
          arr.splice(10, 0, { title: '第三方库存', field: 'thirdStockQty', key: 'thirdStockQty', width: 60, align: 'center', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return numsFormat(row[column.field]) } })
        }
        arr.splice((_this.showStockCol ? 11 : 10), 0, { title: '售价小计', field: 'totalAmount', key: 'totalAmount', width: 60, align: 'right', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return priceFormat(row[column.field]) } })
      } else {
        if (_this.showStockCol) {
          arr.splice(8, 0, { title: '第三方库存', field: 'thirdStockQty', key: 'thirdStockQty', width: 60, align: 'center', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return numsFormat(row[column.field]) } })
        }
      }
      return arr
    }
  },
  watch: {
    salesBillSn (newValue, oldValue) {
      this.resetSearchForm()
    },
    salesPromoSnSet (newValue, oldValue) {
      this.getTableData()
      this.clearTableSelect()
    },
    spinning (a, b) {
      if (a) {
        this.$emit('spinning', a)
      }
    }
  },
  methods: {
    // 选择单元格
    selectedRowChange ({ row, isSelected, selectedRowKeys }) {
      this.selectedRowKeys = selectedRowKeys
    },
    // 全选行
    selectedAllChange ({ isSelected, selectedRowKeys }) {
      this.selectedRowKeys = selectedRowKeys
    },
    // 获取表格数据
    getTableData () {
      this.disabled = true
      this.spinning = true
      this.queryParam.salesBillSn = this.salesBillSn || ''
      this.queryParam.salesPromoSnSet = this.salesPromoSnSet || []
      salesDetailExtPromoList(Object.assign(this.queryParam, {
        showStock: true
        // promoFlag: this.detailData.promoFlag
      })).then(res => {
        let data = []
        if (res.status == 200) {
          data = res.data
          const no = 0
          for (var i = 0; i < data.length; i++) {
            data[i].no = no + i + 1
            data[i].qtyBackups = data[i].qty
            data[i].productUnit = data[i].productEntity && data[i].productEntity.unit
            // 禁用选框
            if (data[i].promotionFlag.indexOf('GIFT') >= 0 && !!data[i].salesPromoDetailParentSn) {
              this.disableSelectedRowKeys.push(data[i].id)
            }
          }
          this.dataSource = data
        } else {
          this.dataSource = []
        }
        this.disabled = false
        this.spinning = false
      })
    },
    // 参与规则名称
    activeRuleFilter (val, data) {
      const row = this.activeList.length && this.activeList.find(item => item.promoRuleSn == val)
      const rule = data.salesPromoDetailList.find(item => item.promoRuleSn == val)
      return row ? (row.promotionRule.promotionRuleTypeDictValue + '-' + row.promotion.description + '(' + row.promotionRule.description + ')') + (data.borrowFlag != 1 ? '，起订量：' + rule.promoUnit : '') : ''
    },
    // 查看参与规则详情
    showRuleDetail (promoRuleSn) {
      this.$emit('showRuleDetail', promoRuleSn)
    },
    // 仓库下拉列表筛选
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    // 仓库列表加载完成
    warehouseLoad (sn, list) {
      this.warehouseDataList = list
    },
    // 显示查询条件
    showSearch () {
      this.showSearchBox = !this.showSearchBox
    },
    // 查询第三方库存
    searchThreeStockOk () {
      this.resetSearchForm()
      this.showStockCol = true
    },
    // 表格选中项
    rowSelectionFun (obj) {
      this.rowSelectionInfo = obj || null
    },
    //  选择产品分类
    changeProductType (val, opt) {
      this.queryParam.productTypeSn1 = val[0] ? val[0] : ''
      this.queryParam.productTypeSn2 = val[1] ? val[1] : ''
      this.queryParam.productTypeSn3 = val[2] ? val[2] : ''
    },
    //  重置查询
    resetSearchForm (flag) {
      this.queryParam.productCode = ''
      this.queryParam.productName = ''
      this.queryParam.warehouseSn = undefined
      this.queryParam.productBrandSn = undefined
      this.queryParam.productTypeSn1 = ''
      this.queryParam.productTypeSn2 = ''
      this.queryParam.productTypeSn3 = ''
      this.queryParam.borrowFlag = undefined
      this.queryParam.promoProductClz = undefined
      this.queryParam.unitFlag = undefined
      this.productType = []
      this.rowSelectionInfo = null
      this.getTableData()
      this.clearTableSelect()
    },
    // 查询产品，不重置
    searchProduct () {
      this.getTableData()
    },
    clearTableSelect () {
      this.disableSelectedRowKeys = []
      this.selectedRowKeys = []
    },
    // 保存添加的产品到销售列表
    saveNewProduct (row, promo, promoProductClz) {
      // 防止多次添加产品
      if (this.isInster) { return }
      this.$message.loading('正在添加产品...', 1)
      this.isInster = true
      this.spinning = true
      const params = {
        salesPromoSn: promo.salesPromoSn,
        promoRuleSn: promo.promoRuleSn,
        promoSn: promo.promoSn,
        promoProductClz: promoProductClz,
        packQty: row.productPackQty,
        productSn: row.productSn,
        showCost: row.lastStockCost,
        price: row.productPrice,
        origPrice: row.origPrice,
        promotionGiftsAmount: 0,
        usePromotionGiftsAmount: 0,
        qty: row.salesNums,
        salesBillSn: this.detailData.salesBillSn,
        salesBillNo: this.detailData.salesBillNo,
        purchaseBillSn: this.detailData.purchaseBillSn,
        purchaseBillNo: this.detailData.purchaseBillNo,
        priceLevel: row.priceLevel,
        stockSn: row.stockSn,
        promotableFlag: row.isJoinActivityProduct || 0, // 可促销标记 有活动的传1，没活动的传0
        promotionFlag: 0, // 促销标记 正品传0，促销品传1
        warehouseSn: row.warehouseSn
      }
      salesDetailInsert(params).then(res => {
        if (res.status == 200) {
          this.$message.success('产品添加成功', 2.5)
          this.resetSearchForm(true)
          this.$emit('refash', 'promo', 'add')
        } else {
          this.$emit('error', 'promo', 'add')
        }
        this.spinning = false
        this.isInster = false
      }).catch(err => {
        this.$emit('error', 'promo', 'add')
        this.isInster = false
        this.spinning = false
      })
    },
    // 累计产品到活动
    accumulateProduct (chooseData, promo, promoProductClz) {
      // 防止多次添加产品
      if (this.isInster) { return }
      this.$message.loading('正在添加产品...', 1)
      this.isInster = true
      this.spinning = true
      const params = {
        salesPromoSn: promo.salesPromoSn,
        salesBillSn: promo.salesBillSn,
        salesBillDetailList: chooseData,
        promoProductClz
      }
      salesDetailInsertBatchBorrow(params).then(res => {
        this.spinning = false
        this.isInster = false
        if (res.status == 200) {
          this.$message.success('累计产品添加成功', 2.5)
          this.resetSearchForm(true)
          this.$emit('refash', 'borrow', 'add')
        } else {
          this.$emit('error', 'borrow', 'add')
        }
      }).catch(err => {
        this.$emit('error', 'borrow', 'add')
        this.isInster = false
        this.spinning = false
      })
    },
    // 批量取消出现产品
    handleBatchCancelActive () {
      const _this = this
      if (this.selectTotal == 0) {
        _this.$message.warning('请先选择要批量取消的产品！')
        return
      }
      const len = this.selectedRowKeys.length
      const rowSelect = this.dataSource.filter(item => this.selectedRowKeys.includes(item.id))
      // 判断是否全部为赠品
      const obj = []
      const gift = []
      rowSelect && rowSelect.map(item => {
        // 赠品
        if (item.promotionFlag.indexOf('GIFT') >= 0) {
          gift.push(item.productCode)
        } else {
          // 非赠品
          obj.push(item.salesBillDetailSn)
        }
      })
      // 如果全部是赠品，不能转为正常产品
      if (gift.length == len) {
        this.$info({
          title: '提示',
          content: '所选全部为赠品，其不能转为正常产品！',
          centered: true,
          okText: '知道了'
        })
        return
      }
      this.$confirm({
        title: '提示',
        content: '已选产品' + len + '项，' + (gift.length ? '其中包含赠品' + gift.join('，') + '（赠品不能转正常产品），确认要继续批量取消促销转为正常产品吗？' : '确认要批量取消促销转为正常产品吗？'),
        centered: true,
        onOk () {
          _this.spinning = true
          const params = {
            salesBillDetailSnList: obj,
            salesBillSn: _this.salesBillSn
          }
          // 更换活动
          _this.$emit('upActive', params, 1)
        }
      })
    },
    // 删除全部产品
    handleBatchDelAll () {
      const _this = this
      if (_this.dataSource.length == 0) {
        _this.$message.warning('暂无可删除的产品！')
        return
      }
      this.$confirm({
        title: '提示',
        content: '确认要删除全部已选活动产品吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          deletePromoAll({ salesBillSn: _this.salesBillSn }).then(res => {
            if (res.status == 200) {
              _this.searchProduct()
              _this.$emit('refash', 'promo', 'batchDel')
              _this.$message.success(res.message)
            }
            _this.spinning = false
          })
        }
      })
    },
    // 批量删除已选产品
    handleBatchDel () {
      const _this = this
      if (this.selectTotal == 0) {
        _this.$message.warning('请先选择要批量删除产品！')
        return
      }
      const selectedRows = this.dataSource.filter(item => this.selectedRowKeys.includes(item.id))
      const obj = selectedRows ? selectedRows.map(item => item.salesBillDetailSn) : []
      this.$confirm({
        title: '提示',
        content: '已选产品' + obj.length + '项，确认要批量删除吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          salesDetailBatchDel({
            salesBillSn: _this.salesBillSn,
            salesBillDetailSnList: obj
          }).then(res => {
            if (res.status == 200) {
              _this.searchProduct()
              _this.clearTableSelect()
              _this.$emit('refash', 'promo', 'batchDel')
              _this.$message.success(res.message)
            }
            _this.spinning = false
          })
        }
      })
    },
    // 设置单个出库仓库
    handleWarehouseBox (row) {
      const snArr = [row.salesBillDetailSn]
      const ajax_data = {
        warehouseSn: row.warehouseSn,
        salesBillDetailSnList: snArr,
        salesBillSn: this.salesBillSn,
        allFlag: false,
        salesPromoDetailSnSet: row.salesPromoDetailList ? [row.salesPromoDetailList[0].salesPromoDetailSn] : undefined
      }
      this.setWarehouseInfo(ajax_data)
    },
    // 选择仓库确认
    chooseWarehouseOk (sn) {
      const _this = this
      const selectedRows = _this.dataSource.filter(item => _this.selectedRowKeys.includes(item.id))
      const obj = selectedRows ? selectedRows.map(item => item.salesBillDetailSn) : []
      const mergedArr = _this.getSalesPromoSnList(obj && obj.length > 0 ? selectedRows : _this.dataSource)
      const ajaxData = {
        warehouseSn: sn,
        salesBillDetailSnList: obj,
        salesBillSn: _this.salesBillSn,
        allFlag: obj && obj.length === 0, // 设置全部参数
        salesPromoDetailSnSet: mergedArr
      }
      _this.setWarehouseInfo(ajaxData)
    },
    // 筛选salesPromoSnSet值
    getSalesPromoSnList (arr) {
      // 借助reduce方法和Set来合并salesPromoDetailSn值并去重
      const mergedAndUniqueVals = arr.reduce((acc, item) => {
        // 遍历当前项的salesPromoDetailList数组
        item.salesPromoDetailList.forEach(subItem => {
          // 将每个subItem的salesPromoDetailSn添加到累加器Set中
          acc.add(subItem.salesPromoDetailSn)
        })
        // 返回累加器Set供下一次迭代使用
        return acc
      }, new Set())

      const resultArr = Array.from(mergedAndUniqueVals)
      return resultArr
    },
    // 更改仓库信息
    setWarehouseInfo (data) {
      const _this = this
      _this.spinning = true
      updateWarehouse(data).then(res => {
        if (res.status == 200) {
          _this.$message.success(res.message)
          _this.$emit('refash', 'promo', 'update')
        }
        _this.openWarehouseModal = false
        _this.searchProduct()
        _this.clearTableSelect()
        _this.spinning = false
      })
    },
    // 更多操作下拉菜单
    handleMenuClick (e) {
      const _this = this
      if (e.key == 0) { // 部分仓库设置
        if (_this.selectTotal == 0) {
          _this.$message.warning('请先选择要批量设置的产品！')
        } else {
          _this.warehouseTit = '部分仓库设置'
          _this.openWarehouseModal = true
        }
      } else if (e.key == 1) { // 删除已选项
        this.handleBatchDel()
      } else if (e.key == 3) { // 全部仓库设置
        if (_this.dataSource.length == 0) {
          _this.$message.warning('暂无可设置的产品！')
          return
        }
        _this.clearTableSelect()
        _this.warehouseTit = '全部仓库设置'
        _this.openWarehouseModal = true
      } else if (e.key == 4) { // 批量取消促销
        _this.handleBatchCancelActive()
      } else { // 全部删除
        _this.clearTableSelect()
        _this.handleBatchDelAll()
      }
    },
    // 打开换促销活动列表选项
    handleUpdateActive (record) {
      this.$refs.updateActive.getActiveList({
        productSn: record.productSn,
        salesBillSn: this.salesBillSn,
        salesBillDetailSn: record.salesBillDetailSn
      }, record)
      this.openUpActiveModal = true
    },
    // 已选产品数量修改
    onCellBlur (val, record) {
      const _this = this
      //  光标移出，值发生改变再调用编辑接口
      if (val && val != record.qtyBackups) {
        _this.spinning = true
        salesDetailUpdateQty({
          salesBillDetailSn: record.salesBillDetailSn,
          qty: record.qty,
          salesBillSn: _this.salesBillSn
        }).then(res => {
          if (res.status == 200) {
            _this.$emit('refash', 'promo', 'update')
            _this.$message.success(res.message)
          }
          _this.searchProduct()
          _this.spinning = false
        })
      } else {
        record.qty = record.qtyBackups
      }
    },
    // 删除产品
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认要删除吗？',
        centered: true,
        closable: true,
        onOk () {
          _this.delLoading = true
          _this.spinning = true
          salesDetailDel({ salesBillDetailSn: row.salesBillDetailSn, salesBillSn: _this.salesBillSn }).then(res => {
            if (res.status == 200) {
              _this.searchProduct()
              _this.$emit('refash', 'promo', 'del')
              _this.$message.success(res.message)
            }
            _this.delLoading = false
            _this.spinning = false
          })
        }
      })
    },
    // 确定更换促销活动
    async upActiveOk (salesPromoSnList, editRow) {
      const params = {
        salesBillDetailSn: editRow.salesBillDetailSn,
        salesBillSn: this.salesBillSn,
        priceLevel: editRow.priceLevel,
        salesPromoSnList: salesPromoSnList
      }
      // 更换活动
      this.$emit('upActive', params, 1)
    },
    // 更换活动成功
    upAcitveSuccess () {
      this.spinning = false
      this.$refs.updateActive.confirmLoading = false
      this.openUpActiveModal = false
      this.clearTableSelect()
      this.searchProduct()
    }
  }
}
</script>

<style lang="less">
  .empty-data2{
        color: #999;
        text-align: center;
        padding: 20px;
        position: absolute;
        bottom: 50px;
        width: 100%;
    }
  .table-header-cell-center{
    text-align: center!important;
  }
   .ant-input-number-sm input{
    text-align: center;
   }
</style>
