<!-- 
/**
	* 忘记密码 
	*@desc 忘记密码填写表单(通过手机号获取验证码)
	*
**/ 
 -->
<template>
  <div class="rest-password-box" :class="{ 'rest-password-cut': show }">
    <el-menu
      v-if="show"
      :default-active="activeIndex"
      class="rest-menu-cut"
      mode="horizontal"
      @select="handleSelect"
    >
      <el-menu-item index="6">短信验证</el-menu-item>
      <el-menu-item index="11">邮箱验证</el-menu-item>
      <el-menu-item index="0" v-if="this.operationCheckCode"
        >原密码验证</el-menu-item
      >
    </el-menu>
    <es-form
      ref="pwdForm"
      v-loading.fullscreen.lock="submit"
      element-loading-text="修改中..."
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.65)"
      class="es-rest-password"
      :model="formData"
      :contents="page"
      :autocomplete="false"
      @submit="handleSubmit"
    >
    </es-form>
  </div>
</template>

<script>
import {
  initModifyPassword,
  getModifyPassCode,
  codeModifyPass,
  loginModifyPassword
} from 'eoss-ui/src/config/api.js';
import rules from 'eoss-ui/src/utils/rules.js';
import util from 'eoss-ui/src/utils/util';
export default {
  name: 'resetPassword',
  props: {
    secret: String,
    isEncrypt: Boolean,
    type: String,
    operationCheckCode: String,
    username: String
  },
  computed: {
    page() {
      switch (this.activeIndex) {
        case '6':
          return [
            {
              type: 'text',
              name: 'target',
              label: '手机号',
              placeholder: '请输入手机号',
              rules: [
                {
                  required: true,
                  message: '请输入手机号',
                  trigger: 'blur'
                },
                {
                  ...rules.phone,
                  trigger: 'blur'
                }
              ]
            },
            {
              type: 'password',
              name: 'password',
              label: '新密码',
              placeholder: '请输入新密码',
              showPassword: true,
              rules: [
                this.checkPassword
                  ? {
                      pattern: this.checkPassword,
                      message: this.checkPasswordMsg
                        ? this.checkPasswordMsg
                        : '密码格式不合法',
                      trigger: 'blur'
                    }
                  : {},
                {
                  required: true,
                  message: '请输入新密码',
                  trigger: 'blur'
                }
              ]
            },
            {
              type: 'password',
              name: 'repassword',
              placeholder: '请确认新密码',
              label: '确认新密码',
              showPassword: true,
              rules: [
                this.checkPassword
                  ? {
                      pattern: this.checkPassword,
                      message: this.checkPasswordMsg
                        ? this.checkPasswordMsg
                        : '密码格式不合法',
                      trigger: 'blur'
                    }
                  : {},
                {
                  required: true,
                  message: '请输入新密码',
                  trigger: 'blur'
                },
                { validator: this.reregExpValidate, trigger: 'blur' }
              ]
            },
            {
              type: 'text',
              name: 'verificationCode',
              placeholder: '请输入验证码',
              label: '验证码',
              append: {
                text: this.btnText,
                attrs: { disabled: this.disabled },
                event: this.getVerificationCode
              },
              rules: [
                {
                  required: true,
                  message: '请输入验证码',
                  trigger: 'blur'
                }
              ]
            },
            {
              type: 'submit',
              contents: [
                {
                  type: 'primary',
                  text: '提交',
                  event: 'confirm'
                }
              ]
            }
          ];
        case '11':
          return [
            {
              type: 'text',
              name: 'target',
              label: '邮箱地址',
              placeholder: '请输入邮箱地址',
              rules: [
                {
                  required: true,
                  message: '请输入邮箱地址',
                  trigger: 'blur'
                },
                {
                  type: 'email',
                  message: '请输入正确的邮箱地址',
                  trigger: 'blur'
                }
              ]
            },
            {
              type: 'password',
              name: 'password',
              label: '新密码',
              placeholder: '请输入新密码',
              showPassword: true,
              rules: [
                this.checkPassword
                  ? {
                      pattern: this.checkPassword,
                      message: this.checkPasswordMsg
                        ? this.checkPasswordMsg
                        : '密码格式不合法',
                      trigger: 'blur'
                    }
                  : {},
                {
                  required: true,
                  message: '请输入新密码',
                  trigger: 'blur'
                }
              ]
            },
            {
              type: 'password',
              name: 'repassword',
              placeholder: '请确认新密码',
              label: '确认新密码',
              showPassword: true,
              rules: [
                this.checkPassword
                  ? {
                      pattern: this.checkPassword,
                      message: this.checkPasswordMsg
                        ? this.checkPasswordMsg
                        : '密码格式不合法',
                      trigger: 'blur'
                    }
                  : {},
                {
                  required: true,
                  message: '请输入新密码',
                  trigger: 'blur'
                },
                { validator: this.reregExpValidate, trigger: 'blur' }
              ]
            },
            {
              type: 'text',
              name: 'verificationCode',
              placeholder: '请输入验证码',
              label: '验证码',
              append: {
                text: this.btnText,
                attrs: { disabled: this.disabled },
                event: this.getVerificationCode
              },
              rules: [
                {
                  required: true,
                  message: '请输入验证码',
                  trigger: 'blur'
                }
              ]
            },
            {
              type: 'submit',
              contents: [
                {
                  type: 'primary',
                  text: '提交',
                  event: 'confirm'
                }
              ]
            }
          ];
        case '0':
          this.$set(
            this.formData,
            'username',
            this.username ? this.username : ''
          );
          return [
            {
              type: 'text',
              name: 'userName',
              label: '用户名',
              placeholder: '请输入用户名',
              rules: [
                {
                  required: true,
                  message: '请输入用户名',
                  trigger: 'blur'
                }
              ]
            },
            {
              type: 'password',
              name: 'oldPassword',
              label: '旧密码',
              placeholder: '请输入旧密码',
              showPassword: true,
              rules: [
                {
                  required: true,
                  message: '请输入旧密码',
                  trigger: 'blur'
                }
              ]
            },
            {
              type: 'password',
              name: 'password',
              label: '新密码',
              placeholder: '请输入新密码',
              showPassword: true,
              rules: [
                this.checkPassword
                  ? {
                      pattern: this.checkPassword,
                      message: this.checkPasswordMsg
                        ? this.checkPasswordMsg
                        : '密码格式不合法',
                      trigger: 'blur'
                    }
                  : {},
                {
                  required: true,
                  message: '请输入新密码',
                  trigger: 'blur'
                }
              ]
            },
            {
              type: 'password',
              name: 'repassword',
              placeholder: '请确认新密码',
              label: '确认新密码',
              showPassword: true,
              rules: [
                this.checkPassword
                  ? {
                      pattern: this.checkPassword,
                      message: this.checkPasswordMsg
                        ? this.checkPasswordMsg
                        : '密码格式不合法',
                      trigger: 'blur'
                    }
                  : {},
                {
                  required: true,
                  message: '请确认新密码',
                  trigger: 'blur'
                },
                { validator: this.reregExpValidate, trigger: 'blur' }
              ]
            },
            {
              type: 'submit',
              contents: [
                {
                  type: 'primary',
                  text: '提交',
                  event: 'confirm'
                }
              ]
            }
          ];
      }
    },
    show() {
      if (this.type) {
        let types = this.type.split(',');
        return types.length > 1;
      }
      return false;
    }
  },
  data() {
    return {
      activeIndex: '0',
      checkPassword: null,
      checkPasswordMsg: null,
      btnText: '获取验证码',
      timer: '',
      countdown: 0,
      disabled: false,
      submit: false,
      formData: {}
    };
  },
  created() {
    this.getInitModifyPassword();
    if (this.type) {
      let types = this.type.split(',');
      if (types.length) {
        this.activeIndex = types[0];
      }
    } else {
      this.activeIndex = '0';
    }
  },
  destroyed() {
    clearInterval(this.timer);
  },
  methods: {
    // 密码再次验证
    reregExpValidate(rule, value, callback) {
      if (value != this.formData.password) {
        callback(new Error('两次密码不一致'));
      } else {
        callback();
      }
    },
    getInitModifyPassword() {
      util
        .ajax({
          url: initModifyPassword
        })
        .then((res) => {
          if (res.rCode === 0) {
            const results = JSON.parse(JSON.stringify(res.results));
            if (results.checkPassword) {
              this.checkPassword = new RegExp(results.checkPassword);
            }
            if (results.checkPasswordMsg) {
              this.checkPasswordMsg = results.checkPasswordMsg;
            }
          } else {
            let msg = res.msg || '系统错误，请联系管理员！';
            this.$message.error(msg);
          }
        })
        .catch((err) => {
          if (err.message && err.message !== 'canceled') {
            this.$message.error(err.message);
          }
        });
    },
    getVerificationCode() {
      if (this.countdown) {
        return false;
      }
      if (!this.formData.target) {
        this.$refs.pwdForm.validateField('target');
        return false;
      } else {
        let flag = false;
        this.$refs.pwdForm.validateField('target', (res) => {
          flag = res != '';
        });
        if (flag) {
          return false;
        }
        let data = {
          target: this.formData.target,
          targetType: this.activeIndex == '6' ? 'SMS' : 'EMAIL'
        };
        this.countdown = 60;
        this.getCode(data);
        this.timer = setInterval(() => {
          if (this.countdown > 0) {
            this.countdown--;
            this.disabled = true;
            this.btnText = '重新获取' + this.countdown + 's';
          } else {
            this.btnText = '获取验证码';
            this.disabled = false;
            clearInterval(this.timer);
          }
        }, 1000);
      }
    },
    getCode(params) {
      util
        .ajax({
          url: getModifyPassCode,
          params: params
        })
        .then((res) => {
          if (res.rCode === 0) {
            this.$message.success(res.msg);
          } else {
            let msg = res.msg || '系统错误，请联系管理员！';
            if (res.rCode === 2) {
              this.btnText = '获取验证码';
              this.disabled = false;
              this.countdown = 0;
              clearInterval(this.timer);
            }
            this.$message.error(msg);
          }
        })
        .catch((err) => {
          if (err.message && err.message !== 'canceled') {
            this.$message.error(err.message);
          }
        });
    },
    handleSubmit(res) {
      this.submit = true;
      let { repassword, ...data } = res;
      if (this.secret && this.isEncrypt) {
        data.password = util.esmEncrypt({
          data: data.password,
          key: this.secret
        });
        if (data.oldPassword) {
          data.oldPassword = util.esmEncrypt({
            data: data.oldPassword,
            key: this.secret
          });
        }
      }
      if (this.activeIndex == '0') {
        data.operationCheckCode = this.operationCheckCode;
        util
          .ajax({
            method: 'post',
            url: loginModifyPassword,
            data: data
          })
          .then((res) => {
            this.submit = false;
            if (res.rCode === 0) {
              this.$message.success(res.msg);
              this.$emit('success');
            } else {
              let msg = res.msg || '系统错误，请联系管理员！';
              this.$message.error(msg);
              this.disabled = false;
              delete this.formData.verificationCode;
              clearInterval(this.timer);
            }
          })
          .catch((err) => {
            if (err.message && err.message !== 'canceled') {
              this.$message.error(err.message);
            }
          });
      } else {
        if (this.activeIndex == '6') {
          data.targetType = 'SMS';
        } else {
          data.targetType = 'EMAIL';
        }
        util
          .ajax({
            method: 'post',
            url: codeModifyPass,
            data: data
          })
          .then((res) => {
            this.submit = false;
            if (res.rCode === 0) {
              this.$message.success(res.msg);
              this.$emit('success');
            } else {
              let msg = res.msg || '系统错误，请联系管理员！';
              this.btnText = '获取验证码';
              this.disabled = false;
              clearInterval(this.timer);
              delete this.formData.verificationCode;
              this.$message.error(msg);
            }
          })
          .catch((err) => {
            if (err.message && err.message !== 'canceled') {
              this.$message.error(err.message);
            }
          });
      }
    },
    handleSelect(res) {
      this.$refs.pwdForm.resetFields();
      this.activeIndex = res;
      this.btnText = '获取验证码';
      this.disabled = false;
      clearInterval(this.timer);
    }
  }
};
</script>
