<template>
  <a-modal
    centered
    class="promotionList-modal"
    :footer="null"
    :maskClosable="false"
    title="买产品送产品-规则设置"
    v-model="isShow"
    @cancel="isShow=false"
    width="70%">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-form-model
        id="promotionList-form"
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :label-col="formItemLayout.labelCol"
        :wrapper-col="formItemLayout.wrapperCol" >
        <a-form-model-item label="规则简称" prop="description">
          <a-input
            size="small"
            id="promotionList-description"
            v-model.trim="form.description"
            allowClear
            placeholder="请输入规则简称（最多20个字符）"
            :maxLength="20"></a-input>
        </a-form-model-item>
        <a-form-model-item label="规则门槛" prop="gateFlag">
          <div class="fixWidthBox">
            <a-radio-group v-model="form.gateFlag" id="promotionList-gateFlag" button-style="solid" size="small" @change="changeGateFlag">
              <a-radio-button value="1" id="promotionList-gateFlag1">
                有
              </a-radio-button>
              <a-radio-button value="0" id="promotionList-gateFlag0">
                无
              </a-radio-button>
            </a-radio-group>
          </div>
          <div v-if="form.gateFlag && form.gateFlag === '1'">
            <v-select
              size="small"
              style="width:60%;"
              v-model="form.gateType"
              id="promotionList-gateType"
              code="PROMOTION_GATE_TYPE"
              placeholder="请选择门槛与配额设置要求"
              @change="changeGateTypeFlag"
              allowClear></v-select>
            <div v-if="form.gateType==='RATIO_AMOUNT'">
              购买门槛产品金额 <a-input-number
                v-model="form.gateValue"
                id="promotionList-gateValue"
                :min="0"
                :max="99999999"
                :precision="2"
                size="small"/> %作为配额
              <a-tooltip title="如：填写100%，则购买10000元门槛产品，可享受10000配额购买正价产品，根据门槛金额动态调整配额">
                <a-icon type="question-circle" theme="filled" :style="{ fontSize: '14px', color: 'gray' }"/>
              </a-tooltip>
            </div>
            <div v-if="form.gateType==='MIN_AMOUNT'">
              购买门槛产品满最低金额 <a-input-number
                id="promotionList-gateValue1"
                v-model="form.gateValue"
                :min="0"
                :max="99999999"
                :precision="2"
                size="small"/>元，不限制配额。
            </div>
            <div class="ruleDescList" v-if="form.gateType==='FIXED_AMOUNT'">
              购买满
              <a-input-number
                id="promotionList-gateValue2"
                v-model="form.gateValue"
                :min="0"
                :max="99999999"
                :precision="2"
                size="small"/>
              元门槛产品，可使用
              <a-input-number
                id="promotionList-quotaAmount"
                v-model="form.quotaAmount"
                :min="0"
                :max="99999999"
                :precision="2"
                size="small"/>
              元配额，采购规则中的正价商品（配额算销售额)
            </div>
          </div>
        </a-form-model-item>
        <a-form-model-item label="满赠规则" prop="regularSameFlag">
          <div class="fullGiftRuleBox">
            <div class="ruleDescList" v-for="(con,i) in fullGiftRuleList" :key="i">
              <span v-if="fullGiftRuleList.length>1">{{ i*1+1 }}、</span>
              <a-select
                id="promotionList-regularSameFlag"
                default-value="1"
                :disabled="i!=0"
                v-model="form.regularSameFlag"
                style="width: 100px"
                size="small"
                @change="handleFullGift"
                allowClear>
                <a-select-option value="1" id="promotionList-regularSameFlag1">
                  同款
                </a-select-option>
                <a-select-option value="0" id="promotionList-regularSameFlag0">
                  不同款
                </a-select-option>
              </a-select>
              产品购买满
              <a-input-number
                v-model="con.regularValue"
                id="promotionList-regularValue"
                :min="i!=0?fullGiftRuleList[i-1].regularValue:0"
                :step="1"
                :max="99999999"
                :precision="form.regularUnit==='YUAN'?2:0"
                size="small"/>
              <a-select
                id="promotionList-regularUnit"
                default-value="GE"
                :disabled="i!=0"
                v-model="form.regularUnit"
                style="width: 50px;margin-left:5px;"
                size="small"
                @change="handleChangeUnit">
                <a-select-option value="GE" id="promotionList-regularUnit-ge">
                  个
                </a-select-option>
                <a-select-option value="YUAN" id="promotionList-regularUnit-yuan">
                  元
                </a-select-option>
              </a-select>
              正价产品，送
              <a-input-number
                id="promotionList-promotionValue"
                v-model="con.promotionValue"
                :min="0"
                :step="1"
                :precision="0"
                :max="99999999"
                size="small"/>
              个促销产品
              <a-button
                type="link"
                id="promotionList-add"
                v-if="i==0&&fullGiftRuleList&&fullGiftRuleList.length<5"
                class="button-info"
                @click="addFullGiftRule">
                <a-icon type="plus"/>新增
              </a-button>
              <a-button type="link" :id="'promotionList-del-'+i" v-if="i!=0" class="button-error" @click="delFullGiftRule(con.id)">
                <a-icon type="delete" />删除
              </a-button>
            </div>
          </div>
          <div class="ruleDescList">
            <a-checkbox id="promotionList-restrictFlag" :checked="form.restrictFlag === '1'" size="small" @change="onChange">
              限制正价产品款数
            </a-checkbox>
            <a-input-number
              v-if="form.restrictFlag==='1'"
              v-model="form.restrictCategory"
              :min="0"
              :step="1"
              :max="99999999"
              :precision="0"
              size="small"
              id="promotionList-restrictCategory"
              style="margin-right:10px;"/>
            <a-checkbox id="promotionList-convertExpenseFlag" :checked="form.convertExpenseFlag==='1'" size="small" @change="onChangeConvert">
              可转费用报销单
            </a-checkbox>
          </div>
        </a-form-model-item>
        <a-form-model-item label="数量叠加" prop="accrualFlag">
          <a-radio-group id="promotionList-accrualFlag" v-model="form.accrualFlag" button-style="solid" size="small">
            <a-radio value="1" id="promotionList-accrualFlag1">
              是
            </a-radio>
            <a-radio value="0" id="promotionList-accrualFlag0">
              否
            </a-radio>
          </a-radio-group>
          <span style="color:gray;">（如：满10送2，数量叠加则：满20送4，满30送6）</span>
        </a-form-model-item>
        <a-form-model-item label="产品累计">
          <v-select
            style="width:40%;margin-right:10px;"
            size="small"
            v-model="form.borrowTimeLimtType"
            id="promotionList-borrowTimeLimtType"
            code="BORROW_TIME_LIMT_TYPE"
            placeholder="请选择累计时间"
            @change="borrowTimeLimtChange"
            allowClear></v-select>
          <a-checkbox v-if="form.borrowTimeLimtType" id="promotionList-borrowedShowFlag" :checked="form.borrowedShowFlag === '1'" size="small" @change="onBorrowedShowChange">
            加盟商显示“转促”标签
          </a-checkbox>
        </a-form-model-item>
        <!-- <a-form-model-item label="促销品与正品一致" prop="regularPromotionSameFlag">
          <div class="fixWidthBox">
            <a-radio-group
              id="promotionList-regularPromotionSameFlag"
              v-model="form.regularPromotionSameFlag"
              button-style="solid"
              size="small"
              :disabled="form.regularSameFlag==0"
              @change="handleSameFlag">
              <a-radio-button value="1" id="promotionList-regularPromotionSameFlag1">
                是
              </a-radio-button>
              <a-radio-button value="0" id="promotionList-regularPromotionSameFlag0">
                否
              </a-radio-button>
            </a-radio-group>
          </div>
        </a-form-model-item> -->
        <a-form-model-item label="规则叠加" prop="stackFlag">
          <v-select
            style="width:40%;"
            size="small"
            v-model="form.stackFlag"
            id="promotionList-stackFlag"
            code="FLAG"
            placeholder="请选择是否叠加规则"
            allowClear></v-select>
          <span>（销售单内的产品可同时参与多个叠加规则）</span>
        </a-form-model-item>
      </a-form-model>
      <a-card size="small" :bordered="false" class="pages-wrap">
        <div class="flex" style="margin-bottom:10px;">
          <a-radio-group id="promotionList-chooseVal" v-model="chooseVal" button-style="solid" @change="onChooseVal">
            <a-radio-button value="a" id="promotionList-chooseVal-a" v-show="form.gateFlag==='1'">
              门槛产品
            </a-radio-button>
            <a-radio-button value="b" id="promotionList-chooseVal-b">
              正价产品
            </a-radio-button>
            <a-radio-button :id="'promotionList-chooseVal-c'+item.id" :value="'c'+item.id" v-for="(item,i) in fullGiftRuleList" :key="i" v-show="form.regularPromotionSameFlag==='0'">
              {{ fullGiftRuleList.length>1?'促销产品（'+'阶梯'+(i*1+1)+'）':'促销产品' }}
            </a-radio-button>
          </a-radio-group>
          <div>
            <a-button
              size="small"
              type="link"
              class="button-info"
              @click="openGuideModal=true"
              id="promotionList-import">+导入产品</a-button>
            <a-button type="link" id="promotionList-preview" class="button-error" @click="handlePreview">预览</a-button>
          </div>
        </div>
        <div v-show="chooseVal=='a'"><tableType1 :unitTypeList="unitTypeDataList" ref="cillProduct"></tableType1></div>
        <div v-show="chooseVal=='b'"><tableType1 :unitTypeList="unitTypeDataList" ref="normalPriceProduct"></tableType1></div>
        <div v-show="chooseVal==('c'+item.id)" v-for="(item,i) in fullGiftRuleList" :key="item.id"><tableType1 :unitTypeList="unitTypeDataList" :ref="'offerProduct'+i"></tableType1></div>
      </a-card>
      <div class="btn-cont">
        <a-button id="promotionList-cancel" @click="isShow = false">取消</a-button>
        <a-button style="margin-left: 15px;" type="primary" id="promotionList-save" :loading="loadingSave" @click="handleSave">确定</a-button>
      </div>
    </a-spin>
    <!-- 导入产品 -->
    <importGuideModal goodFlag="1" :openModal="openGuideModal" @close="closeGuideModel" @ok="hanldeOk" />
    <!-- 预览弹窗 -->
    <productPreviewModal ref="previewModal" :openModal="openProductModal" :dataList="previewList" @close="closeProductModal"></productPreviewModal>
  </a-modal>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
