<template>
  <el-dialog 
  :title="title" 
  :visible.sync="open" 
  width="70%" 
  append-to-body 
  :close-on-click-modal="false"
    @close="cancel">
    <div class="form-dialog-box" v-loading="loading" :element-loading-text="loadingText"
      element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0)">
      <div v-loading="loading" :element-loading-text="''" element-loading-spinner="''"
        element-loading-background="rgba(0, 0, 0, 0.8)">
        <el-form :model="form" ref="form" :rules="rules" label-width="150px">
          <div class="form-title"><span>基本信息</span></div>
          <el-form-item label="实体卡名称：" prop="cardName">
            <el-input style="width: 100%;" v-model="form.cardName" placeholder="请输入实体卡名称" maxlength="50"
              show-word-limit />
          </el-form-item>
          <el-form-item label="实体卡价格：" prop="price">
            <el-input-number v-model="form.price" placeholder="请输入实体卡价格" controls-position="right">
            </el-input-number>
            <span>元</span>
          </el-form-item>
          <div class="form-title"><span>使用规则</span></div>
          <el-form-item label="使用期限：" prop="useType">
            <el-radio-group v-model="form.useType" @input="radioInputs">
              <div style="display: flex;flex-direction: column;padding-top: 10px;">
                <div>
                  <el-radio :label="1">永久生效</el-radio>
                </div>
                <div style="display: flex;align-items: center;margin-top: 25px;">
                  <el-radio style="display: flex;align-items: center;" :label="2">
                    <div style="display: flex;align-items: center;">
                      <el-form-item label="" label-width="0" :prop="'useDay'">
                        <span>指定</span>
                        <el-input-number :disabled="form.useType != 2" v-model="form.useDay"
                          placeholder="请输入天数" controls-position="right">
                        </el-input-number>
                        <span>天数有效</span>
                      </el-form-item>
                    </div>
                  </el-radio>
                </div>
                <div style="display: flex;align-items: center;margin-top: 25px;">
                  <el-radio style="display: flex;align-items: center;" :label="3">
                    <div style="display: flex;align-items: center;">
                      <el-form-item label="" label-width="0" :prop="'useEndDay'">
                        <span>指定</span>
                        <el-date-picker :disabled="form.useType != 3" v-model="form.useEndDay"
                        type="date" placeholder="请选择日期" value-format="yyyy-MM-dd"
                          >
                        </el-date-picker>
                        <span>结束日期</span>
                      </el-form-item>
                    </div>
                  </el-radio>

                </div>
              </div>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="生效日期：" prop="effectiveDateType">
            <el-radio-group v-model="form.effectiveDateType">
              <el-radio :label="1">制卡之日生效</el-radio>
              <el-radio :label="2">激活之日生效</el-radio>
            </el-radio-group>
          </el-form-item>
          <div class="form-title"><span>激活规则</span></div>
          <el-form-item label="激活后完善信息：" prop="activationRule">
            <el-checkbox-group v-model="form.activationRule">
              <el-checkbox 
              v-for="dict in dict.type.activation_rule"
              :key="dict.value"
              :label="dict.value">{{dict.label}}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <div class="form-title"><span>权益规则</span></div>
          <el-form-item label="支持储值" prop="isStorageValue">
            <el-radio-group v-model="form.isStorageValue">
              <el-radio :label="0">不可储值</el-radio>
              <el-radio :label="1">可储值</el-radio>
            </el-radio-group>
          </el-form-item>
          <div v-if="form.isStorageValue==1">
            <div class="form-title"><span>实体卡储值规则配置</span></div>
            <el-form-item label="储值金额范围" label-width="120px">
              <div style="display: flex;align-items: center;">
                <el-form-item label="" label-width="0px" prop="minAmount">
                <el-input-number v-model="form.minAmount" placeholder="请输入最小储值金额"
                  controls-position="right">
                  </el-input-number>
                </el-form-item>
                <span>--</span>
                <el-form-item label="" label-width="0px" prop="maxAmount">
                  <el-input-number v-model="form.maxAmount" placeholder="请输入最大储值金额"
                    controls-position="right">
                  </el-input-number>
                </el-form-item>
              </div>
              
            </el-form-item>
            <el-form-item label="储值消费可获得积分" prop="storageConfigIsCredit">
              <el-radio-group v-model="form.storageConfigIsCredit">
                <el-radio :label="0">不可积分</el-radio>
                <el-radio :label="1">可积分</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="支持退款" prop="storageConfigRefundType">
              <el-radio-group v-model="form.storageConfigRefundType">
                <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-item label="不参与实体卡储值付款商品：" label-width="220px" prop="storageConfigGoodIds">
              <el-select 
              v-model="form.storageConfigGoodIds" 
              multiple
              clearable 
              placeholder="请选择不参与实体卡储值付款商品">
                <el-option
                  v-for="item in scenicAreaProducts"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </div>
          <el-form-item label="支持积分" prop="isCredit">
            <el-radio-group v-model="form.isCredit">
              <el-radio :label="0">不可积分</el-radio>
              <el-radio :label="1">可积分</el-radio>
            </el-radio-group>
            <span style="color: #ccc;">（积分跟随实体卡卡号，实体卡不与电子会员的积分融合，不支持实体卡与电子会员的绑定）</span>
          </el-form-item>
          <el-form-item label="折扣权益：">
            <div style="display: flex;align-items: center;">
              <el-form-item label="基本折扣：" prop="discountValue" label-width="100px">
                <el-input-number style="width: 150px;" v-model="form.discountValue" controls-position="right" placeholder="请输入基本折扣"></el-input-number>
                <span style="padding-bottom: 15px;">%</span>
              </el-form-item>
              <el-button style="margin-left: 15px;" v-if="!form.discountGoodList||form.discountGoodList.length==0" type="primary" @click="addClassifyList">添加单品</el-button>
            </div>
            
            <div v-for="(item,index) in form.discountGoodList" :key="index" style="margin-top: 10px;display: flex;align-items: center;">
              <el-form-item label="单品折扣：" label-width="100px">
                <el-select v-model="form.discountGoodList[index].goodId" clearable placeholder="请选择单品">
                  <el-option
                    v-for="item in scenicAreaProducts"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
                <el-input-number style="width: 150px;margin-left: 20px;" v-model="form.discountGoodList[index].discountValue" placeholder="请输入单品折扣" controls-position="right"></el-input-number>
                <span style="padding-bottom: 15px;">%</span>
              </el-form-item>
              <el-button style="margin-left: 15px;" v-if="form.discountGoodList.length==(index+1)" type="primary" @click="addClassifyList">添加单品</el-button>
              <el-button style="margin-left: 15px;" type="danger" @click="clearClassifyList(index)">移除</el-button>
            </div>
          </el-form-item>
          <el-form-item label="积分权益：">
            <el-form-item label="积分成长系数：" prop="integralRatio" label-width="120px">
              <el-input-number style="width: 150px;" v-model="form.integralRatio" placeholder="请输入积分成长系数" controls-position="right"></el-input-number>
              <span style="padding-bottom: 15px;font-size: 12px;color: #ccc;">（用户下单获取积分值=实付金额**积分规则基础系数*会员成长系数会员系数越大，获得成长值越多，建议数值设置不要过大）</span>
            </el-form-item>
          </el-form-item>
          <el-form-item label="持卡须知" prop="remark">
            <el-input style="width: 100%;" type="textarea" v-model="form.remark" placeholder="请输入实体卡名称" maxlength="200"
              show-word-limit />
          </el-form-item>
        </el-form>
      </div>
    </div>
    <span slot="footer" class="dialog-footer" v-if="formStatus == 1">
      <el-button @click="cancel" :loading="loading">关闭</el-button>
      <el-button 
      type="primary" 
      @click="submitForm(true)" 
      :loading="loading">
              {{ loading ? '提交中...' : '提交' }}
      </el-button>
    </span>
    <!-- 添加或修改对话框 End -->
  </el-dialog>
