<template>
  <div class="trial-myinfo-right">
    <div class="trial-myinfo-right-box">
      <div class="trial-myinfo-head">
        <!-- 账号信息 -->
        {{ $t("trials:trials-myinfo:title:accountInfo") }}
      </div>
      <el-form label-position="right" label-width="100px" ref="userForm" :model="userForm" :rules="rules">
        <!-- 用户名 -->
        <el-form-item :label="$t('trials:trials-myinfo:form:userName')" style="margin-bottom: 5px" prop="UserName">
          <span>{{ user.UserName }}</span>
        </el-form-item>
        <el-form-item label="" style="position: relative" prop="UserName">
          <el-input v-model="userForm.UserName" :placeholder="$t('trials:trials-myinfo:form:userName')" />
          <!-- 修改 -->
          <el-button :disabled="!userForm.UserName" class="saveBtn" type="primary" size="small" @click="setNewUserName">
            {{ $t("trials:trials-myinfo:button:update") }}
          </el-button>
        </el-form-item>
        <!-- 校验码 -->
        <el-form-item :label="$t('trials:researchForm:form:checkCode')" style="margin-bottom: 5px" prop="CheckCode">
          <span>{{ user.CheckCode }}</span>
        </el-form-item>
        <el-form-item label="" style="position: relative" prop="CheckCode">
          <el-input v-model="userForm.CheckCode" :placeholder="$t('trials:researchForm:form:checkCode')" :maxlength="6"
            :title="this.$t('recompose:tip:inputCheckCode')" type="number" />
          <!-- 修改 -->
          <el-button :disabled="!userForm.CheckCode || userForm.CheckCode.length != 6" class="saveBtn" type="primary"
            size="small" @click.stop="setNewUserCheckCode">
            {{ $t("trials:trials-myinfo:button:update") }}
          </el-button>
        </el-form-item>
        <!-- 电话 -->
        <el-form-item :label="$t('trials:trials-myinfo:form:phone')" style="margin-bottom: 5px" prop="Phone">
          <span>{{ user.Phone }}</span>
        </el-form-item>
        <el-form-item label="" style="position: relative">
          <el-input v-model="userForm.Phone" :placeholder="$t('trials:trials-myinfo:form:phone')" />
          <!-- 修改 -->
          <el-button :disabled="!userForm.Phone" class="saveBtn" type="primary" size="small" @click="setNewPhone">
            {{ $t("trials:trials-myinfo:button:update") }}
          </el-button>
        </el-form-item>
        <!-- 邮箱 -->
        <el-form-item :label="$t('trials:trials-myinfo:form:email')" style="margin-bottom: 5px">
          <span>{{ user.EMail }}</span>
        </el-form-item>
        <el-form-item label="" style="margin-bottom: 10px; position: relative" prop="EMail" v-if="IsCanConnectInternet">
          <el-input v-model="userForm.EMail" @input="handleEmailChange"
            :placeholder="$t('trials:trials-myinfo:form:email')" />
          <el-button class="sendCode" :disabled="sendDisabled" type="primary" size="mini"
            @click="sendVerificationCode">{{ sendTitle }}</el-button>
        </el-form-item>
        <el-form-item label="" style="position: relative" v-if="IsCanConnectInternet">
          <el-input v-model="userForm.VerificationCode" :placeholder="$t('trials:researchForm:form:verifyCode')" />
          <!-- 修改 -->
          <el-button :disabled="!userForm.EMail || !userForm.VerificationCode
            " class="saveBtn" type="primary" size="small" @click="setNewEmail">
            {{ $t("trials:trials-myinfo:button:update") }}
          </el-button>
        </el-form-item>
        <el-form-item :label="$t('trials:trials-myinfo:form:toggleRole')" style="position: relative" v-if="hasRole">
          <el-radio-group v-model="userRoleId" class="roles" v-if="hasRole">
            <el-radio v-for="item in roles" :key="item.Id" :label="item.Id" :disabled="item.IsUserRoleDisabled"
              style="margin-bottom: 10px">
              {{ item.UserTypeShortName }}
            </el-radio>
          </el-radio-group>
          <!-- 修改 -->
          <el-button :disabled="!userRoleId || saveDisabled" class="saveBtn" :loading="toggleRoleLoading" type="primary"
            size="small" @click="toggleRole">
            {{ $t('trials:trials-myinfo:button:toggleRole') }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <password />
  </div>
</template>
<script>
import {
  sendVerificationCode,
  setNewEmail,
  setNewPhone,
  setNewUserName,
  SetNewCheckCode,
} from "@/api/system/user.js";
import { removeToken } from "@/utils/auth";
import password from "./password.vue";
var timer = "";
var countdown = 60;
export default {
  name: "account",
  components: { password },
  props: {
    user: {
      required: true,
      default: () => {
        return {};
      },
    },
    IsCanConnectInternet: {
      required: true,
      default: true,
    },
  },
  data() {
    return {
      userForm: {},
      sendDisabled: true,
      sendTitle: this.$t("trials:trials-myinfo:button:getVCode"),
      userRoleId: null,
      toggleRoleLoading: false,
      rules: {
        CheckCode: [
          {
            validator: (rule, value, callback) => {
              const regex = /^[1-9]\d{5}$/;
              if (
                value &&
                (String(value).includes('.') ||
                  !regex.test(String(value)))
              ) {
                callback(new Error(this.$t('recompose:tip:inputCheckCode')))
              } else {
                callback()
              }
            },
            trigger: 'blur',
          },
        ],
        EMail: [
          {
            pattern: new RegExp(this.$reg().EmailRegexStr),
            message: this.$t("passwordReset:formRule:passwordinvalid"),
            trigger: ['blur'],
          },
        ],
        UserName: [
          {
            validator: (rule, value, callback) => {
              var lang = zzSessionStorage.getItem('lang')
                ? zzSessionStorage.getItem('lang')
                : 'zh'
              /* eslint-disable */
              var reg1 = /^[a-zA-Z0-9_]{4,16}$/ //密码必须是8位以上、必须含有字母、数字、特殊符号
              if (value && !reg1.test(value)) {
                callback(
                  lang === 'zh'
                    ? new Error(
                      '1）新建账号，用户名字符长度最小为4个字符，最大为16个字符，只可使用字母、数字、下划线；'
                    )
                    : new Error(
                      'For a new account, the username must have:1) At least 4 characters;2) At most 16 characters;3)Only letters, numbers, and underscores are allowed.'
                    )
                )
              } else {
                callback()
              }
            }, trigger: 'blur'
          },
        ],
      }
    };
  },
  created() {
    this.userRoleId = zzSessionStorage.getItem('userId')
  },
  computed: {
    roles() {
      return this.$store.state.user.roles
    },
    hasRole() {
      return this.roles && this.roles.length > 1
    },
    saveDisabled() {
      return this.userRoleId === zzSessionStorage.getItem('userId')
    },
  },
  methods: {
    // 切换角色
    toggleRole() {
      if (
        this.userRoleId === zzSessionStorage.getItem('userId') ||
        this.toggleRoleLoading
      )
        return false
      this.toggleRoleLoading = true
      this.$store
        .dispatch('user/loginByRole', { userRoleId: this.userRoleId })
        .then((res) => {
          zzSessionStorage.removeItem('lastWorkbench')
          window.location.reload()
        })
        .catch(() => {
          this.toggleRoleLoading = false
        })
    },
    // 修改校验码
    async setNewUserCheckCode() {
      try {
        let validate = await this.$refs.userForm.validate()
        if (!validate) return false
        let res = await SetNewCheckCode(this.userForm.CheckCode);
        if (res.IsSuccess) {
          this.userForm.CheckCode = "";
          this.$message.success(
            this.$t("trials:trials-myinfo:message:updateSuccessfully")
          );
          this.$emit("getUserInfo");
        }
      } catch (err) {
        console.log(err);
      }
    },
    async setNewEmail() {
      let validate = await this.$refs.userForm.validate()
      if (!validate) return false
      setNewEmail(this.userForm.EMail, this.userForm.VerificationCode).then(
        () => {
          this.userForm.EMail = "";
          this.userForm.VerificationCode = "";
          this.$message.success(
            this.$t("trials:trials-myinfo:message:updateSuccessfully")
          );
          this.$emit("getUserInfo");
        }
      );
    },
    async setNewUserName() {
      try {
        let validate = await this.$refs.userForm.validate()
        if (!validate) return false
        let confirm = await this.$confirm(
          this.$t("trials:trials-myInfo:confirmMessage:updateUserName"),
          {
            type: "warning",
            distinguishCancelAndClose: true,
            confirmButtonText: this.$t("common:button:confirm"),
            cancelButtonText: this.$t("common:button:cancel"),
          }
        );
        if (confirm !== "confirm") return;
        let res = await setNewUserName(this.userForm.UserName);
        if (res.IsSuccess) {
          this.userForm.UserName = "";
          this.$message.success(
            this.$t("trials:trials-myinfo:message:updateSuccessfully")
          );
          this.$emit("getUserInfo");
          removeToken();
          this.logout();
        }
      } catch (err) {
        console.log(err);
      }
    },
    async setNewPhone() {
      let validate = await this.$refs.userForm.validate()
      if (!validate) return false
      setNewPhone(this.userForm.Phone).then(() => {
        this.userForm.Phone = "";
        this.$message.success(
          this.$t("trials:trials-myinfo:message:updateSuccessfully")
        );
        this.$emit("getUserInfo");
      });
    },
    handleEmailChange() {
      var reg =
        /^[A-Za-z0-9]+([_\.][A-Za-z0-9]+)*@([A-Za-z0-9\-]+\.)+[A-Za-z]{2,6}$/;
      if (this.userForm.EMail && reg.test(this.userForm.EMail)) {
        this.sendDisabled = false;
      } else {
        this.sendDisabled = true;
      }
    },
    sendVerificationCode() {
      sendVerificationCode(this.userForm.EMail).then(() => {
        this.settime(this);
        // 发送成功
        this.$message.success(
          this.$t("trials:trials-myinfo:message:sendSuccessfully")
        );
      });
    },
    settime(obj) {
      if (countdown === 0) {
        obj.sendDisabled = false;
        obj.sendTitle = this.$t("trials:trials-myinfo:button:getVCode"); // '获取验证码'
        countdown = 60;
        clearTimeout(timer);
        return;
      } else {
        obj.sendDisabled = true;
        obj.sendTitle = `${this.$t(
          "trials:trials-myinfo:button:wait"
        )}(${countdown}s)`;
        countdown--;
        // eslint-disable-next-line no-self-assign
        countdown = countdown;
        timer = setTimeout(function () {
          obj.settime(obj);
        }, 1000);
      }
    },
    async logout() {
      /* eslint-disable */
      var loginType = zzSessionStorage.getItem("loginType");
      await this.$store.dispatch("user/logout");
      if (loginType) {
        this.$router.push(`/login?loginType=${loginType}`);
      } else {
        this.$router.push(`/login`);
      }
      this.$i18n.locale = "zh";
      this.setLanguage("zh");
      this.$updateDictionary();
    },
  },
};
</script>