<template>
  <div :style="{padding:type=='edit'?'10px':0}">
    <a-spin :spinning="spinning" tip="Loading...">
      <ve-table
        style="width:100%"
        border-y
        border-x
        border-around
        row-key-field-name="salesPromoSn"
        :checkbox-option="checkboxOption"
        :column-width-resize-option="columnWidthResizeOption"
        :cell-style-option="cellStyleOption"
        :row-style-option="{clickHighlight: true}"
        :cellSelectionOption="{enable: false}"
        :virtual-scroll-option="{enable: false}"
        :columns="columns"
        :table-data="tableData" />
    </a-spin>
    <!-- 活动规则详情 -->
    <detailModal :openModal="openDetailModal" pageType="salesPage" :title="promoRuleTitle" :itemSn="promoRuleSn" @close="closeDetailModal"></detailModal>
    <!-- 导入产品 -->
    <importGuideModal
      v-if="type=='edit'"
      ref="importGuideModal"
      :openModal="openGuideModal"
      @close="closeGuideModel"
      @ok="hanldeImportOk" />
    <!-- 查看累计产品 -->
    <totalProductDetailModal ref="totalProductModal" :show="openTotalProductModal" @cancel="openTotalProductModal=false"></totalProductDetailModal>
    <!-- 查看买赠产品详情 -->
    <normalProductDetailModal ref="normalProductModal" :buyGiftsInfo="buyGiftsInfo" :openModal="openNormalProductModal" @close="openNormalProductModal=false"></normalProductDetailModal>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import detailModal from '@/views/promotionRulesManagement/dealerPromotions/detailModal.vue'