</template>

<script>
import {
  getTableDeatilsByIdApi,
  updateTableApi,
  addTableApi
} from '@/api/CURD'

export default {
  name: "addAndEdit",
  dicts: ['activation_rule'],
  data() {
    return {
      title: "",
      model: "", // EDIT: 编辑模式 ADD : 新增模式  EDITInit : 编辑模式（需要请求详情）
      open: false,
      loading: false,
      loadingText: "拼命加载数据中...",
      formStatus: null, // 0/null : 加载中 1 : 获取详情成功 2  : 获取详情失败 
      configUrl: {
        add: '/merchant/merchantEntitycardConfig/insertOrUpdate', // 新增地址
        details: '/merchant/merchantEntitycardConfig/selectById', // 规格详情
        edit: '/merchant/merchantEntitycardConfig/insertOrUpdate', // 编辑地址
      },
      performId: null,
      form: {
        id: undefined,
        activationRule: []
      },
      rules: {
        cardName: [{ required: true, message: "请输入实体卡名称", trigger: ["change", "blur"] }],
        price: [{ required: true, message: "请输入实体卡价格", trigger: ["change", "blur"] }],

        useType: [{ required: true, message: "请选择使用期限", trigger: ["change", "blur"] }],
        useDay: [{ required: false, message: "请输入天数", trigger: ["change", "blur"] }],
        useEndDay: [{ required: false, message: "请选择日期", trigger: ["change", "blur"] }],

        effectiveDateType: [{ required: true, message: "请选择生效日期", trigger: ["change", "blur"] }],
        activationRule: [{ required: true, message: "请选择激活后完善信息", trigger: ["change", "blur"] }],

        isStorageValue: [{ required: true, message: "请选择支持储值", trigger: ["change", "blur"] }],
        minAmount: [{ required: true, message: "请输入最小储值金额", trigger: ["change", "blur"] }],
        maxAmount: [{ required: true, message: "请输入最大储值金额", trigger: ["change", "blur"] }],
        storageConfigIsCredit: [{ required: true, message: "请选择储值消费可获得积分", trigger: ["change", "blur"] }],
        storageConfigRefundType: [{ required: true, message: "请选择支持退款", trigger: ["change", "blur"] }],
        storageConfigGoodIds: [{ required: false, message: "请选择不参与实体卡储值付款商品", trigger: ["change", "blur"] }],

        isCredit: [{ required: true, message: "请选择支持积分", trigger: ["change", "blur"] }],

        discountValue: [{ required: true, message: "请输入基本折扣", trigger: ["change", "blur"] }],
        integralRatio: [{ required: true, message: "请输入积分成长系数", trigger: ["change", "blur"] }],
      },
      tableList: [],// 景点产品关联
      scenicAreaProducts: [],
    };
  },
  methods: {
    async initData(title, model, row) {
      this.title = title
      this.open = true
      this.loadingText = "拼命加载数据中..."
      this.loading = true
      this.actionUrlLoading = false
      this.model = model
      this.formStatus = 0
      if(model=='ADD') { // 新增
        this.$set(this,'form',{
          ...row,
          activationRule: []
        })
        this.formStatus = 1
      }else if(model=='EDIT') { // 新增
        let obj = {
          ...row
        }
        this.$set(this,'form',obj)
        this.formStatus = 1
      }else if(model=='EDITInit') { // 新增
        await this.getTableDeatilsFun(row)
      }
      this.loading = false
      this.$nextTick(()=>{
        if(this.$refs["form"]) {
          this.$refs["form"].clearValidate();
        }
      })
    },
    /** 获取详情 */
    async getTableDeatilsFun(row) {
      const id = row.id
      this.loading = true
      try {
        let res = await getTableDeatilsByIdApi(this.configUrl.details, { id })
        if (res.code == 200) {
          let obj = {
            ...res.data,
            activationRule: res.data.activationRule?res.data.activationRule.split(','):[]
          }
          if(obj.isStorageValue==1) {
            obj['minAmount'] = obj.storageConfig.minAmount
            obj['maxAmount'] = obj.storageConfig.maxAmount
            obj['storageConfigIsCredit'] = obj.storageConfig.isCredit
            obj['storageConfigRefundType'] = obj.storageConfig.refundType
            obj['storageConfigGoodIds'] = obj.storageConfig.goodIds?obj.storageConfig.goodIds.split(','):[]
          }
          this.radioInputs(obj.useType)
          this.$set(this, 'form', JSON.parse(JSON.stringify(obj)))
          this.formStatus = 1
        } else {
          this.$message.error('获取详情失败!!!');
          this.formStatus = 2
          this.loading = false
          //this.open = false;
        }
        this.loading = false
      } catch (error) {
        console.error('获取详情失败!!!!', error)
        this.formStatus = 2
        this.loading = false
        //this.open = false;
      }
    },
    /**
     * 保存
     * @date 2023-11-22
     * @returns {any}
     */
    submitForm(type) {
      console.log("dsfsfds=======", type, this.form)
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.loadingText = "提交数据中..."
          this.loading = true
          let params = JSON.parse(JSON.stringify(this.form))
          if(params.isStorageValue == 1) {
            params['storageConfig'] = {
              isCredit: this.form.storageConfigIsCredit,
              minAmount: this.form.minAmount,
              maxAmount: this.form.maxAmount,
              refundType: this.form.storageConfigRefundType,
              goodIds: this.form.storageConfigGoodIds?this.form.storageConfigGoodIds.join(','):''
            }
          }
          delete params.minAmount
          delete params.maxAmount
          delete params.storageConfigIsCredit
          delete params.storageConfigRefundType
          delete params.storageConfigGoodIds
          addTableApi(this.configUrl.edit, {
            ...params,
            activationRule: params.activationRule?params.activationRule.join(','):null,
          }).then(response => {
            this.$modal.msgSuccess(`${this.form.id ? '编辑' : '新增'}成功`);
            this.loading = false
            this.$set(this, 'form', {activationRule:[]})
            this.$nextTick(() => {
              this.$refs.form.clearValidate();
            })
            this.open = false;
            this.$emit('refresh')
          }).catch(() => {
            this.$message.error(`${this.form.id ? '编辑' : '新增'}失败!!!`);
            this.loading = false
          })
        }
      });
    },
    /**
     * 重置
     * @date 2023-11-22
     * @returns {any}
     */
    reset() {
      if (this.$refs["form"]) {
        //this.$refs["form"].resetFields();
        this.$set(this, 'form', {activationRule:[]})
        this.$nextTick(() => {
          this.$refs["form"].clearValidate();
        })
      }
    },
    /**
     * 关闭弹框
     * @date 2023-11-22
     * @returns {any}
     */
    cancel() {
      this.reset();
      this.open = false;
    },
    /** */
    radioInputs(value) {
      if (value == 1) {
        this.rules.useDay[0].required = false
        this.rules.useEndDay[0].required = false
        this.$refs.form.clearValidate('useDay');
        this.$refs.form.clearValidate('useEndDay');
      } else if (value == 2) {
        this.rules.useDay[0].required = true
        this.rules.useEndDay[0].required = false
        this.$refs.form.clearValidate('useEndDay');
      } else if (value == 3) {
        this.rules.useDay[0].required = false
        this.rules.useEndDay[0].required = true
        this.$refs.form.clearValidate('useDay');
      }
    },
    /** 填加单品  */
    addClassifyList(){
      let list = []
      if(this.form.discountGoodList) {
        list = JSON.parse(JSON.stringify(this.form.discountGoodList))
      }
      list.push({
        goodId: null,
        discountValue: null
      })
      this.$set(this.form,'discountGoodList',list)
    }, 
    /** 移除单品  */
    clearClassifyList(index) {
      this.form.discountGoodList.splice(index,1)
    }
  },
};
</script>

