<template>
  <div>
    <!-- 筛选条件 -->
    <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="累计产品">
              <v-select code="FLAG" 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-left:10px;">已选{{ selectTotal }}项</span>
        </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>

    <!-- 已选配件列表 -->
    <a-spin :spinning="spinning" tip="Loading...">
      <ve-table
        style="width:100%"
        border-y
        border-x
        border-around
        :max-height="300"
        :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"
      />
    </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 { 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,
  deleteAll,
  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,
      // 表格列宽拖到
      columnWidthResizeOption: {
        // default false
        enable: true,
        // column resize min width
        minWidth: 50
      },
      dataSource: [],
      showSearchBox: true, // 是否显示筛选条件
      openWarehouseModal: false, // 打开仓库设置
      delLoading: false, // 删除logding
      disabled: false, //  查询、重置按钮是否可操作
      queryParam: {
        warehouseSn: undefined, // 仓库
        productCode: '', // 产品编码
        productName: '', // 产品名称
        productBrandSn: undefined, // 产品品牌
        productTypeSn1: '', //  产品一级分类
        productTypeSn2: '', //  产品二级分类
        productTypeSn3: '', //  产品三级分类
        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
    },
    // 表格复选框设置
    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 arr = [
        { title: '', field: '', key: '0', width: 40, type: 'checkbox', align: 'center' },
        { title: '序号', field: 'no', key: '1', width: 50, align: 'center', operationColumn: false },
        {
          title: '产品编码',
          field: 'productCode',
          key: '2',
          align: 'center',
          width: 120,
          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('DISCOUNT') >= 0 ? <a-badge count="特" numberStyle={{ backgroundColor: '#faad14', 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' }}/> : ''}
                {Number(row.stockQty || 0) < Number(row.unpushedQty || 0) ? <a-badge count="缺" numberStyle={{ zoom: '0.7' }}/> : ''}
              </div>
            )
          }
        },
        { title: '产品名称', field: 'productName', key: '3', width: 150, align: 'center', operationColumn: false, ellipsis: { showTitle: true }, renderBodyCell: ({ row, column, rowIndex }, h) => { return row.productEntity.name || '--' } },
        {
          title: '规则数量',
          field: 'rulesNums',
          key: '4',
          width: 60,
          align: 'center',
          operationColumn: false,
          renderBodyCell: ({ row, column, rowIndex }, h) => {
            return (
              <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) }</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: 100, align: 'center', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return row[column.field] || '--' } },
        {
          title: '销售数量',
          field: 'salesNums',
          key: '6',
          width: 80,
          align: 'center',
          operationColumn: false,
          renderBodyCell: ({ row, column, rowIndex }, h) => {
            return (
              !(row.promotionFlag == 'GIFT' && row.salesPromoDetailParentSn)
                ? <a-input-number
                  id={'salesEdit-qty-' + row.id}
                  size="small"
                  vModel={row.qty}
                  precision={0}
                  min={1}
                  max={99999999}
                  placeholder="请输入"
                  onBlur={(e) => _this.onCellBlur(e.target.value, row)}
                  style={{ width: '100%', color: row.qty >= row.unitQtyR ? '' : 'red' }}/>
                : <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)
                ? <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: 100,
          key: '8',
          align: 'center',
          operationColumn: false,
          renderBodyCell: ({ row, column, rowIndex }, h) => {
            return (
              <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>
            )
          }
        },
        { title: '单位', field: 'productOrigUnit', width: 50, key: 'unit', align: 'center', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return row.productEntity.unit || '--' } },
        {
          title: '操作',
          field: 'action',
          width: 100,
          key: 'action',
          align: 'center',
          fixed: 'right',
          operationColumn: false,
          renderBodyCell: ({ row, column, rowIndex }, h) => {
            return (
              <div>
                {
                  row.promotionFlag != 'GIFT'
                    ? <a-button
                      id={'salesEdit-upactive-' + row.id}
                      size="small"
                      type="link"
                      loading={_this.delLoading}
                      class="button-primary"
                      onClick={() => _this.handleUpdateActive(row)}
                    >换促销</a-button> : ''
                }
                {
                  !(row.promotionFlag == 'GIFT' && row.salesPromoDetailParentSn)
                    ? <a-button
                      id={'salesEdit-del-' + row.id}
                      size="small"
                      type="link"
                      loading={_this.delLoading}
                      class="button-error"
                      onClick={() => _this.handleDel(row)}
                    >删除</a-button> : ''
                }
              </div>
            )
          }
        }
      ]
      if (this.showStockCol) {
        arr.splice(7, 0, { title: '第三方库存', field: 'thirdStockQty', key: 'thirdStockQty', width: 80, align: 'center', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return numsFormat(row[column.field]) } })
      }
      // 售价权限
      if (this.$hasPermissions('B_salesEdit_salesPrice')) {
        arr.splice(4, 0, { title: '售价(原价)',
          field: 'price',
          width: 120,
          key: 'price',
          align: 'center',
          operationColumn: false,
          renderBodyCell: ({ row, column, rowIndex }, h) => {
            return <div>{_this.toThousands(row[column.field])}<span style="color:#666;margin-left:3px;" title="原价">({_this.toThousands(row.origPrice)})</span></div>
          }
        })
        arr.splice(5, 0, { title: '价格级别', field: 'priceLevelDictValue', width: 80, key: 'priceLevel', align: 'center', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return row[column.field] || '--' } })
        arr.splice((_this.showStockCol ? 10 : 9), 0, { title: '售价小计', field: 'totalAmount', key: 'totalAmount', width: 80, align: 'center', operationColumn: false, renderBodyCell: ({ row, column, rowIndex }, h) => { return priceFormat(row[column.field]) } })
      }
      return arr
    }
  },
  watch: {
    salesBillSn (newValue, oldValue) {
      this.resetSearchForm()
    },
    salesPromoSnSet (newValue, oldValue) {
      this.resetSearchForm()
    },
    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 == 'GIFT' && !!data[i].salesPromoDetailParentSn) {
              this.disableSelectedRowKeys.push(data[i].id)
            }
          }
          this.dataSource = data
        } else {
          this.dataSource = []
        }
        this.disabled = false
        this.spinning = false
      })
    },
    // 参与规则名称
    activeRuleFilter (val) {
      const row = this.activeList.length && this.activeList.find(item => item.promoRuleSn == val)
      return row ? row.promotion.description + '-' + row.promotionRule.description : ''
    },
    // 查看参与规则详情
    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.showStockCol = true
      this.resetSearchForm()
    },
    // 表格选中项
    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.unitFlag = undefined
      this.productType = []
      this.rowSelectionInfo = null
      this.getTableData()
      this.clearTableSelect()
      this.showStockCol = false
    },
    // 查询产品，不重置
    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')
        }
        this.spinning = false
        this.isInster = false
      }).catch(err => {
        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
      }
      salesDetailInsertBatchBorrow(params).then(res => {
        if (res.status == 200) {
          if (res.data && res.data.length) {
            const tipInfo = res.data.map((item, i) => { return <p>{item}，无法添加！</p> })
            this.$info({
              title: '提示',
              content: tipInfo,
              centered: true,
              okText: '知道了'
            })
            return
          }
          this.$message.success('累计产品添加成功', 2.5)
          this.resetSearchForm(true)
          this.$emit('refash', 'promo')
        }
        this.spinning = false
        this.isInster = false
      }).catch(err => {
        this.isInster = false
        this.spinning = false
      })
    },
    // 批量取消出现产品
    handleBatchCancelActive () {
      const _this = this
      if (this.selectTotal == 0) {
        _this.$message.warning('请先选择要批量取消的产品！')
        return
      }
      const rowSelect = this.dataSource.filter(item => this.selectedRowKeys.includes(item.id))
      // 判断是否全部为赠品
      const obj = []
      const gift = []
      rowSelect && rowSelect.map(item => {
        // 赠品
        if (item.promotionFlag == 'GIFT') {
          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', '0', params)
        }
      })
    },
    // 删除全部产品 this.promo ? this.promo.salesPromoSn : ''
    handleBatchDelAll () {
      const _this = this
      if (_this.dataSource.length == 0) {
        _this.$message.warning('暂无可删除的已选产品！')
        return
      }
      this.$confirm({
        title: '提示',
        content: '确认要删除全部已选产品吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          deleteAll({ salesBillSn: _this.salesBillSn, salesPromoSn: '' }).then(res => {
            if (res.status == 200) {
              _this.searchProduct()
              _this.$emit('refash', 'promo')
              _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,
            salesPromoSn: '',
            salesBillDetailSnList: obj
          }).then(res => {
            if (res.status == 200) {
              _this.searchProduct()
              _this.$emit('refash', 'promo')
              _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,
        salesPromoSn: ''
      }
      this.setWarehouseInfo(ajax_data)
    },
    // 选择仓库确认
    chooseWarehouseOk (sn) {
      const _this = this
      const snArr = []
      _this.rowSelectionInfo.selectedRows.forEach(item => {
        snArr.push(item.salesBillDetailSn)
      })
      const ajax_data = {
        warehouseSn: sn,
        salesBillDetailSnList: snArr,
        salesBillSn: _this.salesBillSn,
        salesPromoSn: '',
        allFlag: _this.warehouseTit ? true : undefined
      }
      _this.setWarehouseInfo(ajax_data)
    },
    // 更改仓库信息
    setWarehouseInfo (data) {
      const _this = this
      _this.spinning = true
      updateWarehouse(data).then(res => {
        console.log(res)
        if (res.status == 200) {
          _this.$message.success(res.message)
          _this.$emit('refash', 'promo')
        }
        _this.openWarehouseModal = false
        _this.searchProduct()
        _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) { // 全部仓库设置
        _this.clearTableSelect()
        _this.warehouseTit = '全部仓库设置'
        _this.openWarehouseModal = true
      } else if (e.key == 4) { // 批量取消促销
        _this.handleBatchCancelActive()
      } else { // 全部删除
        _this.handleBatchDelAll()
      }
    },
    // 打开换促销活动列表选项
    handleUpdateActive (record) {
      console.log('22222222:', this.promo)
      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,
          salesPromoSn: ''
        }).then(res => {
          if (res.status == 200) {
            _this.$emit('refash', 'promo')
            _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, salesPromoSn: '' }).then(res => {
            if (res.status == 200) {
              _this.searchProduct()
              _this.$emit('refash', 'promo')
              _this.$message.success(res.message)
            }
            _this.delLoading = false
            _this.spinning = false
          })
        }
      })
    },
    // 确定更换促销活动
    async upActiveOk (salesPromoSnList, editRow) {
      this.spinning = true
      const params = {
        salesBillDetailSn: editRow.salesBillDetailSn,
        salesBillSn: this.salesBillSn,
        priceLevel: editRow.priceLevel,
        salesPromoSnList: salesPromoSnList
      }
      // 更换活动
      this.$emit('upActive', params)
    },
    // 更换活动成功
    upAcitveSuccess () {
      this.spinning = false
      this.$refs.updateActive.confirmLoading = false
      this.openUpActiveModal = false
      this.clearTableSelect()
      this.searchProduct()
    }
  }
}
</script>

<style lang="less">
   .ant-input-number-sm input{
    text-align: center;
   }
   .alert-bar{
    display: flex;
    justify-content: space-between;
    align-items: center;
    .countData{
      span{
        margin: 0 2px;
        color: rgb(0, 153, 255);
      }
      span.cor1{
        color: rgb(248, 132, 0);
      }
      b{
        font-weight: bold;
        span{
          color: red;
          font-weight: normal;
        }
      }
    }
    > div{
      &:first-child{
        flex-grow: 1;
        width:70%;
        padding-right: 100px;
      }
    }
   }
</style>
