<template>
  <el-drawer :visible.sync="visible" direction="rtl" :before-close="beforeClose" size="600px" custom-class="drawer" :modal="false">
    <template v-slot:title>
      <h2>计费规则配置</h2>
    </template>
    <el-form ref="form" :model="form" class="content" label-width="195px" :rules="rules">
      <p class="tip lineh17">开启“多账户模式”后，系统将根据所配置的计费规则将通讯费用按照“独立计费部门”进行汇总核算及扣除费用；开启后次日凌晨生效，并且开启后不允许关闭，请谨慎操作；</p>
      <el-form-item label="是否开启多账户模式：" class="mt15 mb15" prop="status">
        <el-radio-group v-model="form.status" :disabled="isMoreAccount">
          <el-radio :label="0">关闭</el-radio>
          <el-radio :label="1">开启</el-radio>
        </el-radio-group>
      </el-form-item>
      <template v-if="form.status">
        <hr class="mb10" />
        <div class="info mb15">
          <i class="iconfont icon-warning-circle-fill icon" />
          <div class="lineh22">
            <p class="tip">计费规则说明：</p>
            <p class="tip">1、会员所属服务门店：由会员所属的服务门店承担费用（最终根据门店所属的“独立计费部门”进行汇总核算和扣除），若产生费用时会员无服务门店，则由总部承担费用；</p>
            <p class="tip">2、活动创建人：由此活动的创建人来承担费用（最终根据该管理员所属的“独立计费部门”进行汇总核算和扣除）；</p>
            <p class="tip">3、导购所在门店：由导购所在的门店承担费用（最终根据门店所属的“独立计费部门”进行汇总核算和扣除）；</p>
            <p class="tip">4、总部：由“总部”承担费用；</p>
          </div>
        </div>
        <template>
          <h2 class="icon-type-title mb20">
            <div class="mark" />
            短信
          </h2>
          <el-form-item label="短信营销：" prop="smsPlanRule" class="mb20">
            <el-radio-group v-model="form.smsPlanRule">
              <el-radio :label="2">会员所属服务门店</el-radio>
              <el-radio :label="3">活动创建人</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="智能&扫码营销发送短信：" prop="smsEcmRule" class="mb20">
            <el-radio-group v-model="form.smsEcmRule">
              <el-radio :label="2">会员所属服务门店</el-radio>
              <el-radio :label="3">活动创建人</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="会员修改手机号：" prop="smsValidCodeRule" class="mb20">
            <el-radio-group v-model="form.smsValidCodeRule">
              <el-radio :label="2">会员所属服务门店</el-radio>
              <el-radio :label="1">总部</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="会员认证开卡：" prop="smsOpenCardRule" class="mb20">
            <el-radio-group v-model="form.smsOpenCardRule">
              <el-radio :label="1">总部</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="登录观云台小程序：" prop="gytRule" class="mb20">
            <el-radio-group v-model="form.gytRule">
              <el-radio :label="1">总部</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="好办-导购绑定手机号：" prop="smsHaobanRule" class="mb20">
            <el-radio-group v-model="form.smsHaobanRule">
              <el-radio :label="4">导购所在门店</el-radio>
            </el-radio-group>
          </el-form-item>
        </template>
        <hr class="dashed mb20" />
        <template>
          <h2 class="icon-type-title mb20">
            <div class="mark" />
            双向呼叫
          </h2>
          <el-form-item label="双向呼叫：" prop="callRule" class="mb20">
            <el-radio-group v-model="form.callRule">
              <el-radio :label="4">导购所在门店</el-radio>
              <el-radio :label="3">活动创建人</el-radio>
            </el-radio-group>
          </el-form-item>
        </template>

        <hr class="dashed mb20" v-if="isMoreAccount" />
        <template v-if="isMoreAccount">
          <h2 class="icon-type-title mb20">
            <div class="mark" />
            AI营销
          </h2>
          <el-form-item label="AI电话(包含短信)：" prop="aiRule" class="mb20">
            <el-radio-group v-model="form.aiRule">
              <el-radio :label="2">会员所属服务门店</el-radio>
              <el-radio :label="3">活动创建人</el-radio>
            </el-radio-group>
          </el-form-item>
        </template>
      </template>
    </el-form>
    <div class="footer">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" :loading="loading" @click="save">保 存</el-button>
    </div>
  </el-drawer>
</template>

