<template>
  <div class="reset-wrapper">
    <el-page-header :content="$t('passwordReset:title:reset')" @back="goBack" />
    <el-steps :active="active" align-center style="margin-top: 30px">
      <el-step :title="$t('resetPassword:step:VerifyIdentity')"></el-step>
      <el-step :title="$t('resetPassword:step:ResetPassword')"></el-step>
      <el-step :title="$t('resetPassword:step:ResetSuccess')"></el-step>
    </el-steps>
    <!-- Reset Password -->

    <div class="box-wrapper" v-if="active === 0">
      <el-form
        ref="resetForm"
        v-loading="formLoading"
        :model="form"
        label-width="130px"
        :rules="rules"
        class="demo-ruleForm"
        size="small"
      >
        <!-- 邮箱 -->
        <el-form-item
          :label="$t('passwordReset:form:email')"
          prop="EmailOrPhone"
        >
          <el-col :span="18">
            <el-input
              v-model="form.EmailOrPhone"
              autocomplete="off"
              @change="handleEmailChange"
            />
          </el-col>
        </el-form-item>
        <!-- 验证码 -->
        <el-form-item
          :label="$t('trials:researchForm:form:verifyCode')"
          required
        >
          <el-col :span="18">
            <el-form-item prop="VerificationCode">
              <el-input v-model="form.VerificationCode" autocomplete="off" />
            </el-form-item>
          </el-col>
          <el-col :span="6" style="text-align: right">
            <el-button
              size="small"
              type="primary"
              style="width: 80%"
              :disabled="sendDisabled"
              @click="handleSendCode"
              >{{ sendTitle }}</el-button
            >
          </el-col>
        </el-form-item>
      </el-form>
      <!-- 校验 -->
      <el-button
        size="small"
        type="primary"
        style="width: 50%; margin: auto; display: block"
        :disabled="form.VerificationCode === '' || form.EmailOrPhone === ''"
        @click="verifyCode"
      >
        {{ $t('passwordReset:button:verify') }}
      </el-button>
    </div>
    <div class="box-wrapper" v-show="active === 1">
      <el-form
        ref="resetForm2"
        v-loading="formLoading"
        :model="form"
        :label-width="$i18n.locale === 'en' ? '180px' : '100px'"
        :rules="rules2"
        class="demo-ruleForm"
        size="small"
      >
        <!-- 用户名 -->
        <el-form-item :label="$t('passwordReset:form:userName')" prop="UserId">
          <el-select
            v-model="form.UserId"
            clearable
            filterable
            style="width: 100%"
            @change="handleUserChange"
          >
            <el-option
              v-for="item of users"
              :key="item.UserId"
              :label="item.UserName"
              :value="item.UserId"
            >
              <span style="float: left">{{ item.UserName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{
                item.UserType
              }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 用户类型 -->
        <el-form-item
          v-if="form.UserId"
          :label="$t('passwordReset:form:userType')"
        >
          <el-input v-model="form.UserType" disabled />
        </el-form-item>
        <!-- 新密码 -->
        <el-form-item
          class="my_new_pwd"
          :label="$t('passwordReset:form:password')"
          prop="NewPwd"
          style="position: relative"
        >
          <el-input v-model="form.NewPwd" show-password autocomplete="off" />
          <span style="position: absolute; right: -30px">
            <el-tooltip
              :content="$t('passwordReset:form:passwordCentent')"
              placement="top"
            >
              <i class="el-icon-question" />
            </el-tooltip>
          </span>
        </el-form-item>
        <!-- 确认密码 -->
        <el-form-item
          :label="$t('passwordReset:form:confirmPassword')"
          prop="CheckPass"
        >
          <el-input v-model="form.CheckPass" show-password autocomplete="off" />
        </el-form-item>
      </el-form>
      <div style="width: 50%; margin: auto; display: flex">
        <!-- 取消 -->
        <el-button size="small" @click="onCancel" style="width: 46%">
          {{ $t('passwordReset:button:cancel') }}
        </el-button>
        <!-- 提交 -->
        <el-button
          size="small"
          type="primary"
          @click="onSubmit"
          style="width: 46%"
        >
          {{ $t('passwordReset:button:submit') }}
        </el-button>
      </div>
    </div>
    <div class="box-wrapper flexBox" v-if="active === 3">
      <svg-icon icon-class="resetSuccess" style="width: 300px; height: 300px" />
      <p style="width: 100%; text-align: center">
        {{ $t('resetPassword:successTip') }}
      </p>
      <el-button size="small" type="primary" @click="goBack">
        {{ $t('passwordReset:button:back') }}
      </el-button>
    </div>
  </div>
</template>
<script>
import {
  anonymousSendVerificationCode,
  verifyAnonymousVerifyCode,
  anonymousSetPassword,
} from '@/api/user'
import md5 from 'js-md5'
import Img from '@/assets/icons/svg/resetSuccess.svg'
var timer = ''
var countdown = 60
export default {
  data() {
    var validateEmail = (rule, value, callback) => {
      if (value === '') {
        // 请输入邮箱
        callback(new Error(this.$t('passwordReset:formRule:email')))
      } else {
        var reg =
          /^[A-Za-z0-9]+([_\.][A-Za-z0-9]+)*@([A-Za-z0-9\-]+\.)+[A-Za-z]{2,6}$/
        if (this.form.EmailOrPhone && reg.test(this.form.EmailOrPhone)) {
          this.sendDisabled = false
          callback()
        } else {
          // 邮箱无效
          callback(new Error(this.$t('passwordReset:formRule:passwordinvalid')))
          this.sendDisabled = true
        }
      }
    }
    // var validatePass = (rule, value, callback) => {
    //   if (value === '') {
    //     // 请输入密码
    //     callback(new Error(this.$t('passwordReset:formRule:password')))
    //   } else {
    //     if (this.CheckPass !== '') {
    //       this.$refs.resetForm.validateField('CheckPass')
    //     }
    //     callback()
    //   }
    // }
    var validatePass2 = (rule, value, callback) => {
      if (value === '' || value === undefined) {
        // 请再次输入密码
        callback(new Error(this.$t('passwordReset:formRule:confirmPassword')))
      } else if (value !== undefined && value !== this.form.NewPwd) {
        // 两次密码不一致
        callback(new Error(this.$t('passwordReset:formRule:passwordsDiffer')))
      } else {
        callback()
      }
    }
    return {
      active: 0,
      Img,
      form: {
        EmailOrPhone: '',
        VerificationCode: '',
        NewPwd: '',
        CheckPass: '',
        UserId: '',
        UserType: '',
      },
      users: [],
      CheckPass: '',
      rules: {
        EmailOrPhone: [
          {
            required: true,
            validator: validateEmail,
            trigger: ['blur', 'change'],
          },
        ],
        VerificationCode: [
          {
            required: true,
            message: this.$t('common:ruleMessage:specify'),
            trigger: ['blur', 'change'],
          },
        ],
        NewPwd: [
          {
            required: true,
            validator: this.$validatePassword,
            trigger: ['blur', 'change'],
          },
        ],
        CheckPass: [
          {
            required: true,
            validator: validatePass2,
            trigger: ['blur', 'change'],
          },
        ],
        UserId: [
          {
            required: true,
            message: this.$t('common:ruleMessage:select'),
            trigger: ['blur', 'change'],
          },
        ],
      },
      rules2: {
        NewPwd: [
          {
            required: true,
            validator: this.$validatePassword,
            trigger: ['blur', 'change'],
          },
        ],
        CheckPass: [
          {
            required: true,
            validator: validatePass2,
            trigger: ['blur', 'change'],
          },
        ],
        UserId: [
          {
            required: true,
            message: this.$t('common:ruleMessage:select'),
            trigger: ['blur', 'change'],
          },
        ],
      },
      sendDisabled: true,
      sendTitle: this.$t('passwordReset:button:send'),
      formLoading: false,
    }
  },
  methods: {
    onSubmit() {
      this.$refs['resetForm2'].validate((valid) => {
        if (valid) {
          this.formLoading = true
          anonymousSetPassword(this.form.UserId, md5(this.form.NewPwd))
            .then((res) => {
              if (res.IsSuccess) {
                // 修改成功
                this.$message.success(
                  this.$t('passwordReset:message:updatedSuccessfully')
                )
                this.formLoading = false
                this.active = 3
                // this.goBack();
              } else {
                this.$alert(res.ErrorMessage)
              }
            })
            .catch(() => {
              this.formLoading = false
            })
        }
      })
    },
    handleSendCode() {
      const that = this
      this.sendDisabled = true
      // var isReviewer = JSON.parse(zzSessionStorage.getItem('IsReviewer'))
      anonymousSendVerificationCode(this.form.EmailOrPhone)
        .then((res) => {
          if (res.IsSuccess) {
            let msg = this.$t('passwordReset:message:tip:sendCode').replace(
              'xxx',
              this.form.EmailOrPhone
            )
            this.$message.success(msg)
            that.settime(that)
          } else {
            that.$alert(res.ErrorMessage)
          }
        })
        .catch(() => {
          this.sendDisabled = false
        })
    },
    verifyCode() {
      this.formLoading = true
      verifyAnonymousVerifyCode(
        this.form.EmailOrPhone,
        this.form.VerificationCode
      )
        .then((res) => {
          this.formLoading = false
          this.users = res.Result
          if (this.users.length === 1) {
            this.form.UserId = this.users[0].UserId
            this.form.UserType = this.users[0].UserType
          }
          // 验证成功
          this.$message.success(
            this.$t('passwordReset:message:verifiedSuccessfully')
          )
          this.active = 1
        })
        .catch(() => {
          this.formLoading = false
        })
    },
    handleEmailChange() {
      var reg =
        /^[A-Za-z0-9]+([_\.][A-Za-z0-9]+)*@([A-Za-z0-9\-]+\.)+[A-Za-z]{2,6}$/
      if (this.form.EmailOrPhone && reg.test(this.form.EmailOrPhone)) {
        this.sendDisabled = false
      }
    },
    handleUserChange(val) {
      const seleted = this.users.findIndex((user) => user.UserId === val)
      if (seleted > -1) {
        this.form.UserType = this.users[seleted].UserType
      }
    },
    settime(obj) {
      if (countdown === 0) {
        obj.sendDisabled = false
        obj.sendTitle = this.$t('passwordReset:button:send')
        countdown = 60
        clearTimeout(timer)
        return
      } else {
        obj.sendDisabled = true
        obj.sendTitle = `${this.$t('passwordReset:button:wait')}(${countdown}s)`
        countdown--
        // eslint-disable-next-line no-self-assign
        countdown = countdown
        timer = setTimeout(function () {
          obj.settime(obj)
        }, 1000)
      }
    },
    onCancel() {
      this.$refs['resetForm'].resetFields()
      Object.keys(this.form).forEach((key) => {
        this.form[key] = ''
      })
      this.active = 0
    },
    goBack() {
      this.$router.push('/login')
    },
  },
}
</script>
<style>
.reset-wrapper {
  padding: 20px;
}
.reset-wrapper .el-page-header {
  line-height: 50px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #fff;
}
.reset-wrapper .box-wrapper {
  width: 700px;
  margin: 20px auto;
  padding: 10px;
  color: #303133;
  /* border: 1px solid #e6e6e6; */
}
</style>
<style scoped>
/*/deep/ .is-error{*/
/*  margin-bottom: 40px;*/
/*}*/
.is-error.my_new_pwd {
  margin-bottom: 40px;
}
.flexBox {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
}
</style>
