<template>
  <a-modal
    centered
    class="promotionList-basicInfo-modal"
    :footer="null"
    :maskClosable="false"
    title="特价产品-规则设置"
    v-model="isShow"
    @cancel="isShow=false"
    width="83%">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-form-model
        id="promotionList-basicInfo-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 id="promotionList-gateFlag" v-model="form.gateFlag" button-style="solid" size="small" @change="handleChange">
              <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
                id="promotionList-gateValue"
                v-model="form.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-gateValue"
                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
                v-model="form.gateValue"
                id="promotionList-gateValue"
                :max="99999999"
                :min="0"
                :precision="form.gateUnit=='YUAN'?2:0"
                size="small"/>
              <a-select
                default-value="GE"
                id="promotionList-gateUnit"
                v-model="form.gateUnit"
                style="width: 50px;margin-left:5px;"
                size="small"
                @change="handleUnit">
                <a-select-option value="GE" id="promotionList-gateUnit-ge">
                  个
                </a-select-option>
                <a-select-option value="YUAN" id="promotionList-gateUnit-yuan">
                  元
                </a-select-option>
              </a-select>
              门槛产品，可采购
              <a-input-number
                v-model="form.quotaAmount"
                id="promotionList-quotaAmount"
                :max="99999999"
                :min="0"
                :precision="0"
                size="small"/>
              个特价产品（配额算销售额)
            </div>
          </div>
        </a-form-model-item>
        <a-form-model-item label="产品累计" v-if="form.gateFlag==='1'">
          <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-borrowTimeLimtType" :checked="form.borrowedShowFlag === '1'" size="small" @change="onBorrowedShowChange">
            加盟商显示“转促”标签
          </a-checkbox>
        </a-form-model-item>
        <a-form-model-item label="特价规则" prop="discountType">
          <a-select
            id="promotionList-discountType"
            default-value="0"
            v-model="form.discountType"
            placeholder="请选择"
            style="width:60%;"
            size="small"
            @change="handleDiscountType"
            allowClear>
            <a-select-option value="0" id="promotionList-discountType0">
              手动输入特价
            </a-select-option>
            <a-select-option value="1" id="promotionList-discountType1">
              各级别价打折
            </a-select-option>
            <a-select-option value="2" id="promotionList-discountType2">
              各级别价直降
            </a-select-option>
          </a-select>
          <a-table
            v-show="form.discountType!=0"
            ref="setTable"
            :rowKey="(record) => record.id"
            :columns="setColumns"
            :dataSource="setTableData"
            :pagination="false"
            style="width:60%;"
          >
            <template slot="provinceDiscount" slot-scope="text, record">
              <a-input-number
                size="small"
                style="width:70px;"
                :id="'promotionList-provinceDiscount'+record.id"
                v-model="record.provinceValue"
                :min="0"
                :step="1"
                :precision="2"
                :max="99999999"
                placeholder="请输入"/> %
            </template>
            <template slot="cityDiscount" slot-scope="text, record">
              <a-input-number
                size="small"
                style="width:70px;"
                :id="'promotionList-cityValue'+record.id"
                v-model="record.cityValue"
                :min="record.provinceValue||0"
                :step="1"
                :precision="2"
                :max="99999999"
                placeholder="请输入"/> %
            </template>
            <template slot="specialDiscount" slot-scope="text, record">
              <a-input-number
                size="small"
                style="width:70px;"
                :id="'promotionList-specialValue'+record.id"
                v-model="record.specialValue"
                :min="record.cityValue ||0"
                :step="1"
                :precision="2"
                :max="99999999"
                placeholder="请输入"/> %
            </template>
            <template slot="provincePrice" slot-scope="text, record">
              <a-input-number
                size="small"
                :value="record.provinceValue"
                :id="'promotionList-provinceValue'+record.id"
                :min="0"
                :step="1"
                :precision="2"
                :max="99999999"
                placeholder="请输入"
                @blur="handleProvincePrice"/>
            </template>
            <template slot="cityPrice" slot-scope="text, record">
              <a-input-number
                size="small"
                :value="record.cityValue"
                :id="'promotionList-cityValue'+record.id"
                :min="0"
                :step="1"
                :precision="2"
                :max="99999999"
                placeholder="请输入"
                @blur="handleCityPrice"/>
            </template>
            <template slot="specialPrice" slot-scope="text, record">
              <a-input-number
                size="small"
                :value="record.specialValue"
                :id="'promotionList-specialValue'+record.id"
                :min="0"
                :step="1"
                :precision="2"
                :max="99999999"
                placeholder="请输入"
                @blur="handleSpecialPrice"/>
            </template>
            <template slot="orginAmount" slot-scope="text, record, index">
              <div style="display:flex;align-items: center;">
                <span>购买满</span>
                <a-input-number
                  size="small"
                  style="width:100px;margin:0 5px;"
                  :id="'promotionList-orginAmountValue'+record.id"
                  v-model="record.orginAmountValue"
                  :min="index>0?setTableData[index-1].orginAmountValue:0"
                  :precision="record.unitType=='YUAN'?2:0"
                  :max="99999999"
                  placeholder="请输入"/>
                <a-select size="small" style="width:80px;" v-model="record.unitType" @change="changeUnitType(index)" :disabled="index>0">
                  <a-select-option value="YUAN">元(原价)</a-select-option>
                  <a-select-option value="GE">个</a-select-option>
                </a-select>
              </div>
            </template>
            <template slot="actions" slot-scope="text, record, index">
              <a-button v-if="index==0" size="small" type="link" class="button-info" @click="addTableData"><a-icon type="plus"/>新增</a-button>
              <a-button v-else size="small" type="link" @click="delTableData(record,index)"><a-icon type="delete"/>删除</a-button>
            </template>
          </a-table>
        </a-form-model-item>
        <a-form-model-item label="规则叠加" prop="stackFlag" v-if="form.discountType!=0">
          <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">
            <a-radio-button value="a" v-show="form.gateFlag==='1'" id="promotionList-chooseVal-a">
              门槛产品
            </a-radio-button>
            <a-radio-button value="d" id="promotionList-chooseVal-d">
              特价产品
            </a-radio-button>
          </a-radio-group>
          <div>
            <a-button
              size="small"
              type="link"
              class="button-info"
              id="promotionList-import-btn"
              @click="openGuideModal=true"
            >+导入产品</a-button>
            <a-button
              v-show="chooseVal==='d'"
              style="margin-left:10px;"
              size="small"
              type="link"
              class="button-info"
              id="promotionList-add-btn"
              @click="addProducts">+新增产品</a-button>
            <a-button type="link" id="promotionList-preview-btn" 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=='d'"><tableType3 :setData="setTableData" :rulesType="form.discountType" :unitTypeList="unitTypeDataList" ref="specialProduct"></tableType3></div>
      </a-card>
      <div class="btn-cont">
        <a-button id="promotionList-cancel-btn" @click="isShow = false">取消</a-button>
        <a-button style="margin-left: 15px;" type="primary" id="promotionList-save-btn" @click="handleSave">确定</a-button>
      </div>
    </a-spin>
    <!-- 选择产品 -->
    <chooseProductsModal
      type="dealership"
      ref="productBox"
      :openModal="openProductsModal"
      :chooseData="chooseProducts"
      @close="openProductsModal=false"
      @ok="handleProductsAdd" />
    <!-- 导入产品 -->
    <importGuideModal :goodFlag="chooseVal=='a'?'1':'0'" :rulesType="form.discountType" :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 tableType3 from './tableType3.vue'
