<template>
  <div class="trial-myinfo">
    <div class="trial-myinfo-left">
      <div class="trial-myinfo-left-top">
        <div class="trial-myinfo-head">
          <!-- 个人头像 -->
          {{ $t('trials:trials-myinfo:title:avater') }}
        </div>
        <div class="trial-myinfo-body">
          <div>
            {{ user.LastName }}
          </div>
        </div>
      </div>
      <div class="trial-myinfo-left-bottom">
        <div class="trial-myinfo-head">
          <!-- 用户基本信息 -->
          {{ $t('trials:trials-myinfo:title:basicInfo') }}
        </div>
        <el-form ref="userForm" label-position="right" :model="user" :rules="userFormRules" label-width="120px">
          <el-form-item v-if="user.Code" label="ID: " prop="Code">
            <el-input :maxLength="$inputMax" v-model="user.Code" disabled />
          </el-form-item>
          <!-- 姓 -->
          <el-form-item :disabled="user.UserTypeEnum === 8" :label="$t('trials:trials-myinfo:form:surname')" prop="LastName">
            <el-input :maxLength="50" v-model="user.LastName" :placeholder="$t('trials:trials-myinfo:form:surname')"/>
          </el-form-item>
          <!-- 名 -->
          <el-form-item :disabled="user.UserTypeEnum === 8" :label="$t('trials:trials-myinfo:form:givenname')" prop="FirstName">
            <el-input :maxLength="50" v-model="user.FirstName" :placeholder="$t('trials:trials-myinfo:form:givenname')"/>
          </el-form-item>
          <!-- 性别 -->
          <el-form-item :label="$t('trials:trials-myinfo:form:gender')" prop="Sex" style="margin-right:40px;">
            <el-radio-group v-model="user.Sex">
              <el-radio v-for="item of $d.Sex" :label="item.value">{{ item.label }}</el-radio>
<!--              <el-radio :label="1">Male</el-radio>-->
<!--              <el-radio :label="0">Female</el-radio>-->
            </el-radio-group>
          </el-form-item>
          <!-- 单位 -->
          <el-form-item :label="$t('trials:trials-myinfo:form:organization')" prop="OrganizationName">
            <el-input :maxLength="$inputMax" v-model="user.OrganizationName" :placeholder="$t('trials:trials-myinfo:form:organization')"/>
          </el-form-item>
          <!-- 部门 -->
          <el-form-item :label="$t('trials:trials-myinfo:form:department')" prop="DepartmentName">
            <el-input :maxLength="$inputMax" v-model="user.DepartmentName" :placeholder="$t('trials:trials-myinfo:form:organization')"/>
          </el-form-item>
          <!-- 职位 -->
          <el-form-item :label="$t('trials:trials-myinfo:form:position')" prop="PositionName">
            <el-input :maxLength="$inputMax" v-model="user.PositionName" :placeholder="$t('trials:trials-myinfo:form:position')"/>
          </el-form-item>
        </el-form>
        <!-- 保存 -->
        <el-button
          class="trial-info-btn"
          type="primary"
          size="small"
          @click="handleSave"
        >
          {{ $t('trials:trials-myinfo:button:save') }}
        </el-button>
      </div>
    </div>
    <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 ref="userForm2" @submit.native.prevent label-position="right" label-width="150px" :model="userForm" :rules="userFormRules2">
          <!-- 用户名 -->
          <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 :maxLength="16" 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>
        <el-form ref="userForm4" @submit.native.prevent label-position="right" label-width="150px" :model="userForm" :rules="userFormRules4">
          <!-- 电话 -->
          <el-form-item :label="$t('trials:trials-myinfo:form:phone')" style="margin-bottom: 5px;">
            <span>{{ user.Phone }}</span>
          </el-form-item>
          <el-form-item label="" style="position: relative" prop="Phone">
            <el-input :maxLength="50" 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>
        <el-form ref="userForm3" @submit.native.prevent label-position="right" label-width="150px" :model="userForm" :rules="userFormRules3">
        <!-- 邮箱 -->
          <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: 20px;position: relative" prop="EMail">
            <el-input :maxLength="$inputMax" v-model="userForm.EMail" @input="handleEmailChange" :placeholder="$t('trials:trials-myinfo:form:email')"/>
            <el-button :loading="loading" 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">
            <el-input :maxLength="6" 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>
      </div>
      <div class="trial-myinfo-right-box">
        <div class="trial-myinfo-head">
          <!-- 修改密码 -->
          {{ $t('trials:trials-myinfo:title:updatePaasord') }}
        </div>
        <el-form ref="passwordForm" label-position="right" :model="password" :rules="passwordFormRules" label-width="150px">
          <!-- 旧密码 -->
          <el-form-item :label="$t('recompose:form:oldPassword')" prop="OldPassWord">
            <el-input :maxLength="32" v-model="password.OldPassWord" type="password" show-password auto-complete="new-password" :placeholder="$t('recompose:form:oldPassword')"/>
          </el-form-item>
          <!-- 新密码 -->
          <el-form-item class="my_new_pwd" :label="$t('recompose:form:newPassword')" prop="NewPassWord">
            <el-input :maxLength="32" v-model="password.NewPassWord" type="password" show-password auto-complete="new-password" :placeholder="$t('recompose:form:newPassword')"/>
          </el-form-item>
          <!-- 确认密码 -->
          <el-form-item class="my_new_pwd" :label="$t('recompose:form:confirmPassword')" prop="ConfirmPassWord">
            <el-input :maxLength="32" v-model="password.ConfirmPassWord" type="password" show-password auto-complete="new-password" :placeholder="$t('recompose:form:confirmPassword')"/>
          </el-form-item>
        </el-form>
        <el-button
          type="primary"
          size="small"
          class="trial-info-btn"
          @click="save"
        >
          {{ $t('trials:trials-myinfo:button:save') }}
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { getUserTypeList, getUser, updateUser, modifyPassword } from '@/api/admin.js'
import { sendVerificationCode, setNewEmail, setNewPhone, setNewUserName } from '@/api/system/user.js'
import md5 from 'js-md5'
var timer = ''
var countdown = 60
import store from '@/store'
import { mapGetters } from 'vuex'