// 组件
import { VSelect } from '@/components'
import tableType1 from './tableType1.vue'
import ImportGuideModal from './importGuideModal.vue'
import productPreviewModal from './productPreviewModal'
// 接口
import { getLookUpData } from '@/api/data'
import { promotionSave, getRuleDetail, getNewScopeSn } from '@/api/promotion'
export default {
  name: 'PromotionListBasicInfoModal',
  mixins: [commonMixin],
  components: { VSelect, tableType1, ImportGuideModal, productPreviewModal },
  props: {
    openModal: { //  弹框显示状态
      type: Boolean,
      default: false
    },
    promotionSn: {
      type: [Number, String],
      default: ''
    },
    itemSn: {
      type: [Number, String],
      default: ''
    }
  },
  data () {
    return {
      isShow: this.openModal, //  是否打开弹框
      spinning: false,
      // form表单  label布局
      formItemLayout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 17 }
      },
      fullGiftRuleList: [], // 促销产品数据
      form: {
        giveRuleType: 'RATIO', // 满赠规则类型: SUM_MONEY[金额叠加] / RATIO[按比例]   满产品送产品写死为: 按比例
        promotionRuleType: 'BUY_PROD_GIVE_PROD', // 买产品送产品
        description: '', // 简称
        stackFlag: undefined, // 叠加规则  1是 0否
        gateFlag: '0', // 门槛
        gateType: undefined, // 选择门槛类型
        gateValue: undefined, // 门槛值
        quotaAmount: undefined, // 门槛配额
        regularSameFlag: '1', // 满赠规则  同款不同款商品
        regularUnit: 'GE', // 单位
        restrictFlag: '0', // 限制正价产品款数
        convertExpenseFlag: '0', // 转费用报销标记
        restrictCategory: '', // 正价产品款数
        accrualFlag: '1', // 数量叠加
        regularPromotionSameFlag: '1', // 促销品与正品是否一致
        giftProductMap: {}, // 阶梯促销产品集合
        gateInfo: undefined, // 门槛产品规则描述
        ruleInfo: undefined, // 正价产品规则描述
        gateUnit: undefined, // 门槛产品单位
        quotaUnit: undefined, // 门槛配额单位
        borrowTimeLimtType: undefined, // 产品累计
        borrowedShowFlag: undefined// 显示转促标签 1是 0否
      },
      // 表单验证规则
      rules: {
        description: [ { required: true, message: '请输入规则简称', trigger: 'blur' } ],
        gateFlag: [ { required: true, message: '请选择规则门槛', trigger: 'change' } ],
        regularSameFlag: [{ required: true, message: '请选择满赠规则', trigger: 'change' }],
        accrualFlag: [{ required: true, message: '请选择数量是否叠加', trigger: 'change' }],
        regularPromotionSameFlag: [{ required: true, message: '请选择促销品与正品是否一致', trigger: 'change' }],
        stackFlag: [{ required: true, message: '请选择规则叠加', trigger: 'change' }]
      },
      chooseVal: 'a', // a门槛产品 b正价产品 c 或者c+id促销产品  促销阶梯产品
      openGuideModal: false, // 导入弹窗
      id: null,
      code: 'SCOPE_UNIT_TYPE', // 起订类型数据字典
      unitTypeDataList: [], // 起订量数据
      loadingSave: false, // 提交按钮加载状态
      openProductModal: false, // 预览弹窗
      previewList: []// 预览值
    }
  },
  methods: {
    // 单位切换时,满赠规则数据清空
    handleChangeUnit (e) {
      this.form.regularUnit = e
      this.fullGiftRuleList.forEach(item => {
        item.regularValue = undefined
      })
    },
    // 新增  满减规则  最多能添加五个
    async addFullGiftRule () {
      const result = await getNewScopeSn({})
      const obj = {
        id: result.data,
        scopeLevel: undefined,
        regularValue: undefined,
        promotionValue: undefined
      }
      this.fullGiftRuleList.push(obj)
    },
    // 删除满减规则
    delFullGiftRule (id) {
      const pos = this.fullGiftRuleList.findIndex(con => { return con.id == id })
      this.fullGiftRuleList.splice(pos, 1)
      if (this.chooseVal == 'c' + id) {
        this.chooseVal = this.form.gateFlag == '0' ? 'b' : 'a'
      }
    },
    // 满赠  同款    促销品与正品一致  默认是 可修改
    //     不同款                   默认否 不可修改
    handleFullGift (e) {
      if (e === '0') { // 不同款
        this.form.regularPromotionSameFlag = '0'
      } else {
        this.form.regularPromotionSameFlag = '1'
        if (this.chooseVal.indexOf('c') != -1) {
          this.chooseVal = this.form.gateFlag == '0' ? 'b' : 'a'
        }
      }
    },
    // 导入
    closeGuideModel () {
      this.openGuideModal = false
    },
    // 导入成功
    hanldeOk (arr) {
      if (this.chooseVal == 'a') {
        this.$refs['cillProduct'].importRow(arr)
      } else if (this.chooseVal == 'b') {
        this.$refs['normalPriceProduct'].importRow(arr)
      } else {
        const pos = this.fullGiftRuleList.findIndex(item => { return 'c' + item.id == this.chooseVal })
        if (pos != -1) {
          this.$refs['offerProduct' + pos][0].importRow(arr)
        }
      }
      this.openGuideModal = false
    },
    // 限制正价产品款数
    onChange (e) {
      this.form.restrictFlag = e.target.checked ? '1' : '0'
    },
    // 可转费用报销单
    onChangeConvert (e) {
      this.form.convertExpenseFlag = e.target.checked ? '1' : '0'
    },
    // 产品累计
    borrowTimeLimtChange (val) {
      this.form.borrowedShowFlag = '0'
      if (!val && this.itemSn) {
        this.form.borrowTimeLimtTypeDictValue = undefined
      }
    },
    // 加盟商显示“转促”标签
    onBorrowedShowChange (e) {
      this.form.borrowedShowFlag = e.target.checked ? '1' : '0'
    },
    // 门槛切换  tab 按钮默认显示问题
    changeGateFlag (e) {
      if (e.target.value == '0') {
        this.chooseVal = 'b'
        this.form.gateType = undefined
        this.form.gateValue = undefined
        this.form.quotaAmount = undefined
      } else {
        this.chooseVal = 'a'
      }
    },
    // 促销品与正品一致
    handleSameFlag (e) {
      if (e.target.value != '0') {
        this.chooseVal = this.form.gateFlag == '1' ? 'a' : 'b'
      }
    },
    // 门槛与配额设置要求
    changeGateTypeFlag (val) {
      this.form.gateType = val
      this.form.gateValue = undefined
      this.form.quotaAmount = undefined
    },
    //  保存
    handleSave () {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          // 验证门槛必填
          if (_this.form.gateFlag == '1') {
            if (!_this.form.gateType) {
              _this.$message.warning('请选择规则门槛设置类型！')
              return
            }
            if (!_this.form.gateValue || (_this.form.gateType === 'FIXED_AMOUNT' && !_this.form.quotaAmount)) {
              _this.$message.warning('规则门槛条件不能为空！')
              return
            }
            _this.form.gateUnit = _this.form.gateType === 'RATIO_AMOUNT' ? 'RATIO' : 'YUAN'
            _this.form.quotaUnit = _this.form.gateType === 'FIXED_AMOUNT' ? 'YUAN' : undefined
          }
          // 验证满赠必填
          const hasNullVal = _this.fullGiftRuleList.some(itemVal => !itemVal.regularValue || !itemVal.promotionValue)
          if (hasNullVal) {
            _this.$message.warning('满赠规则条件不能为空！')
            return
          }
          // 验证限制正价产品款数
          if (_this.form.restrictFlag === '1' && !_this.form.restrictCategory) {
            _this.$message.warning('请输入限制正价产品款数！')
            return
          }
          // 验证表格必填内容
          var form = JSON.parse(JSON.stringify(_this.form))
          if (form.gateFlag == '1') { // 门槛产品
            form.gateValue = form.gateType === 'RATIO_AMOUNT' ? form.gateValue / 100 : form.gateValue
            form.gateProductList = this.$refs.cillProduct.getResultVal()
            if (form.gateProductList.length == 0) {
              _this.$message.warning('请添加门槛产品！')
              return
            } else {
              if (_this.isJudge(form.gateProductList)) {
                return
              }
            }
          } else {
            form.gateProductList = []
            form.gateType = undefined
          }

          // 正价产品
          form.regularProductList = this.$refs.normalPriceProduct.getResultVal()
          // 判断表格必填
          if (form.regularProductList.length == 0) {
            _this.$message.warning('请添加正价产品！')
            return
          } else {
            if (_this.isJudge(form.regularProductList)) {
              return
            }
          }

          // 促销产品   阶梯促销产品
          if (form.regularPromotionSameFlag === '0') {
            const allGiftObj = {}
            _this.fullGiftRuleList.forEach((val, i) => {
              allGiftObj['GIFT' + (i * 1 + 1)] = _this.$refs['offerProduct' + i][0].getResultVal()
            })
            // 促销产品 阶梯促销产品不为空
            var lengthFlag = null
            // 组数据，添加数组标识
            let keyPos = 0
            for (const key in allGiftObj) {
              lengthFlag = !(allGiftObj[key] && allGiftObj[key].length)
              keyPos += 1
              allGiftObj[key].forEach((item, j) => {
                item.scopeLevel = keyPos
              })
            }
            if (lengthFlag) {
              _this.$message.warning('请添加促销产品！')
              return
            }
            // 产品中分类、品牌或产品是否为空
            const arrFlag = []
            for (const key in allGiftObj) {
              if (allGiftObj[key] && allGiftObj[key].length > 0) {
                arrFlag.push(_this.isJudge(allGiftObj[key]))
              }
            }
            if (arrFlag.some(val => val)) {
              return
            }
            // 赋值
            form.giftProductMap = allGiftObj
          } else {
            form.giftProductMap = {}
          }

          // 组传给后台所需数据
          _this.fullGiftRuleList.map((val, i) => {
            val.scopeLevel = i * 1 + 1
            val.regularSameFlag = form.regularSameFlag
            val.regularUnit = form.regularUnit
          })
          form.promotionSn = _this.promotionSn
          form.giveRuleList = _this.fullGiftRuleList
          if (form.gateFlag == '1') {
            if (form.gateType === 'RATIO_AMOUNT') {
              form.gateInfo = '购买门槛产品金额' + (form.gateValue * 100).toFixed(2) + '%作为配额'
            } else if (form.gateType === 'MIN_AMOUNT') {
              form.gateInfo = '购买门槛产品满最低金额' + form.gateValue.toFixed(2) + '元，不限制配额'
            } else {
              form.gateInfo = '购买满' + form.gateValue.toFixed(2) + '元门槛产品，可使用' + form.quotaAmount.toFixed(2) + '元配额，采购规则中的正价商品（配额算销售额）'
            }
          }
          var newInfo = `<div>${form.stackFlag == '1' ? '规则叠加；' : ''}${form.accrualFlag == '1' ? '数量叠加；' : ''}${form.convertExpenseFlag == '1' ? '可转费用报销单；' : ''}</div>`
          _this.fullGiftRuleList.forEach((item, i) => {
            newInfo += `<div>${_this.fullGiftRuleList.length > 1 ? (i * 1 + 1) + '、' : ''}${form.regularSameFlag == '1' ? '同款' : '不同款'}产品购买满${form.regularUnit == 'YUAN' ? item.regularValue.toFixed(2) : item.regularValue}${form.regularUnit == 'YUAN' ? '元' : '个'}正价产品，送${item.promotionValue}个促销产品</div>`
          })
          newInfo += `<div>${form.restrictFlag == '1' ? '限制正价产品' + form.restrictCategory + '款；' : ''}</div><div>${form.borrowTimeLimtType ? '产品累计：' + (form.borrowTimeLimtType == 'LENGTH_YEAR' ? '近一年' : '本年度') : ''}${form.borrowedShowFlag === '1' ? '，加盟商显示“转促”标签；' : ''}</div>`
          form.ruleInfo = newInfo
          _this.spinning = true
          _this.loadingSave = true
          promotionSave(form).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              setTimeout(() => {
                _this.isShow = false
                _this.$emit('ok')
                _this.spinning = false
                _this.loadingSave = false
              }, 1000)
            } else {
              _this.spinning = false
              _this.loadingSave = false
            }
          })
        } else {
          return false
        }
      })
    },
    // 判断品牌，分类，产品其中一个必填
    isJudge (list) {
      let flag = null
      let flag1 = null
      flag = list.some(con => !(con.productThisList && con.productThisList.length) && !(con.productTypeList && con.productTypeList.length) && !(con.productBrandList && con.productBrandList.length))
      flag1 = list.some(newCon => { return (!newCon.unitType || !newCon.unitQty) })
      if (flag) {
        this.$message.warning('请选择产品分类、品牌或产品！')
      } else if (flag1) {
        this.$message.warning('订单起订量设置不能为空！')
      }
      return flag || flag1
    },
    // 重置表格
    resetSearchForm () {
      this.form = {
        giveRuleType: 'RATIO', // 满赠规则类型: SUM_MONEY[金额叠加] / RATIO[按比例]   满产品送产品写死为: 按比例
        promotionRuleType: 'BUY_PROD_GIVE_PROD', // 买产品送产品
        description: '', // 简称
        stackFlag: undefined, // 叠加规则  1是 0否
        gateFlag: '0', // 门槛
        gateType: undefined,
        gateValue: undefined,
        quotaAmount: undefined,
        regularSameFlag: '1', // 满赠规则  同款不同款商品
        regularUnit: 'GE',
        restrictFlag: '0', // 限制正价产品款数
        convertExpenseFlag: '0', // 转费用报销标记
        restrictCategory: '',
        accrualFlag: '1', // 数量叠加
        regularPromotionSameFlag: '1',
        giftProductMap: {},
        gateProductList: undefined,
        regularProductList: undefined,
        gateInfo: undefined,
        ruleInfo: undefined,
        gateUnit: undefined,
        quotaUnit: undefined,
        borrowTimeLimtType: undefined, // 产品累计
        borrowedShowFlag: undefined// 显示转促标签 1是 0否
      }
      this.$nextTick(() => {
        this.$refs.ruleForm.resetFields()
        this.$refs.cillProduct.reSetTableData()
        this.$refs.normalPriceProduct.reSetTableData()
      })
      this.fullGiftRuleList.forEach((val, i) => {
        this.$refs['offerProduct' + i][0].reSetTableData()
      })
      this.fullGiftRuleList = []
      this.id = null
    },
    // 获取编辑详情
    getDetail () {
      const _this = this
      _this.spinning = true
      getRuleDetail({ sn: _this.itemSn }).then(res => {
        if (res.status == 200) {
          const resultObj = res.data
          _this.chooseVal = resultObj.gateFlag == '0' ? 'b' : 'a'
          if (resultObj.gateFlag == '1') {
            resultObj.gateValue = resultObj.gateType === 'RATIO_AMOUNT' ? resultObj.gateValue * 100 : resultObj.gateValue
          }
          if (resultObj.giveRuleList && resultObj.giveRuleList.length > 0) {
            _this.fullGiftRuleList = resultObj.giveRuleList
            if (resultObj.giftProductMap && Object.keys(resultObj.giftProductMap).length > 0) {
              _this.$nextTick(() => {
                resultObj.giveRuleList.forEach((item, i) => {
                  _this.$refs['offerProduct' + i][0].setTabVal(_this.newData(resultObj.giftProductMap['GIFT' + (i * 1 + 1)]))
                })
              })
            }
          }
          // 重新组成保存数据
          if (resultObj.gateProductList && resultObj.gateProductList.length > 0) {
            resultObj.gateProductList = _this.newData(resultObj.gateProductList)
            _this.$refs.cillProduct.setTabVal(resultObj.gateProductList)
          }
          if (resultObj.regularProductList && resultObj.regularProductList.length > 0) {
            resultObj.regularProductList = _this.newData(resultObj.regularProductList)
            _this.$refs.normalPriceProduct.setTabVal(resultObj.regularProductList)
          }
          const newDataObj = { ..._this.form, ...resultObj }
          delete newDataObj.giftProductList
          _this.form = newDataObj
        }
        _this.spinning = false
      })
    },
    // 重组所需回显数据
    newData (list) {
      list.forEach(con => {
        // 品牌
        if (con.productBrandList) {
          const brandList = []
          con.productBrandList.forEach(item => {
            item.brandName = item.productBrandName
            item.brandSn = item.productBrandSn
            const brandObj = {
              productBrandSn: item.productBrandSn
            }
            brandList.push(brandObj)
          })
          con.productBrandArr = con.productBrandList
          con.productBrandList = brandList
        }
        // 分类
        if (con.productTypeList) {
          const typeList = []
          con.productTypeList.forEach(item => {
            const typeObj = {}
            const num = 3
            for (var i = 0; i < num; i++) {
              if (item['productTypeName' + (i + 1)]) {
                typeObj['productTypeSn' + (i + 1)] = item['productTypeSn' + (i + 1)] ? item['productTypeSn' + (i + 1)] : ''
              }
            }
            if (item.productTypeName3) {
              item.title = item.productTypeName2 + '/' + item.productTypeName3
            } else if (!item.productTypeName3 && item.productTypeName2) {
              item.title = item.productTypeName2
            } else {
              item.title = item.productTypeName1
            }
            item.id = item.productTypeSn3 ? item.productTypeSn3 : item.productTypeSn2 ? item.productTypeSn2 : item.productTypeSn1
            typeList.push(typeObj)
          })
          con.productTypeArr = con.productTypeList
          con.productTypeList = typeList
        }
        // 产品
        if (con.productThisList) {
          const productList = []
          con.productThisList.forEach(item => {
            const productObj = {
              productCode: item.productCode,
              productSn: item.productSn
            }
            productList.push(productObj)
          })
          con.productThisList = productList
        }
      })
      return list
    },
    // 重组起订量等数据
    getUnitTypeList () {
      const _this = this
      getLookUpData({
        pageNo: 1,
        pageSize: 1000,
        lookupCode: _this.code
      }).then(res => {
        if (res.status == 200) {
          _this.unitTypeDataList = res.data.list
        }
      })
    },
    // 获取预览产品数据
    getPreviewList (dataList) {
      if (dataList && dataList.length > 0) {
        let newList = []
        dataList.forEach(con => {
          if (con.productThisList) {
            con.productThisList.forEach((item, i) => {
              item.unitTypeInfo = (con.unitType === 'SL' ? '按数量设置' : '按整箱设置') + con.unitQty
              item.productTypeInfo = con.promotionProductType
            })
            newList = [ ...newList, ...con.productThisList ]
          }
        })
        return newList
      } else {
        return []
      }
    },
    // 预览
    handlePreview () {
      const dataName = this.chooseVal === 'a' ? 'gate' : this.chooseVal === 'b' ? 'regular' : 'giftGroup'
      const titName = this.chooseVal === 'a' ? '门槛产品' : this.chooseVal === 'b' ? '正价产品' : '促销产品'
      if (dataName != 'giftGroup') {
        if (!this.itemSn) {
          if (this.chooseVal === 'a') {
            this.form.gateProductList = this.$refs.cillProduct.getResultVal()
          } else if (this.chooseVal === 'b') {
            this.form.regularProductList = this.$refs.normalPriceProduct.getResultVal()
          }
        }
        const newPreviewList = this.getPreviewList(this.form[dataName + 'ProductList'])
        if (newPreviewList && newPreviewList.length > 0) {
          this.previewList = newPreviewList
          const resuleObj = {
            tit: titName
          }
          this.$nextTick(() => {
            this.$refs.previewModal.pageInit(resuleObj)
          })
          this.openProductModal = true
        } else {
          this.$message.warning('暂时没有可预览的产品')
        }
      } else {
        // 阶梯数据处理
        const idInfo = this.chooseVal.split('c')[1]
        const stepIndex = this.fullGiftRuleList.findIndex(item => item.id === idInfo)
        if (stepIndex > -1 && !this.itemSn) {
          this.form.giftProductMap['GIFT' + (stepIndex * 1 + 1)] = this.$refs['offerProduct' + stepIndex][0].getResultVal()
        }
        if (this.form.giftProductMap && Object.keys(this.form.giftProductMap).length > 0) {
          const stepPreviewList = this.getPreviewList(this.form.giftProductMap['GIFT' + (stepIndex * 1 + 1)])
          if (stepPreviewList && stepPreviewList.length > 0) {
            this.previewList = stepPreviewList
            const resuleObj = {
              tit: '促销产品（阶梯' + (stepIndex * 1 + 1) + '）'
            }
            this.$nextTick(() => {
              this.$refs.previewModal.pageInit(resuleObj)
            })
            this.openProductModal = true
          } else {
            this.$message.warning('暂时没有可预览的产品')
          }
        }
      }
    },
    // 关闭选择产品弹窗
    closeProductModal () {
      this.previewList = []
      this.openProductModal = false
    },
    // 选择显示产品类型
    onChooseVal (e) {
      this.chooseVal = e.target.value
    }
  },
  watch: {
    //  父页面传过来的弹框状态
    openModal (newValue, oldValue) {
      this.isShow = newValue
    },
    //  重定义的弹框状态
    isShow (newValue, oldValue) {
      if (!newValue) {
        this.$emit('close')
        this.resetSearchForm()
      } else {
        // 获取起订类型数据字典
        this.getUnitTypeList()
        this.addFullGiftRule()
        if (this.itemSn) {
          this.getDetail()
        } else {
          this.chooseVal = this.form.gateFlag == '0' ? 'b' : 'a'
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>
  .promotionList-modal{
    /deep/.ant-modal-body {
      padding: 20px 30px;
      max-height: 745px !important;
      overflow-y: scroll !important;
    }
    .fixWidthBox .ant-radio-button-wrapper{
      width:80px;
      text-align: center;
    }
    .ant-form-item{
      margin-bottom:5px;
    }
    .buyerBox{
      border:1px solid #d9d9d9;margin-top:10px;border-radius:4px;padding:4px 10px;background:#f2f2f2;max-height:130px;overflow-y:scroll;
    }
    .btn-cont {
      text-align: center;
      margin: 35px 0 10px;
    }
    .flex{
      display:flex;
      align-items:center;
      justify-content:space-between;
    }
    .ant-radio-button-wrapper-disabled.ant-radio-button-wrapper-checked{
      background-color: #ed1c24 !important;
    }
  }
  /deep/.ve-table{
    border-radius:5px;
  }

</style>