import chooseProductsModal from './chooseProductsModal.vue'
import ImportGuideModal from './importGuideModal.vue'
import productPreviewModal from './productPreviewModal'
// 接口
import { getLookUpData } from '@/api/data'
import { promotionSave, getRuleDetail } from '@/api/promotion'
export default {
  name: 'PromotionListBasicInfoModal',
  mixins: [commonMixin],
  components: { VSelect, tableType1, tableType3, chooseProductsModal, 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 }
      },
      // 提交参数
      form: {
        promotionRuleType: 'PROMO_PROD', // 特价产品
        description: '', // 规则简称
        stackFlag: undefined, // 规则叠加
        gateFlag: '0', // 门槛
        gateType: undefined, // 门槛产品类型
        gateValue: undefined, // 门槛产品配额值、满最低金额值、最低门槛金额和最低个数值
        gateUnit: 'GE', // 门槛产品单位
        quotaUnit: undefined, // 赠特价产品单位
        quotaAmount: undefined, // 赠特价产品金额
        discountType: '0', // 特价规则
        gateInfo: undefined, // 门槛产品规则描述
        ruleInfo: undefined, // 特价产品规则描述
        borrowTimeLimtType: undefined, // 产品累计
        borrowedShowFlag: undefined// 显示转促标签 1是 0否
      },
      // 表单验证规则
      rules: {
        description: [ { required: true, message: '请输入规则简称', trigger: 'blur' } ],
        gateFlag: [ { required: true, message: '请选择规则门槛', trigger: 'change' } ],
        discountType: [{ required: true, message: '请选择特价规则', trigger: 'change' }],
        stackFlag: [{ required: true, message: '请选择规则叠加', trigger: 'change' }]
      },
      setTableData: null, // 特价表格规则
      chooseVal: 'a', // 显示规则类型 a门槛产品  d特价产品
      openProductsModal: false, // 打开选择产品弹窗
      chooseProducts: [], // 已选产品集合
      openGuideModal: false, // 导入弹窗
      code: 'SCOPE_UNIT_TYPE', // 起订类型数据字典
      unitTypeDataList: [], // 起订量集合
      openProductModal: false, // 预览弹窗
      previewList: []// 预览值
    }
  },
  computed: {
    setColumns () {
      const _this = this
      var arr = []
      if (_this.form.discountType === '1') {
        arr = [
          { title: '特价产品合计', scopedSlots: { customRender: 'orginAmount' }, width: '42%', align: 'left' },
          { title: '省价折扣', scopedSlots: { customRender: 'provinceDiscount' }, width: '16%', align: 'left' },
          { title: '市价折扣', scopedSlots: { customRender: 'cityDiscount' }, width: '16%', align: 'left' },
          { title: '特约折扣', scopedSlots: { customRender: 'specialDiscount' }, width: '16%', align: 'left' },
          { title: '', scopedSlots: { customRender: 'actions' }, width: '10%', align: 'center' }
        ]
      } else if (_this.form.discountType === '2') {
        arr = [
          { title: '省价直降', scopedSlots: { customRender: 'provincePrice' }, width: '33%', align: 'left' },
          { title: '市价直降', scopedSlots: { customRender: 'cityPrice' }, width: '33%', align: 'left' },
          { title: '特约直降', scopedSlots: { customRender: 'specialPrice' }, width: '33%', align: 'left' }
        ]
      }
      return arr
    }
  },
  methods: {
    // 单位切换时,满赠规则数据清空
    handleUnit (val) {
      this.form.gateUnit = val
      this.form.gateValue = undefined
    },
    // 省价 change
    handleProvincePrice (e) {
      this.setTableData[0].provinceValue = Number(e.target.value)
    },
    // 市价 change
    handleCityPrice (e) {
      this.setTableData[0].cityValue = Number(e.target.value)
    },
    // 特约价 change
    handleSpecialPrice (e) {
      this.setTableData[0].specialValue = Number(e.target.value)
    },
    changeUnitType () {
      const ut = this.setTableData[0].unitType
      this.setTableData = this.setTableData.map(item => {
        item.unitType = ut
        if (ut == 'GE' && item.orginAmountValue) {
          item.orginAmountValue = Math.floor(item.orginAmountValue)
        }
        return item
      })
    },
    // 特价规则切换时清空数据
    handleDiscountType (val) {
      this.form.discountType = val
      this.$refs.specialProduct.reSetTableData()
      this.setTableData = [{
        orginAmountValue: undefined,
        unitType: 'YUAN',
        provinceValue: undefined,
        cityValue: undefined,
        specialValue: undefined
      }]
    },
    // 产品累计
    borrowTimeLimtChange (val) {
      this.form.borrowedShowFlag = '0'
      if (!val && this.itemSn) {
        this.form.borrowTimeLimtTypeDictValue = undefined
      }
    },
    // 加盟商显示“转促”标签
    onBorrowedShowChange (e) {
      this.form.borrowedShowFlag = e.target.checked ? '1' : '0'
    },
    // 导入
    closeGuideModel () {
      this.openGuideModal = false
    },
    // 门槛产品
    handleChange (e) {
      if (e.target.value == '1') {
        this.chooseVal = 'a'
      } else {
        this.chooseVal = 'd'
        this.form.gateType = undefined
        this.form.gateValue = undefined
        this.form.quotaAmount = undefined
      }
    },
    // 门槛与配额设置要求
    changeGateTypeFlag (val) {
      this.form.gateType = val
      this.form.gateValue = undefined
      this.form.quotaAmount = undefined
    },
    // 新增特价规则阶梯
    addTableData () {
      const len = this.setTableData.length
      if (len >= 5) {
        this.$message.warning('最多只能添加5条！')
        return
      }
      const ut = this.setTableData[0].unitType
      this.setTableData.push({
        orginAmountValue: undefined,
        unitType: ut,
        provinceValue: undefined,
        cityValue: undefined,
        specialValue: undefined
      })
    },
    // 删除特价规则阶梯
    delTableData (row, index) {
      this.setTableData.splice(index, 1)
    },
    //  保存
    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
            }
          }
          // 验证特价规则条件必填
          if (_this.form.discountType != '0' && _this.setTableData) {
            const hasTemp = _this.setTableData.some(item => {
              if (_this.form.discountType == '2') {
                return item.provinceValue == undefined || item.cityValue == undefined || item.specialValue == undefined
              }
              return item.orginAmountValue == undefined || item.provinceValue == undefined || item.cityValue == undefined || item.specialValue == undefined
            })
            if (hasTemp) {
              _this.$message.warning('特价规则条件不能为空！')
              return
            }
          }
          // 验证表格必填项
          const 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 (_this.isJudge(form.gateProductList, '门槛')) {
              return
            }
            form.gateUnit = form.gateType == 'RATIO_AMOUNT' ? 'RATIO' : form.gateType == 'MIN_AMOUNT' ? 'YUAN' : form.gateUnit
            form.quotaUnit = 'GE'
          } else {
            form.gateProductList = []
            form.gateValue = ''
            form.quotaAmount = ''
            form.gateType = undefined
            form.gateUnit = 'GE'
            form.quotaUnit = undefined
            form.borrowTimeLimtType = undefined
            form.borrowedShowFlag = undefined
          }
          // 特价产品
          form.specialProductList = _this.$refs.specialProduct.getResultVal()
          if (_this.isJudge(form.specialProductList, '特价')) {
            return
          }
          // 校验产品折扣手动输入必填项
          if (form.discountType === '0') {
            const isCountEmpty = _this.isNumEmpty(form.specialProductList)
            if (isCountEmpty.flag) {
              _this.$message.warning('折扣不能为空！')
              return
            }
            if (isCountEmpty.flag1) {
              _this.$message.warning('折扣金额不能为空！')
              return
            }
          } else if (form.discountType === '2') { // 直降
            form.provinceValue = _this.setTableData[0].provinceValue
            form.cityValue = _this.setTableData[0].cityValue
            form.specialValue = _this.setTableData[0].specialValue
          } else {
            // 折扣
            form.specialDiscountList = _this.setTableData.map((item, index) => {
              return {
                scopeLevel: index + 1,
                unitType: item.unitType,
                discountScopeValue: item.orginAmountValue,
                provinceDiscountRate: item.provinceValue,
                cityDiscountRate: item.cityValue,
                specialDiscountRate: item.specialValue
              }
            })
          }
          // 组后端所需数据
          form.promotionSn = _this.promotionSn
          // 门槛描述
          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.gateUnit == 'YUAN' ? (form.gateValue).toFixed(2) : form.gateValue) + (form.gateUnit == 'YUAN' ? '元' : '个') + '门槛产品，可采购' + form.quotaAmount + '个特价产品（配额算销售额）'
            }
          }
          // 规则描述
          let infoDetail = `<div>${form.stackFlag == '1' && form.discountType != '1' ? '规则叠加；' : ''}</div>`
          if (form.discountType == '0') {
            infoDetail += '手动输入特价'
          } else if (form.discountType == '1') {
            infoDetail += '各级别价打折；'
            form.specialDiscountList.forEach(item => {
              const utd = { 'YUAN': '元(原价)', 'GE': '个' }
              infoDetail += form.specialDiscountList.length > 1 ? '<div>' + item.scopeLevel + '、' : '<div>'
              infoDetail += '购买满 ' + (item.unitType == 'YUAN' ? Number(item.discountScopeValue).toFixed(2) : item.discountScopeValue) + ' ' + utd[item.unitType] + ' 特价产品，省级折扣' + item.provinceDiscountRate + '%，市级折扣' + item.cityDiscountRate + '%，特约折扣' + item.specialDiscountRate + '%；</div>'
            })
          } else {
            infoDetail += '各级别价直降；省级直降' + form.provinceValue.toFixed(2) + '，市级直降' + form.cityValue.toFixed(2) + '，特约直降' + form.specialValue.toFixed(2)
          }
          infoDetail += `<div>${form.borrowTimeLimtType ? '产品累计：' + (form.borrowTimeLimtType == 'LENGTH_YEAR' ? '近一年' : '本年度') : ''}${form.borrowedShowFlag === '1' ? '，加盟商显示“转促”标签；' : ''}</div>`
          form.ruleInfo = infoDetail
          _this.spinning = true
          promotionSave(form).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              setTimeout(() => {
                _this.isShow = false
                _this.$emit('ok')
                _this.spinning = false
              }, 1000)
            } else {
              _this.spinning = false
            }
          })
        } else {
          return false
        }
      })
    },
    // 判断是否为空
    isNumEmpty (dataList) {
      const arr = []
      const arr1 = []
      dataList.forEach(item => {
        if (item.dataSourceOrigin === '0') { // 判断分类品牌
          if (!item.provinceDiscountRate || !item.cityDiscountRate || !item.specialDiscountRate) {
            arr.push(item.productScopeSn)
          }
        } else {
          if (!item.cityDiscountPrice || !item.provinceDiscountPrice || !item.specialDiscountPrice) {
            arr1.push(item.productScopeSn)
          }
        }
      })
      return { flag: arr.length > 0, flag1: arr1.length > 0 }
    },
    // 判断品牌，分类，产品其中一个必填
    isJudge (list, typeName) {
      let flag, flag1, flag2
      flag = !(list && list.length)
      flag1 = list.some(con => !(con.productThisList && con.productThisList.length) && !(con.productTypeList && con.productTypeList.length) && !(con.productBrandList && con.productBrandList.length))
      flag2 = list.some(newCon => { return (!newCon.unitType || !newCon.unitQty) })
      if (flag) {
        const tipInfo = '请添加' + typeName + '产品！'
        this.$message.warning(tipInfo)
      } else if (flag1) {
        this.$message.warning('请选择产品分类、品牌或产品！')
      } else if (flag2) {
        this.$message.warning('订单起订量设置不能为空！')
      }
      return flag || flag1 || flag2
    },
    // 重置表格
    resetSearchForm () {
      this.form = {
        promotionRuleType: 'PROMO_PROD', // 特价产品
        description: '', // 规则简称
        stackFlag: undefined, // 规则叠加
        gateFlag: '0', // 门槛
        gateType: undefined,
        gateValue: undefined,
        gateUnit: 'GE',
        quotaAmount: undefined,
        discountType: '0', // 特价规则
        gateProductList: undefined,
        specialProductList: undefined,
        quotaUnit: undefined,
        borrowTimeLimtType: undefined, // 产品累计
        borrowedShowFlag: undefined// 显示转促标签 1是 0否
      }
      this.$nextTick(() => {
        this.$refs.ruleForm.resetFields()
        this.$refs.cillProduct.reSetTableData()
        this.$refs.specialProduct.reSetTableData()
      })
      if (this.form.discountType != '0') {
        this.$refs[0].setTable.clearTable()
      }
      this.setTableData = []
    },
    // 获取编辑详情
    getDetail () {
      const _this = this
      _this.spinning = true
      getRuleDetail({ sn: this.itemSn }).then(res => {
        if (res.status == 200) {
          this.chooseVal = res.data.gateFlag == '0' ? 'd' : 'a'
          const resultObj = res.data
          if (resultObj.gateFlag === '1') {
            resultObj.gateValue = resultObj.gateType === 'RATIO_AMOUNT' ? resultObj.gateValue * 100 : resultObj.gateValue
          }
          if (resultObj.discountType != '0') {
            if (resultObj.discountType == '1' && resultObj.specialDiscountList) {
              _this.setTableData = resultObj.specialDiscountList.map(item => {
                return {
                  orginAmountValue: item.discountScopeValue,
                  unitType: item.unitType,
                  provinceValue: item.provinceDiscountRate,
                  cityValue: item.cityDiscountRate,
                  specialValue: item.specialDiscountRate,
                  scopeLevel: item.scopeLevel
                }
              })
            } else {
              _this.setTableData = [{
                provinceValue: resultObj.provinceValue,
                cityValue: resultObj.cityValue,
                specialValue: resultObj.specialValue
              }]
            }
          }
          // 重新组成保存数据
          if (resultObj.gateProductList && resultObj.gateProductList.length > 0) {
            resultObj.gateProductList = _this.newData(resultObj.gateProductList)
            this.$refs.cillProduct.setTabVal(resultObj.gateProductList)
          }
          if (resultObj.specialProductList && resultObj.specialProductList.length > 0) {
            resultObj.specialProductList = _this.newData(resultObj.specialProductList)
            this.$refs.specialProduct.setSourceData(resultObj.specialProductList)
          }
          this.form = { ...this.form, ...resultObj }
        }
        _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 = {}
            item.title = ''
            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
    },
    // 导入
    hanldeOk (arr) {
      // 门槛产品导入
      const resultArr = []
      if (this.chooseVal == 'a') {
        const name = this.chooseVal == 'a' ? 'cill' : this.chooseVal == 'b' ? 'normalPrice' : 'offer'
        this.$refs[name + 'Product'].importRow(arr)
      } else {
        // 特价产品导入
        const dataList = this.setShowData('This')
        arr.forEach(item => {
          item = { ...item, ...item.product }
          item.code = item.productCode
          if (this.form.discountType == '0') {
            if (item.provincePrice) {
              item.provinceDiscountRate = Math.floor(((item.provinceDiscountPriceText / item.provincePrice) * 100).toFixed(2))
            }
            if (item.cityPrice) {
              item.cityDiscountRate = Math.floor(((item.cityDiscountPriceText / item.cityPrice) * 100).toFixed(2))
            }
            if (item.specialPrice) {
              item.specialDiscountRate = Math.floor(((item.specialDiscountPriceText / item.specialPrice) * 100).toFixed(2))
            }
          } else if (this.form.discountType == '1') {
            if (item.provincePrice) {
              item.provinceDiscountRate = this.form.provinceValue
              item.provinceDiscountPriceText = (item.provincePrice * this.form.provinceValue / 100).toFixed(2)
            }
            if (item.cityPrice) {
              item.cityDiscountRate = this.form.cityValue
              item.cityDiscountPriceText = (item.cityPrice * this.form.cityValue / 100).toFixed(2)
            }
            if (item.specialPrice) {
              item.specialDiscountRate = this.form.specialValue
              item.specialDiscountPriceText = (item.specialPrice * this.form.specialValue / 100).toFixed(2)
            }
          } else {
            if (item.provincePrice) {
              item.provinceSubtract = item.provincePrice - this.form.provinceValue
            }
            if (item.cityPrice) {
              item.citySubtract = item.cityPrice - this.form.cityValue
            }
            if (item.specialPrice) {
              item.specialSubtract = item.specialPrice - this.form.specialValue
            }
          }
          const flag = dataList.includes(item.productSn)
          if (!flag) {
            resultArr.push(item)
          }
        })
        if (resultArr.length > 0) {
          this.handleProductsOk(resultArr)
        } else {
          this.$message.warning('请勿添加重复数据！')
        }
      }
    },
    // 打开新增产品弹窗（禁用已选）
    addProducts () {
      this.chooseProducts = []
      this.openProductsModal = true
      const dataList = this.setShowData('This')
      this.$refs.productBox.handleDisabled(dataList)
    },
    // 获取回显禁用数据
    setShowData (name) {
      const _this = this
      const snArr = []
      const valList = _this.$refs.specialProduct.getResultVal()
      valList.forEach(item => {
        if (item['product' + name + 'List'] && item['product' + name + 'List'].length > 0) {
          item['product' + name + 'List'].forEach(con => {
            const newName = name === 'This' ? '' : name
            snArr.push(con['product' + newName + 'Sn'])
          })
        }
      })
      return snArr
    },
    // 添加产品 重组回显数据
    handleProductsAdd (con) {
      const newArr = []
      const newConArr = []
      con.forEach(newCon => {
        if (!newCon.provincePrice || !newCon.cityPrice || !newCon.specialPrice) {
          newArr.push(newCon.code)
        }
      })
      con.forEach((list, pos) => {
        if (list.provincePrice && list.cityPrice && list.specialPrice) {
          newConArr.push(list)
        }
      })
      const _this = this
      if (newArr && newArr.length > 0) {
        _this.$info({
          title: '提示',
          content: newArr.toString() + '（产品编码），没有定价，不可添加',
          closable: true,
          centered: true,
          onOk () {
            _this.handleProductsOk(newConArr)
          }
        })
      } else {
        _this.handleProductsOk(newConArr)
      }
    },
    // 生成随机数
    generateUniqueRandomNumber () {
      const timestamp = new Date().getTime()
      const randomNumber = Math.floor(Math.random() * 1e5).toString().padStart(5, '0')
      const uniqueRandomNumber = timestamp + randomNumber
      return uniqueRandomNumber
    },
    // +新增产品
    handleProductsOk (con) {
      const _this = this
      _this.spinning = true
      setTimeout(() => {
        _this.spinning = false
      }, 1500)
      con.forEach(async (item) => {
        const chooseProductsList = []
        const getSn = this.generateUniqueRandomNumber()
        if (getSn) {
          const newData = {
            productScopeSn: getSn,
            dataSourceOrigin: '1',
            productTypeArr: [],
            productTypeList: [],
            productBrandArr: [{ productBrandSn: item.productBrandSn, brandName: item.productBrandName }],
            productBrandList: [{ productBrandSn: item.productBrandSn }],
            productThisList: [{
              productSn: item.productSn,
              productCode: item.code
            }],
            provincePrice: item.provincePrice,
            cityPrice: item.cityPrice,
            specialPrice: item.specialPrice,
            provinceDiscountPrice: item.provinceDiscountPriceText,
            cityDiscountPrice: item.cityDiscountPriceText,
            specialDiscountPrice: item.specialDiscountPriceText,
            unitType: item.unitType || 'SL',
            unitQty: item.unitQty || '1',
            provinceDiscountRate: item.provinceDiscountRate ? item.provinceDiscountRate : undefined,
            cityDiscountRate: item.cityDiscountRate ? item.cityDiscountRate : undefined,
            specialDiscountRate: item.specialDiscountRate ? item.specialDiscountRate : undefined
          }
          const obj = {}
          if (item.productTypeSn1) {
            obj.productTypeSn1 = item.productTypeSn1
          }
          if (item.productTypeSn2) {
            obj.productTypeSn2 = item.productTypeSn2
          }
          if (item.productTypeSn3) {
            obj.productTypeSn3 = item.productTypeSn3
          }
          const newObj = { ...obj, ...{} }
          if (Object.keys(obj).length == 1) {
            newObj.title = item.productTypeName1
            newObj.id = item.productTypeSn1
          } else if (Object.keys(obj).length == 2) {
            newObj.title = item.productTypeName2
            newObj.id = item.productTypeSn2
          } else {
            newObj.title = item.productTypeName2 + '/' + item.productTypeName3
            newObj.id = item.productTypeSn3
          }
          newData.productTypeList[0] = obj
          newData.productTypeArr[0] = newObj
          chooseProductsList.push(newData)
        }
        _this.$refs.specialProduct.setSourceData(chooseProductsList)
      })
    },
    // 获取起订类型数据字典
    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' : 'special'
      const titName = this.chooseVal === 'a' ? '门槛产品' : '特价产品'
      if (!this.itemSn) {
        if (this.chooseVal === 'a') {
          this.form.gateProductList = this.$refs.cillProduct.getResultVal()
        } else {
          this.form.specialProductList = this.$refs.specialProduct.getResultVal()
        }
      }
      this.$nextTick(() => {
        const newPreviewList = this.getPreviewList(this.form[dataName + 'ProductList'])
        if (newPreviewList.length === 0) {
          this.$message.warning('暂时没有可预览的产品')
          return
        }
        this.previewList = newPreviewList
        const resuleObj = {
          tit: titName
        }
        this.$refs.previewModal.pageInit(resuleObj)
        this.openProductModal = true
      })
    },
    // 关闭产品弹窗
    closeProductModal () {
      this.previewList = []
      this.openProductModal = false
    }
  },
  watch: {
    //  父页面传过来的弹框状态
    openModal (newValue, oldValue) {
      this.isShow = newValue
    },
    //  重定义的弹框状态
    isShow (newValue, oldValue) {
      if (!newValue) {
        this.$emit('close')
        this.resetSearchForm()
      } else {
        // 获取起订类型数据字典
        this.getUnitTypeList()
        if (this.itemSn) {
          this.getDetail()
        } else {
          this.chooseVal = this.form.gateFlag == '0' ? 'd' : 'a'
        }
      }
    }
  }
}
</script>
<style lang="less" scoped>
  // .ant-modal-confirm-body{
  //   max-height: 500px;
  //   overflow-y:scroll;
  // }
  .promotionList-basicInfo-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: 20px 0 10px;
    }
    .flex{
      display:flex;
      align-items:center;
      justify-content:space-between;
    }
  }
  /deep/.ve-table{
    border-radius:5px;
  }

</style>
