<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"
        :rules="rule"
        :model="userForm"
        ref="userFormRef"
      >
        <!-- 用户名 -->
        <el-form-item
          :label="$t('trials:trials-myinfo:form:userName')"
          style="margin-bottom: 5px"
        >
          <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:trials-myinfo:form:phone')"
          style="margin-bottom: 5px"
          prop="Phone"
        >
          <span>{{ user.Phone }}</span>
        </el-form-item>
        <el-form-item label="" style="position: relative" prop="Phone">
          <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"
          prop="EMail"
        >
          <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"
          prop="VerificationCode"
          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"
          prop="VerificationCode"
          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,
} 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: {},
      userRoleId: null,
      toggleRoleLoading: false,
      sendDisabled: true,
      sendTitle: this.$t('trials:trials-myinfo:button:getVCode'),
      rule: {
        UserName: [
          {
            validator: (rule, value, callback) => {
              if (!value) return callback()
              var lang = zzSessionStorage.getItem('lang')
                ? zzSessionStorage.getItem('lang')
                : 'zh'
              /* eslint-disable */
              var reg1 = /^[a-zA-Z0-9_]{4,16}$/ //密码必须是8位以上、必须含有字母、数字、特殊符号
              if (!reg1.test(value)) {
                callback(
                  lang === 'zh'
                    ? new Error(
                        '1）用户名字符长度最小为4个字符，最大为16个字符，只可使用字母、数字、下划线；'
                      )
                    : new Error(
                        '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
        })
    },
    setNewEmail() {
      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.userFormRef.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)
      }
    },
    setNewPhone() {
      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>
<style lang="scss" scoped>
.el-radio-group {
  margin-top: 12px;
}
.el-radio {
  width: 60px;
}
</style>