<script>
import { saveAccountRule } from '@/service/api/rechargeApi';
export default {
  name: 'setRuleDrawer',
  props: {
    visible: Boolean,
    data: Object
  },
  data() {
    function validate(val, cb, arr) {
      if (!arr.includes(val)) return cb(new Error('请选择内容'));
      cb();
    }
    return {
      loading: false,
      form: {
        status: 0, // 是否多账户
        smsPlanRule: 2, // 短信营销
        smsEcmRule: 2, // 智能引擎
        smsValidCodeRule: 1, // 修改手机号
        smsOpenCardRule: 1, // 认证
        smsHaobanRule: 4, // 好办
        callRule: 4, // 双向呼叫
        gytRule: 1, // 观云台小程序
        aiRule: 3 // AI营销
      },
      isMoreAccount: false,
      rules: {
        smsPlanRule: [{ required: true, validator: (rule, val, cb) => validate(val, cb, [2, 3]) }],
        smsEcmRule: [{ required: true, validator: (rule, val, cb) => validate(val, cb, [2, 3]) }],
        smsValidCodeRule: [{ required: true, validator: (rule, val, cb) => validate(val, cb, [2, 1]) }],
        smsOpenCardRule: [{ required: true, validator: (rule, val, cb) => validate(val, cb, [1]) }],
        gytRule: [{ required: true, validator: (rule, val, cb) => validate(val, cb, [1]) }],
        smsHaobanRule: [{ required: true, validator: (rule, val, cb) => validate(val, cb, [4]) }],
        callRule: [{ required: true, validator: (rule, val, cb) => validate(val, cb, [3, 4]) }],
        aiRule: [{ required: true, validator: (rule, val, cb) => validate(val, cb, [2, 3]) }]
      }
    };
  },
  methods: {
    close() {
      this.$emit('update:visible', false);
    },
    save() {
      this.$refs['form'].validate(async valid => {
        if (valid) {
          const options1 = { confirmButtonText: '确认开启', cancelButtonText: '取消', type: 'warning' };
          const options2 = { confirmButtonText: '立即设置', cancelButtonText: '稍后设置', type: 'success' };
          try {
            // 单商户转多商户二次弹窗确认,不存在多切单的情况
            const para = this.form.status ? this.form : {};
            // 比较字段值是否有改变
            if (this.compareIsEdit(para, this.data)) {
              this.loading = true;
              if (!this.isMoreAccount) {
                await this.$confirm('开启多账户计费模式次日凌晨生效，并且开启后不允许关闭', '确认开启多账户模式？', options1);
                await saveAccountRule(para).finally(() => (this.loading = false));
                this.$emit('getNewData', !this.isMoreAccount);
                try {
                  await this.$confirm('赶紧去设置不同的计费账户吧，也可点击【计费中心-账户明细】配置不同的计费账户', '保存成功', options2);
                  this.$router.push(this.$router.push('/recharge/accountDetail'));
                } catch (e) {
                  this.$emit('update:visible', false);
                  return false;
                }
              } else {
                await saveAccountRule(para).finally(() => (this.loading = false));
                this.$emit('getNewData', this.isMoreAccount);
                this.$emit('update:visible', false);
                return this.$message.success('保存成功');
              }
            } else {
              this.$emit('update:visible', false);
              return this.$message.success('保存成功');
            }
          } catch (e) {
            return false;
          }
        }
      });
    },
    extend(to, from) {
      for (let key in to) {
        if (!from.hasOwnProperty(key)) continue;
        to[key] = from[key];
      }
    },
    beforeClose() {
      this.$emit('update:visible', false);
    },
    compareIsEdit(data, all) {
      for (let key in data) {
        if (data[key] != all[key]) {
          return true;
        }
      }
      return false;
    }
  },
  watch: {
    data: {
      handler: function(newVal) {
        this.isMoreAccount = !!newVal.status;
        this.extend(this.form, newVal);
        this.form['status'] = this.form['status'] || 0;
      },
      deep: true,
      immediate: true
    }
  }
};
</script>

<style lang="scss" scoped>
.drawer {
  position: relative;
  /deep/ .el-form-item {
    margin-bottom: 20px;
  }
}
h2 {
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}
.content {
  font-family: PingFangSC-Regular, PingFang SC;
  padding: 0 20px 56px;
  color: #303133;
  .tip {
    color: #909399;
    font-size: 12px;
  }
  .lineh17 {
    line-height: 17px;
  }
  .lineh22 {
    line-height: 22px;
  }
  hr {
    height: 1px;
    background: #e4e7ed;
    outline: none;
    border: none;
    &.dashed {
      height: 0;
      border: 1px dashed #e4e7ed;
      background: none;
    }
  }
  .info {
    display: flex;
    .icon {
      margin-right: 9px;
      color: #2f54eb;
      display: block;
      position: relative;
      top: 3px;
    }
  }
  .icon-type-title {
    display: flex;
    align-items: center;
    height: 20px;
    color: #303133;
    font-size: 16px;
    font-weight: 700;
    padding: 10px;
    background: #f7f8fa;
    .mark {
      width: 3px;
      height: 14px;
      margin-right: 8px;
      background-color: #2f54eb;
    }
  }
}
.footer {
  position: absolute;
  bottom: 0;
  padding: 0 20px;
  box-shadow: 0px -2px 8px 0px rgba(220, 223, 230, 0.6);
  box-sizing: border-box;
  height: 56px;
  width: 100%;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  background: #fff;
}
</style>