export default {
  name: 'TrialsMyinfo',
  data() {
    var validateEmail = (rule, value, callback) => {
      var reg2 = /^[A-Za-z0-9]+([_\.][A-Za-z0-9]+)*@([A-Za-z0-9\-]+\.)+[A-Za-z]{2,6}$/
      if (!reg2.test(this.userForm.EMail)) {
        callback(new Error("邮箱格式不正确"))
      } else {
        callback();
      }
    }
    var validatePassword = (rule, value, callback) => {
      var lang = zzSessionStorage.getItem('lang')?zzSessionStorage.getItem('lang'):'zh'
      /* eslint-disable */
      var reg1 = /^[a-zA-Z0-9_]{4,16}$/; //密码必须是8位以上、必须含有字母、数字、特殊符号
      console.log(!reg1.test(value))
      if (!reg1.test(value)) {
        callback(lang==='zh' ? new Error("1）新建账号，用户名字符长度最小为4个字符，最大为16个字符，只可使用字母、数字、下划线；") : new Error('Passwords must have: 1) 8 - 32 characters; 2) At least 1 number; 3) At least 1 uppercase letter; 4) At least 1 lowercase letter; 5) At least 1 special character (~!-@#$%^&*_+?) '))
      } else {
        callback();
      }
    }
    return {
      loading: false,
      userTypeOptions: [],
      user: {},
      password: {},
      userForm: {},
      sendDisabled: true,
      sendTitle: this.$t('trials:trials-myinfo:button:getVCode'),
      userFormRules: {
        UserName: [{ required: true, message: this.$t('common:ruleMessage:specify'), trigger: 'blur' }],
        UserTypeId: [{ required: true, message: this.$t('common:ruleMessage:select'), trigger: ['blur', 'change'] }],
        IsZhiZhun: [{ required: true, message: this.$t('common:ruleMessage:select'), trigger: ['blur', 'change'] }],
        // OrganizationName: [{ required: true, message: this.$t('common:ruleMessage:specify'), trigger: 'blur' }],
        LastName: [{ required: true, message: this.$t('common:ruleMessage:specify'), trigger: 'blur' }, { max: 50, message: `${this.$t('common:ruleMessage:maxLength')} 50` }],
        FirstName: [{ required: true, message: this.$t('common:ruleMessage:specify'), trigger: 'blur' }, { max: 50, message: `${this.$t('common:ruleMessage:maxLength')} 50` }],
        Sex: [{ required: true, message: this.$t('common:ruleMessage:specify'), trigger: 'blur' }],
        Status: [{ required: true, message: this.$t('common:ruleMessage:specify'), trigger: 'blur' }]
      },
      userFormRules2: {
        UserName:[
          {
            required: true,
            trigger: ['blur'],
            validator: validatePassword
          },
        ]
      },
      userFormRules4: {
        Phone:[
          { max: 50, message: `${this.$t('common:ruleMessage:maxLength')} 20` }
        ]
      },
      userFormRules3: {
        EMail:[
          {
            required: true,
            trigger: ['change', 'blur'],
            validator: validateEmail
          },
        ]
      },
      passwordFormRules: {
        OldPassWord: [{ required: true, message: this.$t('common:ruleMessage:specify'), trigger: 'blur' }],
        NewPassWord: [
          { required: true, message: this.$t('common:ruleMessage:specify'), trigger: 'blur' },
          {
            required: true,
            trigger: 'blur',
            validator: this.$validatePassword
          },
        ],
        ConfirmPassWord: [
          { required: true, message: this.$t('common:ruleMessage:specify'), trigger: 'blur' },
          {
            required: true,
            trigger: 'blur',
            validator: this.$validatePassword
          },
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['userId', 'name'])
  },
  mounted() {
    this.getUserInfo()
    this.getUserTypeList()
  },
  methods: {
    handleSave() {
      this.$refs.userForm.validate(valid => {
        console.log(valid)
        if (valid) {
          this.isDisabled = true
          const selectedUserType = this.userTypeOptions.filter((item) => {
            return item.Id === this.user.UserTypeId
          })
          if (selectedUserType.length > 0) {
            this.user.userTypeEnum = selectedUserType[0].UserTypeEnum
          }
          if (this.user.Id) {
            updateUser(this.user).then(res => {
              this.isDisabled = false
              this.$message.success(this.$t('trials:trials-myinfo:message:updateSuccessfully'))
              this.getUserInfo()
            }).catch(() => { this.isDisabled = false })
          }
        }
      })
    },
    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() {
      this.loading = true
      sendVerificationCode(this.userForm.EMail).then(() => {
        this.settime(this)
        // 发送成功
        this.$message.success(this.$t('trials:trials-myinfo:message:sendSuccessfully'))
        this.loading = false
      }).catch(() => {this.loading = false})
    },
    save() {
      this.$refs.passwordForm.validate(valid => {
        if (valid) {
          if (this.password.NewPassWord !== this.password.ConfirmPassWord) {
            this.$message.error(this.$t('passwordReset:formRule:passwordsDiffer'))
            return
          }
          const param = {
            UserId: this.userId,
            NewPassWord: md5(this.password.NewPassWord),
            OldPassWord: md5(this.password.OldPassWord)
          }
          modifyPassword(param).then(res => {
            if (res.IsSuccess) {
              // 修改成功,请重新登录账号
              this.$message.success(this.$t('trials:trials-myinfo:message:modifyPWSuccessfully'))
              setTimeout(() => {
                this.logout()
              }, 1000)
            }
          })
        }
      })
    },
    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.getUserInfo()
      })
    },
    setNewUserName() {
      this.$refs.userForm2.validate(valid => {
        if (valid) {
          setNewUserName(this.userForm.UserName).then(() => {
            this.userForm.UserName = ''
            this.$message.success(this.$t('trials:trials-myinfo:message:updateSuccessfully'))
            this.getUserInfo()
          })
        }
      })
    },
    setNewPhone() {
      this.$refs.userForm4.validate(valid => {
        if (valid) {
          setNewPhone(this.userForm.Phone).then(() => {
            this.userForm.Phone = ''
            this.$message.success(this.$t('trials:trials-myinfo:message:updateSuccessfully'))
            this.getUserInfo()
          })
        }
      })
    },
    getUserInfo() {
      const loading = this.$loading({
        fullscreen: false,
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.07)'
      })
      getUser(this.userId).then(async res => {
        this.user = res.Result
        /* eslint-disable */
        zzSessionStorage.setItem('realName', this.user.RealName)
        await store.dispatch('user/updateInfo')
        loading.close()
      }).catch(() => { loading.close() })
    },
    settime(obj) {
      if (countdown === 0) {
        obj.sendDisabled = false
        this.handleEmailChange()
        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)
      }
    },
    getUserTypeList() {
      getUserTypeList().then(res => {
        if (res.IsSuccess) {
          this.userTypeOptions = res.Result
        }
      })
    },
    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`)
      }
    }
  }
}
</script>

<style lang="scss">
  .trial-myinfo{
    flex: 1;overflow: auto;display: flex;flex-direction: row;justify-content: space-around;
    .trial-myinfo-head{
      position: absolute;top: 40px;left: -10%;font-size: 14px;
    }
    .trial-myinfo-left{
      overflow: auto;
      background: #fff;width: calc(50% - 9px);margin: 6px 0;
      padding-bottom: 50px;
      .trial-myinfo-left-top{
        width: 70%;padding-top: 100px;position: relative;margin: 0 auto;margin-bottom: 10px;
        .trial-myinfo-body{
          width:160px;height:160px;border-radius: 50%;background: #00bca0;display: flex;justify-content: center;align-items: center;
          div{
            color:#fff;font-size: 30px;
          }
        }
      }
    }
    .saveBtn{
      position: absolute;right: -10px;top:2px;transform: translateX(100%)
    }
    .trial-info-btn{
      position: absolute;bottom: -60px;left: calc(100% + 10px);min-width: 97px;
    }
    .trial-myinfo-left-bottom{
      width: 70%;padding-top: 100px;position: relative;margin: 0 auto;
    }
    .trial-myinfo-right{
      overflow: auto;
      background: #fff;width: calc(50% - 9px);margin: 6px 0;
      padding-bottom: 50px;
      .sendCode {
        position: absolute;right: -10px;top: 50%;transform: translate(100%, -50%);
      }
      .trial-myinfo-right-box{
        width: 70%;padding-top: 100px;position: relative;margin: 0 auto;
      }
    }
  }
</style>
<style lang="scss" scoped>
>>>.is-error.my_new_pwd{
  margin-bottom: 40px;
}
</style>