<style lang="scss" scoped>
.form-dialog-box {
  padding: 0 30px;
  padding: 0 30px;
  min-height: 50vh;
  max-height: 65vh;
  overflow-y: auto;

  >div {
    width: 100%;
    min-height: 50vh;
  }

  .form-title {
    padding: 0 0 10px 0;

    span {
      display: flex;
      color: rgba(65, 80, 88, 1);
      font-size: 16px;
      font-family: SourceHanSansSC;
      font-weight: 700;
      line-height: 23px;
      border-left: 4px solid rgb(22, 132, 252);
      padding-left: 10px;
    }

  }

  ::v-deep .ql-editor {
    height: 400px;
  }

  .upload-btn {
    width: 100px;
    height: 100px;
    background-color: #fbfdff;
    border: dashed 1px #c0ccda;
    border-radius: 5px;

    i {
      font-size: 30px;
      margin-top: 20px;
    }

    &-text {
      margin-top: -10px;
    }
  }

  .avatar {
    cursor: pointer;
  }
}

.el-table {
  .upload-btn {
    width: 100px;
    height: 100px;
    background-color: #fbfdff;
    border: dashed 1px #c0ccda;
    border-radius: 5px;

    i {
      font-size: 30px;
      margin-top: 20px;
    }

    &-text {
      margin-top: -10px;
    }
  }

  .avatar {
    cursor: pointer;
  }
}

.area-container {
  min-height: 400px;
}

::v-deep .area-wrap-city.el-cascader {
  line-height: normal;

  .el-input {
    cursor: pointer;
    width: 100% !important;
    height: 28px !important;

    .el-input__inner {
      display: none !important;
    }

    span.el-input__suffix {
      position: inherit !important;

      i.el-input__icon {
        line-height: inherit;
        margin-left: 5px;
      }
    }

    .el-input__wrapper {
      box-shadow: none;

      input {
        display: none;
      }
    }
  }

  .el-cascader__tags {
    display: none;
  }
}

.area-city-popper {
  .el-cascader-panel {
    .el-scrollbar.el-cascader-menu {
      .el-cascader-menu__wrap.el-scrollbar__wrap {
        height: 315px;
      }
    }
  }
}

::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

::v-deep .avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

::v-deep .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

::v-deep .avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
<style>
.custom-class-box {
  z-index: 999999 !important;
}
</style>