<template>
  <div class="reset-wrapper">
    <!-- Reset Password -->
    <el-page-header :content="$t('passwordReset:title:reset')" @back="goBack" />
    <div class="box-wrapper">
      <el-form ref="resetForm" v-loading="formLoading" :model="form" label-width="150px" :rules="rules"
        class="demo-ruleForm" size="small">
        <!-- 邮箱 -->
        <el-form-item :label="$t('passwordReset:form:email')" prop="EmailOrPhone">
          <el-input v-model="form.EmailOrPhone" autocomplete="off" @change="handleEmailChange"
            v-if="!IsCanConnectInternet" />
          <template v-else>
            <el-col :span="18">
              <el-input v-model="form.EmailOrPhone" autocomplete="off" @change="handleEmailChange" />
            </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>
          </template>
        </el-form-item>
        <!-- 验证码 -->
        <el-form-item :label="!IsCanConnectInternet
          ? $t('trials:researchForm:form:checkCode')
          : $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">
            <i :title="isVerify === null
              ? $t('passwordReset:button:verify')
              : isVerify
                ? $t('passwordReset:button:verifySuccess')
                : $t('passwordReset:button:Failed')
              " :class="isVerify === null
                ? 'el-icon-question'
                : isVerify
                  ? 'el-icon-success'
                  : 'el-icon-error'
                " :style="{
                  marginRight: '5px',
                  color:
                    isVerify === null
                      ? '#909399'
                      : isVerify
                        ? '#67c23a'
                        : '#f56c6c',
                }"></i>
            <!-- 校验 -->
            <el-button size="small" type="primary" :style="{
              width: '80%',
            }" :disabled="form.VerificationCode === '' || form.EmailOrPhone === ''
              " @click="verifyCode">
              {{ $t("passwordReset:button:verify") }}
            </el-button>
          </el-col>
          <span v-if="isVerify" style="float: left">{{
            $t("passwordReset:tip:verifySuccess")
          }}</span>
        </el-form-item>
        <!-- 用户名 -->
        <el-form-item :label="$t('passwordReset:form:userName')" prop="UserId">
          <span :title="userMsg">{{ userMsg }}</span>
          <!-- <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:passwordtip')" 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-item style="text-align: right">
          <!-- 取消 -->
          <el-button size="small" @click="onCancel">
            {{ $t("passwordReset:button:cancel") }}
          </el-button>
          <!-- 提交 -->
          <el-button size="small" type="primary" @click="onSubmit">
            {{ $t("passwordReset:button:submit") }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import {
  anonymousSendVerificationCode,
  verifyAnonymousVerifyCode,
  anonymousSetPassword,
} from "@/api/user";
import md5 from "js-md5";
import { getHospital } from "@/api/hospital.js";
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 {
      form: {
        EmailOrPhone: "",
        VerificationCode: "",
        NewPwd: "",
        UserId: "",
        UserType: "",
      },
      isVerify: null,
      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"],
        //   },
        // ],
      },
      sendDisabled: true,
      sendTitle: this.$t("passwordReset:button:send"),
      formLoading: false,
      IsCanConnectInternet: true,
    };
  },
  computed: {
    userMsg() {
      if (!this.users || this.users.length <= 0) return ''
      let str = ''
      this.users.forEach((item, index) => {
        if (index === 0) {
          str += `${item.UserName}(`
        }

        if (index === this.users.length - 1) {
          str += `${item.UserTypeShortName})`
        } else {
          str += `${item.UserTypeShortName}、`
        }
      })
      return str
    }
  },
  created() {
    this.getInfo();
  },
  methods: {
    // 获取医院信息
    async getInfo() {
      try {
        let res = await getHospital();
        if (res.IsSuccess) {
          this.IsCanConnectInternet = res.Result.IsCanConnectInternet;
        }
      } catch (err) {
        console.log(err);
      }
    },
    onSubmit() {
      this.$refs["resetForm"].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.goBack();
              } else {
                this.$alert(res.ErrorMessage);
              }
            })
            .catch(() => {
              this.formLoading = false;
            });
        }
      });
    },
    handleSendCode() {
      const that = this;
      this.sendDisabled = true;
      anonymousSendVerificationCode(this.form.EmailOrPhone)
        .then((res) => {
          if (res.IsSuccess) {
            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 && this.users.length > 0) {
            this.form.UserId = this.users[0].IdentityUserId
          }
          this.isVerify = true;
          this.$message.success(this.$t("passwordReset:button:verifySuccess"));
        })
        .catch(() => {
          this.formLoading = false;
          this.isVerify = false;
          this.users = [];
          this.form.UserId = null;
        });
    },
    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();
    },
    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>
/*>>>.is-error{*/
/*  margin-bottom: 40px;*/
/*}*/
::v-deep .is-error.my_new_pwd {
  margin-bottom: 40px;
}
</style>
