<template>
  <div>
    <el-dialog title="创建优惠券"  :visible.sync="isShow" :modal-append-to-body="false" :close-on-click-modal="false" @close="resetForm()">
      <el-form ref="couponFormRef" :model="couponForm" label-width="100px" :rules="rules">
      <el-form-item label="优惠券类型" prop="couponType">
        <el-radio-group
          v-model="couponForm.couponType"
          class="ml-4"
          @change="changeCoupon"
        >
          <el-radio label="1" size="small">体验券</el-radio>
          <el-radio label="2" size="small">折扣券</el-radio>
          <el-radio label="3" size="small">满减券</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="优惠券名称" prop="name">
        <el-input
          v-model="couponForm.name"
          :placeholder="`请输入${
            couponForm.couponType == '1'
              ? '体验券'
              : couponForm.couponType == '2'
              ? '折扣券'
              : '满减券'
          }名称，最好5-20位`"
          style="width: 250px"
        />
      </el-form-item>
      <!-- 体验券 -->
      <el-form-item
        v-if="couponForm.couponType == '1'"
        label="体验时长"
        prop="discountNum"
      >
         <el-select
            v-model="couponForm.discountNumType"
            style="width: 115px"
          >
            <el-option label="天" :value="1"></el-option>
            <el-option label="月" :value="2"></el-option>
          </el-select>
        <el-input-number  :min="1" :step="1" :precision="0" :max="9999999"  v-model="couponForm.discountNum" style="width: 250px">
        </el-input-number>
      </el-form-item>
      <!-- 折扣券 -->
      <el-form-item
        v-if="couponForm.couponType == '2'"
        label="折扣"
        prop="discountPercent"
      >
        <div style="display: flex; width: 100%; margin-bottom: 20px">
          打
          <!-- <el-input
            v-model="couponForm.discountPercent"
            style="width: 200px"
            oninput="value=value.replace(/[^0-9.]/g,'')"
          /> -->
          <el-input-number style="width: 200px;margin:0 10px;" v-model="couponForm.discountPercent"  :precision="2" :step="0.01" :min="0.01" :max="9.99" ></el-input-number>
          折
        </div>
      </el-form-item>
      <el-form-item>
        <el-checkbox v-model="isCheckLimit" label="最多优惠" />
          <!-- <el-input v-model.number="couponForm.discountLimit" style="width: 200px" /> -->
          <el-input-number  :min="1" :step="1"  :max="9999999" :precision="0" style="width: 200px;margin:0 10px;"  v-model="couponForm.discountLimit" ></el-input-number>
          元
      </el-form-item>
      <el-form-item
        v-if="couponForm.couponType == '2'"
        label="使用门槛"
        prop="basicConsume"
      >
        <div style="display: flex; width: 100%">
          <span>订单金额大于</span>
          <!-- <el-input
            v-model.number="couponForm.basicConsume"
            style="width: 200px"
          /> -->
          <el-input-number style="width: 200px;margin:0 10px;" v-model="couponForm.basicConsume"  :precision="2" :step="1" :min="0.01" :max="9999999.00" ></el-input-number>
          元
        </div>
      </el-form-item>
      <!-- 满减券 -->
      <el-form-item
        v-if="couponForm.couponType == '3'"
        label="使用门槛"
        prop="basicConsume"
      >
        <div style="display: flex; width: 100%">
          <span>订单金额大于</span>
          <el-input-number style="width: 200px;margin:0 10px;" v-model="couponForm.basicConsume"  :precision="2" :step="1" :min="0.01" :max="9999999.00" ></el-input-number>元
        </div>
      </el-form-item>
      <el-form-item
        v-if="couponForm.couponType == '3'"
        label="优惠金额"
        prop="discount"
      >
      <el-input-number style="width: 200px;margin:0 10px;" v-model="couponForm.discount"  :precision="2" :step="1" :min="1" :max="9999999.00" ></el-input-number>元
      </el-form-item>
      <el-form-item label="用券时间" :prop="validTimeType == 1 ? 'validStart':'validDays' ">
        <el-radio-group v-model="validTimeType" class="ml-4">
          <div style="display: flex; margin-bottom: 10px; width: 100%;align-items: center;">
            <el-radio label="1" size="small">选择日期</el-radio>
            <el-date-picker
              v-model="validTime"
              type="daterange"
              :clearable="false"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              style="width: 400px; height: 40px;"
              :disabled="validTimeType == '2' || validTimeType == ''"
              :picker-options="pickerOptions"
            />
          </div>
          <div style="display: flex;align-items: center;">
            <el-radio label="2" size="small">领取后</el-radio>
            <el-input-number  :min="1" :step="1"  :max="9999999"  :precision="0" v-model="couponForm.validDays" width="100px" :disabled="validTimeType == '1' || validTimeType == ''"></el-input-number>
            <div style="width: 124px; font-size: 14px;margin-left: 10px; ">小时内有效</div>
          </div>
        </el-radio-group>
      </el-form-item>
      <!-- 满减券 -->
      <el-form-item v-if="couponForm.couponType == '2'" label="产品周期" prop="scopeOfPeriod">
        <el-checkbox-group v-model="couponForm.scopeOfPeriod">
          <el-checkbox label="0">长期</el-checkbox>
          <el-checkbox label="1">周</el-checkbox>
          <el-checkbox label="2">月</el-checkbox>
          <el-checkbox label="3">季</el-checkbox>
          <el-checkbox label="4">半年</el-checkbox>
          <el-checkbox label="5">年</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="发放数量" prop="sendTotalNumber">
        <el-input-number v-model="couponForm.sendTotalNumber" :step="1" :precision="0" :min="0" label="请输入发放数量"></el-input-number>
      </el-form-item>
      <el-form-item label="领取要求" prop="receiveRequirement">
        <el-radio-group v-model="couponForm.receiveRequirement">
          <el-radio :label="0">无要求</el-radio>
          <!-- <el-radio :label="1">关注主播</el-radio> -->
          <el-radio :label="2">评论互动</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm"> 取消 </el-button>
        <el-button type="primary" @click="submitForm" :disabled="creatIng">
          {{ isEdit ? "编辑" : "创建" }}
        </el-button>
      </div>
    </el-dialog>

    <el-dialog
      ref="proFormRef"
      :visible.sync="dialog.visible"
      :modal-append-to-body="false"
      :title="dialog.title"
      width="700px"
    >
      <div class="mb">
        已选择：{{ selectedProList.map((item) => item.productName).join(",") }}
      </div>
      <div class="mb" style="display: flex">
        <el-button
          link
          type="primary"
          size="small"
          @click="searchProList('refresh')"
          >刷新</el-button>
        <el-select
          v-model="selectProParams.productType"
          placeholder="请选择"
          clearable
          :fit-input-width="true"
          style="width: 150px"
        >
          <el-option label="基础产品" :value="1" />
          <el-option label="组合产品" :value="2" />
          <el-option label="全部类型" value="" />
        </el-select>
        &nbsp;
        <el-input
          v-model="selectProParams.search"
          clearable
          style="width: 300px"
          placeholder="请输入产品名称/id筛选"
        >
          <template #append>
            <el-button :icon="Search" @click="searchProList()" />
          </template>
        </el-input>
      </div>
      <el-table
        ref="productListRef"
        :data="productRes.productList"
        border
        style="width: 100%"
        class="mb"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          :selectable="handleSelectItem"
        />
        <el-table-column prop="productName" label="产品名称" />
        <el-table-column prop="productId" label="产品ID" />
        <el-table-column prop="productType" label="产品类型">
          <template #default="scope">
            {{ scope.row.productType == 1 ? "基础产品" : "组合产品" }}
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page="selectProParams.current"
        :page-size="selectProParams.size"
        :page-sizes="[100, 200, 300, 400]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="productRes.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="clearSelected">清空</el-button>
          <el-button type="primary" @click="confirmSelection">
            确定选择
          </el-button>
          <el-button @click="resetProForm">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  getCouponList,
  createCouponInfo,
  queryProList,
  editCouponInfo,
  createAndSave
} from '@/api/coupon'
import moment from 'moment'
import _ from 'lodash'

export default {
  mounted() {
    this.validTime = [moment().format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')]
    if (this.$route.query.couponId) {
      this.getEditCouponInfo()
    }
  },
  data() {
    return {
      couponList: [],
      total: 0,
      loading: false,
      dialog: { title: '', visible: false },
      checked1: false,
      checkList: [],
      validTimeType: '1', // 用券时间
      scopeProList: [], // 可用产品
      excludeScopeList: [], // 不可用产品
      isCheckLimit: false,
      isEdit: false, // 编辑页面
      couponForm: {
        id: '',
        basicConsume: 0, // 折扣券/满减券的使用门槛，0.01-9999999.00之间，保留2位小数
        categoryIds: '', // 产品类型ids,逗号分割
        couponType: '1', // 卡券类型
        discount: 1, // 满减券：优惠金额
        discountLimit:  null, // 折扣券： 最多优惠，1-9999999 （正整数）
        discountNum: 1, // 体验券：体验数？？？？？？
        discountNumType: 1, // 体验券： 体验时长1-天 2-月
        discountPercent:  0.01, // 折扣券： 折扣率，0.01-9.99（保留两位小数）
        excludeCategoryIds: ' ', // 不适应产品类型id,逗号分割
        excludeScopeDesc: '', // 不适应范围，产品名称,逗号分割
        excludeScopeOfProduct: '', // 不可用产品id。逗号分割
        name: '',
        scopeDesc: '', // 适用范围，产品名称，逗号
        scopeOfPeriod: [], // 折扣券，适用产品周期范围，逗号 ，多选
        scopeOfProduct: '', // 指定产品可用id，逗号
        scopeType: '0', // 适用类型 0-全场通用，1- 指定产品
        validDays:  null, // 领取日起N天有效 validTimeType ==2
        validEnd: '', // 优惠券有效期截止日 validTimeType ==1
        validStart: '', //	优惠券有效期起始日
        sendTotalNumber:'',// 发放总量
        receiveRequirement: null, // 领取要求
        liveId:Number(this.$route.query.id)
      },
      validTime: "",
      selectProParams: {
        productType:  null, // 1-基本  2-组合
        search: '', // 产品id/产品名
        current: 1,
        size: 10
      },
      productRes: {
        productList: [],
        total: 0
      },
      pickerOptions: {
        disabledDate(time) {
          // 禁用当前时间之前的所有时间
          return time.getTime() < Date.now()-24*60*60*1000;
        }
      },
      selectedProList: [],
      creatIng: false,
      rules: {
        name: [
          { required: true, message: '请输入优惠券名称！', trigger: 'blur' },
          { min: 5, max: 20, message: '长度在 5 到 20 个字符', trigger: 'blur' }
        ],
        discountNum: [
          { required: true, message: '请输入体验时长！', trigger: 'blur' },
        ],
        discountPercent: [
          { required: true, message: '请输入折扣率！', trigger: 'blur' },
        ],
        validDays: [
          { required: true, message: '请选择用券时间！', trigger: 'blur' },
        ],
        validStart: [
          { required: true, message: '请选择用券时间！', trigger: 'change' },
        ],
        sendTotalNumber: [
          { required: true, message: '请输入发放数量！', trigger: 'blur' },
        ],
        receiveRequirement: [
          { required: true, message: '请选择领取要求！', trigger: 'change' },
        ],
        scopeOfPeriod: [
          { required: true, message: '请选择产品周期！', trigger: 'blur' },
        ],
        basicConsume: [
          { required: true, message: '请输入使用门槛！', trigger: 'blur' },
        ],
        discount: [
          { required: true, message: '请输入优惠金额！', trigger: 'blur' },
        ],
        discountPercent: [
          { required: true, message: '请输入折扣！', trigger: 'blur' },
        ],
      },
      isShow:false
    }
  },
  methods: {
    openCoupon(){
      this.isShow = true
    },
    // 全场通用/指定产品可用
    changeScopeType(val) {
      // 选择全场通用,已选可用产品将清空
      if (val === '0' && this.scopeProList.length > 0) {
        this.$confirm('选择全场通用,已选的可用产品即将清空', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.scopeProList = []
          })
          .catch(() => {
            this.$message.info('已取消选择')
            this.$set(this.couponForm, 'scopeType', '1')
          })
      }
    },
    // 可用产品和不可用产品互斥
    handleSelectItem(row, index) {
      let res = false
      if (this.dialog.title === '选择可用产品') {
        const bool = this.excludeScopeList.some(
          (item) => row.productId === item.productId
        )
        res = !bool
      } else if (this.dialog.title === '选择不可用产品') {
        const bool = this.scopeProList.some(
          (item) => row.productId === item.productId
        )

        res = !bool
      }
      return res
    },
    // 选择产品
    deleteSelectedPro(id, type) {
      if (type === 'scope') {
        this.scopeProList = this.scopeProList.filter(
          (item) => item.productId !== id
        )
      } else {
        this.excludeScopeList = this.excludeScopeList.filter(
          (item) => item.productId !== id
        )
      }
    },
    // 清空产品
    clearScopeList(type) {
      if (type === 'scope') {
        this.scopeProList = []
      } else {
        this.excludeScopeList = []
      }
    },
    changeCoupon() {
      if (this.isEdit) {
        this.isEdit = false
      }
      if (this.$refs.couponFormRef) {
        this.$refs.couponFormRef.clearValidate();
      }
      this.$set(this, 'couponForm', {
        id: '',
        basicConsume: 0,
        categoryIds: '',
        couponType: this.couponForm.couponType,
        discount: 1,
        discountLimit: null,
        discountNum: 1,
        discountNumType: 1,
        discountPercent: 0.01,
        excludeCategoryIds: '',
        excludeScopeDesc: '',
        excludeScopeOfProduct: '',
        name: '',
        scopeDesc: '',
        scopeOfPeriod: [],
        scopeOfProduct: '',
        scopeType: '0',
        validDays: null,
        validEnd: '',
        validStart: '',
        sendTotalNumber:'',// 发放总量
        receiveRequirement: null, // 领取要求
        liveId:Number(this.$route.query.id)
      })
      this.scopeProList = []
      this.excludeScopeList = []
      this.validTime = [moment().format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')]
      this.validTimeType = '1'
    },
    /**
     * 选择产品弹窗
     */
    showProList(type) {
      //  getProList();
      queryProList(this.selectProParams).then((data) => {
        this.$set(this.productRes, 'productList', data.data.list)
        this.$set(this.productRes, 'total', data.data.total)
        this.$set(this.dialog, 'visible', true)
        this.$nextTick(() => {
          if (type === 'scope') {
            this.$set(this.dialog, 'title', '选择可用产品')
            this.productRes.productList.forEach((item) => {
              this.$refs['productListRef'].toggleRowSelection(
                item,
                this.scopeProList.some(
                  (scopeItem) => item.productId === scopeItem.productId
                )
              )
            })
          } else if (type === 'excludeScope') {
            this.$set(this.dialog, 'title', '选择不可用产品')
            this.productRes.productList.forEach((item) => {
              this.$refs['productListRef'].toggleRowSelection(
                item,
                this.excludeScopeList.some(
                  (scopeItem) => item.productId === scopeItem.productId
                )
              )
            })
          }
        })
      })
    },

    // 选择产品查询
    getProList() {
      queryProList(this.selectProParams).then((data) => {
        this.$set(this.productRes, 'productList', data.data.list)
        this.$set(this.productRes, 'total', data.data.total)
      })
    },
    handleSizeChange(val) {},
    handleCurrentChange(val) {},
    // 已选择
    handleSelectionChange(arr) {
      this.selectedProList = arr
    },
    // 查找、刷新
    searchProList(type) {
      this.$set(this.selectProParams, 'current', 1)
      if (type === 'refresh') {
        this.$set(this.selectProParams, 'search', '')
        this.$set(this.selectProParams, 'productType', null)
      }
      this.getProList()
    },
    // 清空
    clearSelected() {
      this.$refs['productListRef'].clearSelection()
    },
    formatDate(date) {
      return moment(date).format('YYYY-MM-DD HH:mm:ss')
    },
    // 确定选择
    confirmSelection() {
      if (this.dialog.title === '选择可用产品') {
        this.scopeProList = this.scopeProList.concat(this.selectedProList)
      } else {
        this.excludeScopeList = this.excludeScopeList.concat(
          this.selectedProList
        )
      }
      this.clearSelected()
      this.resetProForm()
    },
    resetProForm() {
      this.$set(this, 'selectProParams', {
        productType:  null, // 1-基本  2-组合
        search: '', // 产品id/产品名
        current: 1,
        size: 10
      })
      this.$set(this, 'dialog', {
        visible: false,
        title: ''
      })
    },
    submitForm() {
      this.$refs['couponFormRef'].validate((isValid) => {
        if (isValid) {
          this.creatIng = true;
          let propList = [
            'id',
            'couponType',
            'name',
            'excludeCategoryIds',
            'excludeScopeDesc',
            'excludeScopeOfProduct',
            'scopeDesc',
            'scopeOfProduct',
            'categoryIds',
            'scopeType'
          ]
          // 用券时间
          if (this.validTimeType === '1') {
            propList = propList.concat(['validEnd', 'validStart'])
            const isEndTime = new Date(this.validTime[1])
            isEndTime.setHours(23)
            isEndTime.setMinutes(59)
            isEndTime.setSeconds(59)
            this.$set(
              this.couponForm,
              'validStart',
              this.formatDate(this.validTime[0])
            )
            this.$set(this.couponForm, 'validEnd', this.formatDate(isEndTime))
          } else if (this.validTimeType === '2') {
            propList = propList.concat(['validDays'])
          }
          // 适用类型:指定产品可用
          if (this.couponForm.scopeType === '1') {
            // 可用产品
            this.$set(
              this.couponForm,
              'categoryIds',
              this.scopeProList.map((item) => item.categoryId).join(',')
            )
            this.$set(
              this.couponForm,
              'scopeDesc',
              this.scopeProList.map((item) => item.productName).join(',')
            )
            this.$set(
              this.couponForm,
              'scopeOfProduct',
              this.scopeProList.map((item) => item.productId).join(',')
            )
            // 不可用产品
            this.$set(this.couponForm, 'excludeCategoryIds', '')
            this.$set(this.couponForm, 'excludeScopeDesc', '')
            this.$set(this.couponForm, 'excludeScopeOfProduct', '')
          } else if (this.couponForm.scopeType === '0') {
            this.$set(this.couponForm, 'categoryIds', '')
            this.$set(this.couponForm, 'scopeDesc', '')
            this.$set(this.couponForm, 'scopeOfProduct', '')

            this.$set(
              this.couponForm,
              'excludeCategoryIds',
              this.excludeScopeList.map((item) => item.categoryId).join(',')
            )
            this.$set(
              this.couponForm,
              'excludeScopeDesc',
              this.excludeScopeList.map((item) => item.productName).join(',')
            )
            this.$set(
              this.couponForm,
              'excludeScopeOfProduct',
              this.excludeScopeList.map((item) => item.productId).join(',')
            )
          }
          let params = {}

          if (this.couponForm.couponType === '1') {
            params = _.pick(
              this.couponForm,
              propList.concat(['discountNumType', 'discountNum'])
            )
          } else if (this.couponForm.couponType === '2') {
            // 折扣券
            params = _.pick(
              this.couponForm,
              propList.concat([
                'basicConsume',
                'discountLimit',
                'discountPercent',
                'scopeOfPeriod'
              ])
            )

            params.scopeOfPeriod = params.scopeOfPeriod.join(',')
            params.discountPercent = Number(params.discountPercent).toFixed(2)
          } else if (this.couponForm.couponType === '3') {
            // 满减券
            params = _.pick(
              this.couponForm,
              propList.concat(['basicConsume', 'discount'])
            )
          }

          if (!this.couponForm.sendTotalNumber) {
            this.creatIng = false
            return this.$message.error("请输入发放数量！")
          }
          if (![0,1,2].includes(this.couponForm.receiveRequirement)) {
            this.creatIng = false
            return this.$message.error("请选择领取要求！")
          }
          params.sendTotalNumber = this.couponForm.sendTotalNumber
          params.receiveRequirement = this.couponForm.receiveRequirement
          params.liveId = this.couponForm.liveId
          // 参数校验
          if (!params.name) {
            this.creatIng = false
            return this.$message.error("请输入优惠券名称！")
          }
          if (this.validTimeType == '2' && !params.validDays) {
            this.creatIng = false
            return this.$message.error("请输入发起日！")
          }

          if (this.couponForm.couponType === '1') {
            if (Number(params.discountNum) < 1) {
              this.creatIng = false
              return this.$message.error("请设置体验时长！")
            }
          }

          if (this.couponForm.couponType === '2') {
            if (!params.discountPercent) {
              this.creatIng = false
              return this.$message.error("请设置折扣率！")
            }
            if (!params.discountLimit && this.isCheckLimit) {
              this.creatIng = false
              return this.$message.error("请设置最多优惠！")
            }
            // if (!params.scopeOfPeriod) {
            //   this.creatIng = false
            //   return this.$message.error("请设置产品周期！")
            // }
          }
          if (this.isEdit) {
            editCouponInfo(params).then((ret) => {
              if (ret.code === 0) {
                this.$message.success('编辑成功')
                this.creatIng = false
                // this.$router.go(-1)
              } else {
                this.creatIng = false
                this.$message.error('编辑失败！')
              }
            }).catch(() => {

            })
          } else {
            createAndSave(params).then((ret) => {
              if (ret.code === 0) {
                this.$message.success('创建成功！')
                this.creatIng = false
                this.$emit('child-event');
                this.resetForm()
                // this.$router.go(-1)
              } else {
                this.creatIng = false
                this.$message.error('创建失败！')
              }
            }).catch(() => {

            })
          }
        }
      })
    },
    resetForm() {
      if (this.$refs.couponFormRef) {
        this.$refs.couponFormRef.clearValidate();
      }
      this.$set(this, 'couponForm', {
        id: '',
        basicConsume: 0,
        categoryIds: '',
        couponType: '1',
        discount: 1,
        discountLimit:  null,
        discountNum: 1,
        discountNumType: 1,
        discountPercent:  0.01,
        excludeCategoryIds: '',
        excludeScopeDesc: '',
        excludeScopeOfProduct: '',
        name: '',
        scopeDesc: '',
        scopeOfPeriod: [],
        scopeOfProduct: '',
        scopeType: '0',
        validDays:  null,
        validEnd: '',
        validStart: '',
        sendTotalNumber:'',// 发放总量
        receiveRequirement: null, // 领取要求
        liveId:Number(this.$route.query.id)
      })

      this.scopeProList = []
      this.excludeScopeList = []
      this.validTime = [moment().format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')]
      this.validTimeType = '1'
      this.isShow = false
    },
    getEditCouponInfo() {
      this.isEdit = true
      getCouponList({
        couponId: this.$route.query.couponId
      }).then((data) => {
        this.$set(this, 'couponForm', data.data.list[0])
        // 处理时间
        if (data.data.list[0].validEnd && data.data.list[0].validStart) {
          const sDate = data.data.list[0].validStart
          const eDate = data.data.list[0].validEnd
          this.validTime = [moment(Number(sDate)).format('YYYY-MM-DD'), moment(Number(eDate)).format('YYYY-MM-DD')]
          this.validTimeType = '1'
        } else if (data.data.list[0].validDays) {
          this.validTimeType = '2'
        }
        // 回显可选和不可选产品
        this.scopeProList = this.formatScope(
          data.data.list[0].categoryIds,
          data.data.list[0].scopeDesc,
          data.data.list[0].scopeOfProduct
        )

        this.excludeScopeList = this.formatScope(
          data.data.list[0].excludeCategoryIds,
          data.data.list[0].excludeScopeDesc,
          data.data.list[0].excludeScopeOfProduct
        )
        // 折扣券：处理产品周期
        if (
          data.data.list[0].scopeOfPeriod &&
          data.data.list[0].couponType === '2'
        ) {
          this.$set(
            this.couponForm,
            'scopeOfPeriod',
            data.data.list[0].scopeOfPeriod.split(',')
          )
        }
        // 折扣券：最多优惠
        if (data.data.list[0].discountLimit) {
          this.isCheckLimit = true
        }
      })
    },

    formatScope(categoryIds, scopeDesc, scopeOfProduct) {
      if (!categoryIds || !scopeDesc || !scopeOfProduct) {
        return []
      }
      const categoryArr = categoryIds.split(',')
      const scopeDescArr = scopeDesc.split(',')
      const scopeOfProductArr = scopeOfProduct.split(',')
      const resArr = []
      for (let i = 0; i < categoryArr.length; i++) {
        resArr.push({
          categoryId: categoryArr[i],
          productName: scopeDescArr[i],
          productId: scopeOfProductArr[i]
        })
      }
      return resArr
    }
  },
  watch: {
    validTime: {
      async handler(newVal) {
        if (newVal.length) {
          this.couponForm.validStart = newVal[0]
        }
      }
    }
  },
}
</script>

<style scoped>
.mb {
  margin-bottom: 20px;
}
.el-radio-group {
  font-size: 14px;
}
::v-deep .el-range-editor.is-disabled {
  height: 33px;
}
</style>
