<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 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
              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
              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 :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
              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
              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
              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 label-position="right" label-width="180px">
          <!-- 用户名 -->
          <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:trials-myinfo:form:phone')"
            style="margin-bottom: 5px"
            prop="UserName"
          >
            <span>{{ user.Phone }}</span>
          </el-form-item>
          <el-form-item label="" style="position: relative" prop="UserName">
            <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="UserName"
          >
            <span>{{ user.EMail }}</span>
          </el-form-item>
          <el-form-item
            label=""
            style="margin-bottom: 10px; position: relative"
            prop="EMail"
          >
            <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"
          >
            <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>
      </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="180px"
        >
          <!-- 旧密码 -->
          <el-form-item
            :label="$t('recompose:form:oldPassword')"
            prop="OldPassWord"
          >
            <el-input
              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
              v-model="password.NewPassWord"
              type="password"
              show-password
              auto-complete="new-password"
              :placeholder="$t('recompose:form:newPassword')"
            />
          </el-form-item>
          <!-- 确认密码 -->
          <el-form-item
            :label="$t('recompose:form:confirmPassword')"
            prop="ConfirmPassWord"
          >
            <el-input
              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, mapMutations } from 'vuex'

export default {
  name: 'TrialsMyinfo',
  data() {
    return {
      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',
          },
        ],
      },
      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: {
    ...mapMutations({ setLanguage: 'lang/setLanguage' }),
    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.IsZhiZhun === true) {
          //   this.user.OrganizationName = 'ZhiZhun'
          // }
          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-Z]{2,}$/
      if (this.$reg().EmailRegexStr) {
        reg = new RegExp(this.$reg().EmailRegexStr)
      }
      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')
        )
      })
    },
    save() {
      this.$refs.passwordForm.validate((valid) => {
        if (valid) {
          if (this.password.NewPassWord !== this.password.ConfirmPassWord) {
            this.$alert(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() {
      setNewUserName(this.userForm.UserName).then(() => {
        this.$store
          .dispatch('user/changeUserName', this.userForm.UserName)
          .then((res) => {
            this.userForm.UserName = ''
            this.$message.success(
              this.$t('trials:trials-myinfo:message:updateSuccessfully')
            )
            this.getUserInfo()
          })
      })
    },
    setNewPhone() {
      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()
        .then(async (res) => {
          this.user = res.Result
          /* eslint-disable */
          zzSessionStorage.setItem('Name', this.user.FullName)
          await store.dispatch('user/updateInfo')
          loading.close()
        })
        .catch(() => {
          loading.close()
        })
    },
    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)
      }
    },
    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`)
      }
      //this.$i18n.locale = 'zh'
      //this.setLanguage('zh')
      this.$updateDictionary()
    },
  },
}
</script>

<style lang="scss" scoped>
.trial-myinfo {
  background: #f3f3f3;
  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: #428bca;
        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 scoped>
::v-deep .is-error.my_new_pwd {
  margin-bottom: 45px;
}
</style>