import totalProductDetailModal from './totalProductDetailModal.vue'
import normalProductDetailModal from './normalProductDetailModal.vue'
import ImportGuideModal from './importGuideModal.vue'
import { salesDisablePromo, salesEnablePromoPromo, salesBatchInsert, salesDetailInsertBatchBorrow } from '@/api/salesDetailNew'
import { salesPromoSaveSort } from '@/api/salesNew'
export default {
  mixins: [commonMixin],
  components: { detailModal, ImportGuideModal, totalProductDetailModal, normalProductDetailModal },
  props: {
    type: {
      type: String,
      default: 'edit'
    },
    activeList: {
      type: Array,
      default: () => []
    },
    // 仓库sn
    warehouseSn: {
      type: String,
      default: ''
    },
    // 销售单sn
    salesBillSn: {
      type: String,
      default: ''
    },
    showCols: {
      type: Array,
      default: () => []
    },
    hasNormal: {
      type: Boolean,
      default: true
    }
  },
  watch: {
    activeList: {
      handler (val) {
        if (!this.hasInit) {
          this.tableData = []
          this.getDataList(val)
        }
      },
      immediate: true
    }
  },
  data () {
    return {
      hasInit: false,
      spinning: false,
      // 表格列宽拖到
      columnWidthResizeOption: {
        // default false
        enable: true,
        // column resize min width
        minWidth: 50
      },
      openTotalProductModal: false, // 查看累计产品
      openNormalProductModal: false, // 查看买赠产品详情
      // 表格复选框
      checkboxOption: {
        hideSelectAll: true,
        selectedRowKeys: [],
        // 禁用的选择（禁止勾选或者禁止取消勾选）
        disableSelectedRowKeys: [],
        // 行选择改变事件
        selectedRowChange: ({ row, isSelected, selectedRowKeys }) => {
          // 当前勾选产品
          const endSelProduct = selectedRowKeys[selectedRowKeys.length - 1]
          // 叠加多选
          if (endSelProduct && row.promotionRule && row.promotionRule.stackFlag == '1') {
            const rows = this.tableData.filter(item => selectedRowKeys.includes(item.salesPromoSn) && item.promotionRule && item.promotionRule.stackFlag == '1')
            this.checkboxOption.selectedRowKeys = rows.map(item => item.salesPromoSn)
          } else {
            // 非叠加单选
            this.checkboxOption.selectedRowKeys = isSelected ? [endSelProduct] : []
          }
          // 查询此活动下的已选产品列表
          this.$emit('selected', this.checkboxOption.selectedRowKeys)
        }
      },
      // 单元格样式
      cellStyleOption: {
        headerCellClass: ({ column, rowIndex }) => {
          if (column.key >= 4 && column.key <= 8) {
            return 'table-header-cell-blue'
          }
          if (column.key >= 9 && column.key < 12) {
            return 'table-header-cell-org'
          }
          if (column.key >= 12 && column.key <= 15) {
            return 'table-header-cell-red'
          }
          if (column.key >= 16 && column.key <= 18) {
            return 'table-header-cell-green'
          }
          if (column.key >= 19 && column.key <= 21) {
            return 'table-header-cell-zs'
          }
        },
        bodyCellClass: ({ row, column, rowIndex }) => {
        }
      },
      // 筛选
      ruleTypeList: [
        { value: 'BUY_PROD_GIVE_PROD', label: '买赠', selected: true },
        { value: 'BUY_PROD_GIVE_MONEY', label: '采购额', selected: true },
        { value: 'PROMO_PROD', label: '特价', selected: true }
      ],
      ruleEnableList: [
        { value: '1', label: '启用', selected: true },
        { value: '0', label: '禁用', selected: true }
      ],
      searchData: {
        ruleType: [],
        enable: []
      },
      // 表格列表
      tableData: [],
      openDetailModal: false, // 规则详情弹框
      promoRuleSn: null, // 规则sn
      promoRuleTitle: '',
      disabledActiveOption: null, // 禁用规则选项
      enableActiveOption: null, // 启用规则选项
      openGuideModal: false, //  导入产品引导
      buyGiftsInfo: null // 买赠产品弹窗详情信息
    }
  },
  computed: {
    columns () {
      const _this = this
      // 格式化数字金额单元格
      const formatTd = (row, column, rowIndex, uniKey, fun) => {
        const ismktj = column.field == 'specialPriceSelected' && row.totalPromoOrigAmount
        console.log(row[column.field], row[column.field] != undefined, column.field)
        if (row[column.field] != undefined) {
          const isred = column.field == 'regularNextVal' && row[column.field] > 0
          return (<div onClick={() => fun ? fun(row, uniKey) : false}><span class={fun ? 'table-link-btn' : (column.field == 'geteBalance' || isred) ? 'table-word-color' : ''}>{row[column.field]}</span>{ismktj ? <span>({row.totalPromoOrigAmount})</span> : ''}<span style="font-size:10px;zoom:0.7;margin-left:3px;">{row[uniKey]}</span></div>)
        } else {
          return ''
        }
      }
      const cols = [
        {
          field: '',
          key: '1',
          title: '序号',
          width: 25,
          align: 'center',
          fixed: 'left',
          renderBodyCell: ({ row, column, rowIndex }, h) => {
            return ++rowIndex
          }
        },
        {
          field: 'promotionRuleType',
          key: '2',
          width: 50,
          title: '类型',
          align: 'center',
          fixed: 'left',
          renderBodyCell: ({ row, column, rowIndex }, h) => {
            const isTejia = row && row.promotionRule && row.promotionRule.promotionRuleType == 'PROMO_PROD' && row.promotionRule.stackFlag == 1 && _this.type == 'edit' // 是否特价叠加
            const tejiaLen = _this.tableData.filter(item => item.promotionRule && item.promotionRule.promotionRuleType == 'PROMO_PROD' && item.promotionRule.stackFlag == 1).length // 特价叠加活动数量
            const tjStart = _this.tableData.findIndex(item => item.promotionRule && item.promotionRule.promotionRuleType == 'PROMO_PROD' && item.promotionRule.stackFlag == 1) // 特价叠加活动开始索引
            // 特价活动上移下移排序
            const equalWord = <div class="table-arrow-box">
              {rowIndex > tjStart ? <span class="up" onClick={() => _this.moveTjRow(row, rowIndex, 1)} title="上移">⇡</span> : ''}
              {rowIndex < tjStart + tejiaLen - 1 ? <span class="down" onClick={() => _this.moveTjRow(row, rowIndex, 0)} title="下移">⇣</span> : <span></span>}
            </div>
            // 买产品送产品  同款产品 是累计产品才弹详情窗
            // if (row.promotionRule.promotionRuleType === 'BUY_PROD_GIVE_PROD' && row.promotionRule.borrowFlag == '1' && row.promotionRule.regularSameFlag == '1') {
            // return (<div style="width:100%;display:flex;justify-content: space-between;">
            //   <div class="table-link-text" onClick={() => _this.showBuyGifts(row)} style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis;" title={row[column.field]}>{row[column.field]}</div>
            //   {isTejia && tejiaLen > 1 ? equalWord : ''}
            // </div>)
            // } else {
            return (<div style="width:100%;display:flex;justify-content: space-between;">
              <div style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis;" title={row[column.field]}>{row[column.field]}</div>
              {isTejia && tejiaLen > 1 ? equalWord : ''}
            </div>)
            // }
          },
          // 筛选项
          filter: {
            filterList: _this.ruleTypeList,
            isMultiple: true,
            // filter confirm
            filterConfirm: (filterList) => {
              const labels = filterList
                .filter((x) => x.selected)
                .map((x) => x.value)
              _this.searchData.ruleType = labels
              _this.filtrateList()
            },
            // filter reset
            filterReset: (filterList) => {
              filterList.map(x => { x.selected = true })
              _this.searchData.ruleType = []
              _this.filtrateList()
            }
          }
        },
        { field: 'promotionRuleDesc',
          key: '3',
          width: 110,
          title: '规则简称',
          align: 'center',
          fixed: 'left',
          renderBodyCell: ({ row, column, rowIndex }, h) => {
            let mkInfo = ''
            if (row.promotionRule.gateFlag === '1') {
              if (row.promotionRule.gateType === 'RATIO_AMOUNT') {
                mkInfo = `购买门槛产品金额 ${row.promotionRule.gateValue ? (row.promotionRule.gateValue * 100).toFixed(2) : '0.00'}% 作为配额`
              } else if (row.promotionRule.gateType === 'MIN_AMOUNT') {
                mkInfo = `购买门槛产品满最低金额 ${this.toThousands(row.promotionRule.gateValue)} 元，不限制配额`
              } else {
                if (row.promotionRule.promotionRuleType != 'PROMO_PROD') {
                  mkInfo = `购买满 ${this.toThousands(row.promotionRule.gateValue)} 元门槛产品，可使用 ${this.toThousands(row.promotionRule.quotaAmount)} 元配额，采购规则中的正价商品`
                } else {
                  mkInfo = `购买每满 ${row.promotionRule.gateUnit === 'YUAN' ? this.toThousands(row.promotionRule.gateValue) : row.promotionRule.gateValue} ${row.promotionRule.gateUnit === 'YUAN' ? '元' : '个'}门槛产品，可采购 ${row.promotionRule.quotaAmount} 个特价产品`
                }
              }
            }
            return (<div style="width:100%;display:flex;justify-content: space-between;" onClick={() => _this.showDesc(row)}>
              <div class="table-link-text">
                <a-popover placement="right">
                  <template slot="title">
                    {row.promotionTitle + '（' + row[column.field] + '）'}
                  </template>
                  <template slot="content">
                    <div><strong>规则门槛：</strong>{row.promotionRule.gateFlag === '1' ? <div>{mkInfo}</div> : <span>无</span>}</div>
                    <div><strong>规则：</strong><div domPropsInnerHTML={row.promotionRule.ruleInfo}></div></div>
                  </template>
                  <span style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis;">{row[column.field]}</span>
                </a-popover>
              </div>
              <div style="position:absolute;right:0;">
                {row.promotionRule.stackFlag == 1 ? <a-badge count="叠" numberStyle={{ backgroundColor: '#00aa00', marginLeft: '2px', zoom: '0.7' }}/> : ''}
                {row.promotionRule.borrowFlag == 1 ? <a-badge count="累" numberStyle={{ backgroundColor: '#aa55ff', marginLeft: '2px', zoom: '0.7' }} /> : ''}
              </div>
            </div>)
          }
        },
        {
          title: '门槛产品',
          children: [
            {
              field: 'gateSelected',
              key: '4',
              title: '已选',
              width: 50,
              align: 'center',
              renderBodyCell: ({ row, column, rowIndex }, h) => formatTd(row, column, rowIndex, 'gateUnit')
            },
            {
              field: 'gateTotal',
              key: '5',
              title: '累计',
              width: 50,
              align: 'center',
              renderBodyCell: ({ row, column, rowIndex }, h) => formatTd(row, column, rowIndex, 'gateUnit')
              // renderBodyCell: ({ row, column, rowIndex }, h) => formatTd(row, column, rowIndex, 'gateUnit', _this.openTotalProduct)
            },
            {
              field: 'geteBalance',
              key: '6',
              title: '差额',
              width: 50,
              align: 'center',
              renderBodyCell: ({ row, column, rowIndex }, h) => formatTd(row, column, rowIndex, 'gateUnit')
            },
            {
              field: 'gateQuota',
              key: '7',
              title: '配额',
              width: 50,
              align: 'center',
              renderBodyCell: ({ row, column, rowIndex }, h) => formatTd(row, column, rowIndex, 'quotaUnit')
            },
            {
              field: 'unUseGateQuota',
              key: '8',
              title: '未用配额',
              width: 60,
              align: 'center',
              renderBodyCell: ({ row, column, rowIndex }, h) => formatTd(row, column, rowIndex, 'quotaUnit')
            }
          ]
        },
        {
          title: '特价',
          children: [
            {
              field: 'specialPriceSelected',
              key: '9',
              title: '已选',
              width: 50,
              align: 'center',
              renderBodyCell: ({ row, column, rowIndex }, h) => formatTd(row, column, rowIndex, 'discountRuleUnit')
            },
            {
              field: 'discountRuleValue',
              key: '10',
              title: '基础',
              width: 60,
              align: 'center',
              renderBodyCell: ({ row, column, rowIndex }, h) => formatTd(row, column, rowIndex, 'discountRuleUnit')
            },
            {
              field: 'discountRuleNextValue',
              key: '11',
              title: '下阶差',
              width: 60,
              align: 'center',
              renderBodyCell: ({ row, column, rowIndex }, h) => formatTd(row, column, rowIndex, 'discountRuleUnit')
            }
          ]
        },
        {
          title: '正价产品',
          children: [
            {
              field: 'regularSelected',
              key: '12',
              title: '已选',
              width: 50,
              align: 'center',
              renderBodyCell: ({ row, column, rowIndex }, h) => formatTd(row, column, rowIndex, 'regularUnit')
            },
            {
              field: 'regularTotal',
              key: '13',
              title: '累计',
              width: 50,
              align: 'center',
              renderBodyCell: ({ row, column, rowIndex }, h) => formatTd(row, column, rowIndex, 'regularUnit')
              // renderBodyCell: ({ row, column, rowIndex }, h) => formatTd(row, column, rowIndex, 'regularUnit', _this.openTotalProduct)
            },
            {
              field: 'regularBaseVal',
              key: '14',
              title: '基础',
              width: 60,
              align: 'center',
              renderBodyCell: ({ row, column, rowIndex }, h) => formatTd(row, column, rowIndex, 'regularUnit')
            },
            {
              field: 'regularNextVal',
              key: '15',
              title: '下阶差',
              width: 60,
              align: 'center',
              renderBodyCell: ({ row, column, rowIndex }, h) => formatTd(row, column, rowIndex, 'regularUnit')
            }
          ]
        },
        {
          title: '促销品',
          children: [
            {
              field: 'promoLimit',
              key: '16',
              title: '额度',
              width: 50,
              align: 'center',
              renderBodyCell: ({ row, column, rowIndex }, h) => formatTd(row, column, rowIndex, 'promoUnit')
            },
            {
              field: 'promoSelected',
              key: '17',
              title: '已选',
              width: 50,
              align: 'center',
              renderBodyCell: ({ row, column, rowIndex }, h) => formatTd(row, column, rowIndex, 'promoUnit')
            },
            {
              field: 'promoBalance',
              key: '18',
              title: '差额',
              width: 50,
              align: 'center',
              renderBodyCell: ({ row, column, rowIndex }, h) => formatTd(row, column, rowIndex, 'promoUnit')
            }
          ]
        },
        {
          title: '采购额',
          children: [
            {
              field: 'purchaseLimit',
              key: '19',
              title: '额度',
              width: 50,
              align: 'center',
              renderBodyCell: ({ row, column, rowIndex }, h) => formatTd(row, column, rowIndex, 'purchaseUnit')
            },
            {
              field: 'purchaseSelected',
              key: '20',
              title: '已选',
              width: 50,
              align: 'center',
              renderBodyCell: ({ row, column, rowIndex }, h) => formatTd(row, column, rowIndex, 'purchaseUnit')
            },
            {
              field: 'purchaseSurplus',
              key: '21',
              title: '结余',
              width: 50,
              align: 'center',
              renderBodyCell: ({ row, column, rowIndex }, h) => formatTd(row, column, rowIndex, 'purchaseUnit')
            }
          ]
        },
        { field: 'totalCategory', key: '22', title: '款数', width: 50, align: 'center', fixed: 'right' },
        { field: 'totalQty', key: '23', title: '数量', width: 50, align: 'center', fixed: 'right' }
      ]
      // 复选框
      cols.unshift({
        field: '',
        key: '0',
        type: 'checkbox',
        title: '',
        width: 23,
        align: 'center',
        fixed: 'left'
      })
      // 销售价权限
      if (this.type == 'view' && this.$hasPermissions('B_salesDetail_salesPrice') || this.type == 'edit' && this.$hasPermissions('B_salesEdit_salesPrice')) {
        cols.push({ field: 'totalAmount', key: '24', title: '总金额', width: 60, align: 'center', fixed: 'right', renderBodyCell: ({ row, column, rowIndex }, h) => { return this.toThousands(row[column.field]) } })
        cols.push({ field: 'lossAmount', key: '25', title: '优惠金额', width: 60, align: 'center', fixed: 'right', renderBodyCell: ({ row, column, rowIndex }, h) => { return this.toThousands(row[column.field]) } })
      }
      // 编辑页面
      if (this.type == 'edit') {
        cols.push({
          field: '',
          key: '26',
          title: '状态',
          width: 50,
          align: 'center',
          fixed: 'right',
          renderBodyCell: ({ row, column, rowIndex }, h) => {
            return (
              <div>
                <a-switch checked-children="启" un-checked-children="禁" checked={row.enabledFlag == 1} on-change={(c, e) => this.enableRow(c, e, row)}/>
              </div>
            )
          },
          // 筛选项
          filter: {
            filterList: _this.ruleEnableList,
            isMultiple: true,
            // filter confirm
            filterConfirm: (filterList) => {
              const labels = filterList
                .filter((x) => x.selected)
                .map((x) => x.value)
              _this.searchData.enable = labels
              _this.filtrateList()
            },
            // filter reset
            filterReset: (filterList) => {
              filterList.map(x => { x.selected = true })
              _this.searchData.enable = []
              _this.filtrateList()
            }
          }
        })
        cols.push({
          field: '',
          key: '27',
          title: '操作',
          width: 100,
          align: 'center',
          fixed: 'right',
          renderBodyCell: ({ row, column, rowIndex }, h) => {
            // 导入产品按钮
            const importButton = []
            if (row && row.promotionRule && row.promotionRule.gateFlag === '1') {
              importButton.push({ key: 'GATE', name: '门槛产品' })
            }
            if (row && row.promotionRule && row.promotionRule.promotionRuleType != 'PROMO_PROD') {
              importButton.push({ key: 'REGULAR', name: '正价产品' })
            }
            if (row && row.promotionRule && (row.promotionRule.regularPromotionSameFlag === '0' || row.promotionRule.scopeFlag === '0' || (row.promotionRule.promotionRuleType == 'BUY_PROD_GIVE_MONEY' && row.promotionRule.scopeFlag === '1'))) {
              importButton.push({ key: 'GIFT', name: '促销产品' })
            }
            if (row && row.promotionRule && row.promotionRule.promotionRuleType == 'PROMO_PROD') {
              importButton.push({ key: 'DISCOUNT', name: '特价产品' })
            }
            if (row && row.promotionRule && row.promotionRule.borrowFlag == 1 && row.promotionRule.gateFlag === '1') {
              importButton.push({ key: 'BORROW_GATE', name: '累计门槛产品' })
            }
            if (row && row.promotionRule && row.promotionRule.borrowFlag == 1 && row.promotionRule.promotionRuleType != 'PROMO_PROD') {
              importButton.push({ key: 'BORROW_REGULAR', name: '累计正价产品' })
            }
            return (
              <div>
                {row.enabledFlag == 1 ? <a-dropdown>
                  <a-menu slot="overlay" on-click={(e) => this.handleImportClick(e, row, importButton)} id={'salesEdit-menu-import-' + row.id}>
                    {importButton.map(item => {
                      return (
                        <a-menu-item id={'salesEdit-menu-import-' + item.key + '-' + row.id} key={item.key}>{item.name}</a-menu-item>
                      )
                    })}
                  </a-menu>
                  <a-button
                    id={'salesEdit-menu-import-plaction-' + row.id}
                    type="link"
                    class="button-primary"
                    size="small"
                  >
                    导入∨
                  </a-button>
                </a-dropdown> : ''}
                {row.enabledFlag == 1 ? <a-button
                  type="link"
                  size="small"
                  class="button-primary"
                  on-click={() => this.addProduct(row, 1)}
                >
                 添加
                </a-button> : ''}
                {row.enabledFlag == 1 && row.promotionRule.borrowFlag == 1 ? <a-button
                  type="link"
                  size="small"
                  class="button-primary"
                  on-click={() => this.addProduct(row, 2)}
                >
                 累计
                </a-button> : <span style="width:40px;display:inline-block;"></span>}
              </div>
            )
          }
        })
      }
      return cols.filter((item, index) => {
        const i = index - 1
        return this.showCols.includes(i.toString()) || index == 0 || index > 12
      })
    }
  },
  methods: {
    // 筛选
    filtrateList () {
      const { ruleType, enable } = this.searchData
      const list = this.activeList.filter(item => ruleType.length === 0 || ruleType.includes(item.promotionRule.promotionRuleType)).filter(item => enable.length == 0 || enable.includes(item.enabledFlag))
      this.tableData = []
      this.getDataList(list)
    },
    getDataList (list) {
      this.hasInit = true
      for (let i = 0; i < list.length; i++) {
        const item = list[i]
        // 门槛统计
        const isYuan = item.gateRuleUnit == 'YUAN'
        const gateUnit = isYuan ? '元' : '个' // 单位
        const gateSelected = isYuan ? (item.gateAmount || item.gateAmount == 0 ? Number(item.gateAmount).toFixed(2) : undefined) : (item.gateQty || item.gateQty == 0 ? item.gateQty : undefined) // 已选
        const gateTotal = isYuan ? (item.gateBorrowAmount || item.gateBorrowAmount == 0 ? Number(item.gateBorrowAmount).toFixed(2) : undefined) : (item.gateBorrowQty || item.gateBorrowQty == 0 ? item.gateBorrowQty : undefined) // 累计
        const geteBalance = item.gateShortfallValue || item.gateShortfallValue == 0 ? item.gateShortfallValue : undefined // 差额
        const quotaUnit = item.quotaRuleUnit == 'YUAN' ? '元' : '个' // 配额单位
        const gateQuota = item.gateQuotaAmount || item.gateQuotaAmount == 0 ? (item.quotaRuleUnit == 'YUAN' ? Number(item.gateQuotaAmount).toFixed(2) : item.gateQuotaAmount) : undefined // 配额
        const unUseGateQuota = item.unUseAmount || item.unUseAmount == 0 ? (item.quotaRuleUnit == 'YUAN' ? Number(item.unUseAmount).toFixed(2) : item.unUseAmount) : undefined // 未用配额
        // 特价产品
        const isYuan2 = item.discountRuleUnit == 'YUAN'
        const discountRuleUnit = isYuan2 ? '元' : '个' // 单位
        const specialPriceSelected = isYuan2 ? (item.discountAmount || item.discountAmount == 0 ? Number(item.discountAmount).toFixed(2) : undefined) : (item.discountQty || item.discountQty == 0 ? item.discountQty : undefined) // 已选
        const totalPromoOrigAmount = isYuan2 && (item.totalPromoOrigAmount || item.totalPromoOrigAmount == 0) ? Number(item.totalPromoOrigAmount).toFixed(2) : undefined // 原价
        const discountRuleValue = item.discountRuleValue || item.discountRuleValue == 0 ? (isYuan2 ? Number(item.discountRuleValue).toFixed(2) : item.discountRuleValue) : undefined// 基础
        const discountRuleNextValue = item.discountShortfallValue || item.discountShortfallValue == 0 ? (isYuan2 ? Number(item.discountShortfallValue).toFixed(2) : item.discountShortfallValue) : undefined// 下阶差
        // 正价统计
        const isYuan1 = item.regularRuleUnit == 'YUAN'
        const regularUnit = isYuan1 ? '元' : '个' // 单位
        const regularSelected = isYuan1 ? (item.regularAmount || item.regularAmount == 0 ? Number(item.regularAmount).toFixed(2) : undefined) : (item.regularQty || item.regularQty == 0 ? item.regularQty : undefined)// 已选
        const regularTotal = isYuan1 ? (item.regularBorrowAmount || item.regularBorrowAmount == 0 ? Number(item.regularBorrowAmount).toFixed(2) : undefined) : (item.regularBorrowQty || item.regularBorrowQty == 0 ? item.regularBorrowQty : undefined) // 累计
        const regularBaseVal = item.regularRuleValue || item.regularRuleValue == 0 ? (isYuan1 ? Number(item.regularRuleValue).toFixed(2) : item.regularRuleValue) : undefined
        const regularNextVal = item.regularShortfallValue || item.regularShortfallValue == 0 ? (isYuan1 ? Number(item.regularShortfallValue).toFixed(2) : item.regularShortfallValue) : undefined
        // 促销品
        const promoUnit = '个'
        const promoSelected = item.giftQty || item.giftQty == 0 ? item.giftQty : undefined// 已选
        const promoBalance = item.giftShortfallQty || item.giftShortfallQty == 0 ? item.giftShortfallQty : undefined //  差额
        const promoLimit = item.giftGiveQty || item.giftGiveQty == 0 ? item.giftGiveQty : undefined // 额度
        // 采购额
        const purchaseUnit = '元'
        const purchaseLimit = item.totalPromoGiftsAmount || item.totalPromoGiftsAmount == 0 ? Number(item.totalPromoGiftsAmount).toFixed(2) : undefined // 额度
        const purchaseSelected = item.totalUsePromoGiftsAmount || item.totalUsePromoGiftsAmount == 0 ? Number(item.totalUsePromoGiftsAmount).toFixed(2) : undefined // 已选
        const purchaseSurplus = item.surplusAmount || item.surplusAmount == 0 ? Number(item.surplusAmount).toFixed(2) : undefined // 结余

        // 促销品
        this.tableData.push({
          ...item,
          ruleType: item.promotionRule.promotionRuleType,
          promotionRuleType: item.promotionRule.promotionRuleTypeAliasDictValue,
          promotionRuleDesc: item.promotionRule.description,
          promotionTitle: item.promotion.title,
          // 门槛
          gateUnit, // 单位
          quotaUnit, // 配额单位
          gateQuota, // 配额
          unUseGateQuota, // 未用配额
          gateSelected, // 已选
          gateTotal, // 累计
          geteBalance, // 差额
          // 特价产品
          discountRuleUnit,
          specialPriceSelected, // 已选
          totalPromoOrigAmount,
          discountRuleValue, // 基础
          discountRuleNextValue, // 下阶差
          // 正价
          regularUnit, // 单位
          regularSelected, // 已选
          regularTotal, // 累计
          regularBaseVal, // 基础差
          regularNextVal, // 下阶差
          // 促销品
          promoUnit, // 单位
          promoLimit, // 额度
          promoSelected, // 已选
          promoBalance, // 差额
          // 采购额
          purchaseUnit,
          purchaseLimit, // 额度
          purchaseSelected, // 已选
          purchaseSurplus // 结余
        })
      }
      // 获取禁用的活动规则
      this.disabledActiveIds()
    },
    // 禁用的活动规则
    disabledActiveIds () {
      this.checkboxOption.disableSelectedRowKeys = this.tableData.filter(item => item.enabledFlag == 0).map(item => item.id)
    },
    // 上下移动特价活动
    moveTjRow (item, rowIndex, type) {
      const temp = this.tableData[type == 1 ? rowIndex - 1 : rowIndex + 1]
      const tempSort = temp.sort
      temp.sort = item.sort
      item.sort = tempSort
      // 保存排序
      const tejia = this.tableData.filter(item => item.promotionRule && item.promotionRule.promotionRuleType == 'PROMO_PROD')
      const data = tejia.map(item => {
        return {
          id: item.id,
          sort: item.sort
        }
      })
      this.spinning = true
      salesPromoSaveSort({ salesBillSn: this.salesBillSn, salesPromoList: data }).then(res => {
        this.spinning = false
        if (res.status == 200) {
          this.$emit('refash', '', 'sort')
        } else {
          // 恢复排序
          item.sort = temp.sort
          temp.sort = tempSort
        }
      })
    },
    // 刷新当前规则
    refashRow (item, enable) {
      // 刷新产品列表
      this.$emit('refash', '', 'enable')
      const active = this.tableData.find(k => k.id == item.id)
      active.enabledFlag = enable
      // 获取禁用的活动规则
      this.disabledActiveIds()
    },
    // 查看累计产品 详情
    openTotalProduct (row, type) {
      this.openTotalProductModal = true
      this.$refs.totalProductModal.pageInit({ salesBillSn: row.salesBillSn, salesPromoSn: row.salesPromoSn, promotionFlag: type === 'gateUnit' ? 'GATE' : 'REGULAR' })
    },
    // 显示买赠产品弹窗
    showBuyGifts (rowVal) {
      rowVal.promotionRule.salesPromoSn = rowVal.salesPromoSn
      this.buyGiftsInfo = rowVal.promotionRule
      this.openNormalProductModal = true
      const _this = this
      this.$nextTick(() => {
        _this.$refs.normalProductModal.resetSearchForm()
      })
    },
    // 启用规则
    enabledActive (item) {
      const _this = this
      this.spinning = true
      salesEnablePromoPromo({
        salesBillSn: _this.salesBillSn,
        salesPromoSn: item.salesPromoSn,
        salesEnableType: _this.enableActiveOption
      }).then(res => {
        if (res.status == 200) {
          // 刷新
          _this.refashRow(item, 1)
          _this.enableActiveOption = null
          _this.$message.success('启用成功')
        }
        _this.spinning = false
      })
    },
    // 禁用规则
    disabledActive (item) {
      const _this = this
      _this.spinning = true
      salesDisablePromo({
        salesBillSn: _this.salesBillSn,
        salesPromoSn: item.salesPromoSn,
        promoRuleSn: item.promoRuleSn,
        salesDisableType: _this.disabledActiveOption
      }).then(res => {
        if (res.status == 200) {
          // 刷新
          _this.refashRow(item, 0)
          _this.disabledActiveOption = null
          _this.$message.success('禁用成功')
        }
        _this.spinning = false
      })
    },
    enableRow (c, e, item) {
      const _this = this
      // 启用
      if (item.enabledFlag == 0) {
        // 启用无正常产品直接启用
        // if (!this.hasNormal) {
        //   _this.enableActiveOption = 'ENABLE_ONLY'
        //   _this.enabledActive(item)
        //   return
        // }
        const isJiejia = item.promotionRule.stackFlag == 1 // 叠加产品
        this.$confirm({
          title: item.promotion.description + '-' + item.promotionRule.description + '，确定启用规则?',
          centered: true,
          class: 'confirm-center',
          content: <div>
            <div style="padding:10px;">
              <div style="padding:10px 0;">请选择</div>
              <aRadioGroup onChange={e => { _this.enableActiveOption = e.target.value }}>
                <aRadio style="display:block;height: '30px';lineHeight: '30px';padding:5px 0;" value="ENABLE_WITH_NORMAL">
                  正常产品适配
                </aRadio>
                {isJiejia ? <aRadio style="display:block;height: '30px';lineHeight: '30px';padding:5px 0;" value="ENABLE_WITH_STACK">
                  叠加规则产品适配
                </aRadio> : ''}
                {isJiejia ? <aRadio style="display:block;height: '30px';lineHeight: '30px';padding:5px 0;" value="ENABLE_WITH_STACK_NORMAL">
                  所有产品适配
                </aRadio> : ''}
                <aRadio style="display:block;height: '30px';lineHeight: '30px';padding:5px 0;" value="ENABLE_ONLY">
                  仅启用不适配
                </aRadio>
              </aRadioGroup>
            </div>
          </div>,
          onOk () {
            if (_this.enableActiveOption) {
              _this.enabledActive(item)
            } else {
              _this.$message.info('请选择启用方式!')
              return true
            }
          },
          onCancel () {
            _this.enableActiveOption = null
          }
        })
        return
      }
      // 禁用
      // 无产品直接禁用
      if (item.totalQty == 0) {
        _this.disabledActiveOption = 'DELETE'
        _this.disabledActive(item)
        return
      }
      this.$confirm({
        title: item.promotion.description + '-' + item.promotionRule.description + '，确定禁用规则?',
        centered: true,
        class: 'confirm-center',
        content: <div>
          <div style="padding:10px 0;text-align:center;">禁用规则后，将无法享受该活动规则优惠</div>
          <div style="padding:0 0 10px 0;text-align:center;">
            <aRadioGroup onChange={e => { _this.disabledActiveOption = e.target.value }}>
              <aRadio style="display:block;height: '30px';lineHeight: '30px';padding:5px 0;" value="DELETE">
                删除产品
              </aRadio>
              <aRadio style="display:block;height: '30px';lineHeight: '30px';padding:5px 0;" value="REMOVE">
                移出产品
              </aRadio>
            </aRadioGroup>
          </div>
        </div>,
        onOk () {
          if (_this.disabledActiveOption) {
            _this.disabledActive(item)
          } else {
            _this.$message.info('请选择禁用方式!')
            return true
          }
        },
        onCancel () {
          _this.disabledActiveOption = null
        }
      })
    },
    // 导入产品
    handleImportClick (e, row, importButton) {
      const title = importButton.find(item => item.key === e.key).name
      this.$refs.importGuideModal.pageInit({ promoProductClz: e.key, salesBillSn: this.salesBillSn, salesPromoSn: row.salesPromoSn }, row, title)
      this.openGuideModal = true
    },
    // 关闭导入弹框
    closeGuideModel () {
      this.openGuideModal = false
    },
    // 批量导入产品
    hanldeImportOk (salesBillDetailList, row, promoProductClz, isTotalFlag) {
      const fun = isTotalFlag ? salesDetailInsertBatchBorrow : salesBatchInsert
      const params = {
        salesBillSn: this.salesBillSn,
        salesBillDetailList: salesBillDetailList
      }
      // 活动导入
      if (row.salesPromoSn) {
        params.salesPromoSn = row.salesPromoSn
        params.promoRuleSn = row.promoRuleSn
        params.promoProductClz = promoProductClz
      }
      fun(params).then(res => {
        if (res.status == 200) {
          this.$message.success(isTotalFlag ? '累计产品导入成功' : '产品导入成功', 2.5)
          this.$emit('refash', '', 'import')
        }
      })
    },
    // 添加产品
    addProduct (row, type) {
      this.$emit('openCpModal', type, row)
    },
    // 查看活动详情
    showDesc (row) {
      if (row.promoRuleSn) {
        this.promoRuleSn = row.promoRuleSn
        this.promoRuleTitle = '详情 — ' + row.promotionTitle + '(' + row.promotionRuleDesc + ')'
        this.openDetailModal = true
      }
    },
    // 关闭详情弹窗
    closeDetailModal () {
      this.promoRuleSn = null
      this.promoRuleTitle = ''
      this.openDetailModal = false
    }
  }
}
</script>

<style lang="less">
  .table-header-cell-blue {
    background: #c9fbff !important;
  }
  .table-header-cell-red {
    background: #ffdccb !important;
  }
  .table-header-cell-green {
    background: #deffec !important;
  }
  .table-header-cell-zs {
    background: #fff2ff !important;
  }
  .table-header-cell-org {
    background: #fff3c2 !important;
  }
  .table-link-text{
    width:100%;
    color: #409EFF;
    display:flex;
    cursor:pointer;
    &:hover{
      text-decoration: underline;
    }
  }
  .table-link-btn{
     color: #409EFF;
     cursor:pointer;
     &:hover{
       text-decoration: underline;
     }
  }
  .table-word-color{
    color:#ed1c24;
  }
  .table-arrow-box{
    display: flex;
    span{
      width:16px;
      text-align:center;
      cursor:pointer;
      border-radius: 50px;
    }
    .up{
      color:#ed1c24;
      &:hover{
        color:#fff;
        background:#ed1c24;
      }
    }
    .down{
      color:#00aaff;
      &:hover{
        color:#fff;
        background:#00aaff;
      }
    }
  }
</style>
