<template>
  <div class="question-login-wrapper">
    <div class="box-wrapper">
      <h2 style="text-align: center">
        <!-- 中心调研表 -->
        <!-- 独立阅片人信息填写 -->
        {{ $t('trials:researchForm:form:title') }}
      </h2>
      <el-card shadow="hover" style="padding-top: 40px">
        <el-form ref="resetForm" v-loading="loading" :model="form" label-width="150px"
          style="width: 80%; margin: 0 auto" :rules="rules" class="demo-ruleForm" size="small">
          <!-- 联系邮箱 -->
          <el-form-item :label="$t('trials:researchForm:form:contactorEmail')" prop="EmailOrPhone">
            <el-input v-model="form.EmailOrPhone" autocomplete="new-password" @change="handleEmailChange" />
          </el-form-item>
          <!-- 验证码 -->
          <el-form-item :label="$t('trials:researchForm:form:verifyCode')" prop="VerificationCode">
            <div style="display: flex;;justify-content: space-between;">
              <el-input v-model="form.VerificationCode" autocomplete="new-password" />
              <el-button size="small" style="margin-left: 10px;" :disabled="sendDisabled" class="codeBtn"
                @click="handleSendCode">{{ this.$t('trials:researchForm:button:send')
                }}{{ count || count === 0 ? `(${count}s)` : '' }}</el-button>
            </div>
          </el-form-item>
          <el-form-item>
            <!-- 取消 -->
            <el-button size="small" :disabled="btnLoading" @click="onCancel">
              {{ $t('common:button:cancel') }}
            </el-button>
            <!-- 提交 -->
            <el-button size="small" type="primary" :loading="btnLoading" @click="onSubmit">
              {{ $t('common:button:submit') }}
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>
<script>
import {
  sendVerifyCode,
  verifySendCode,
  getTrialSurveyInitInfo,
} from '@/api/research'
import { verifyEmialGetDoctorInfo, sendEmialVerifyCode } from '@/api/reviewers'
import { login, getUserMenuTree, getUserPermissions } from '@/api/user'
import store from '@/store'
import { mapMutations } from 'vuex'
export default {
  data() {
    var checkPhone = (rule, value, callback) => {
      const phoneReg = /^1[3|4|5|7|8][0-9]{9}$/
      if (!value) {
        return callback(
          new Error(this.$t('trials:researchForm:formRule:specify'))
        )
      }
      setTimeout(() => {
        if (!Number.isInteger(+value)) {
          callback(new Error(this.$t('trials:researchForm:formRule:phone')))
        } else {
          if (phoneReg.test(value)) {
            callback()
          } else {
            callback(new Error(this.$t('trials:researchForm:formRule:phone')))
          }
        }
      }, 100)
    }
    var validateEmail = (rule, value, callback) => {
      if (value === '') {
        callback(new Error(this.$t('trials:researchForm:formRule:specify')))
      } else {
        var reg =
          /^[A-Za-z0-9]+([_\.][A-Za-z0-9]+)*@([A-Za-z0-9\-]+\.)+[A-Za-z]{2,6}$/
        if (this.$reg().EmailRegexStr) {
          reg = new RegExp(this.$reg().EmailRegexStr)
        }
        if (this.form.EmailOrPhone && reg.test(this.form.EmailOrPhone)) {
          this.sendDisabled = false
          callback()
        } else {
          callback(new Error(this.$t('trials:researchForm:formRule:email')))
          this.sendDisabled = true
        }
      }
    }
    var validateReplaceEmail = (rule, value, callback) => {
      if (value === '') {
        callback(new Error(this.$t('trials:researchForm:formRule:specify')))
      } else {
        var reg =
          /^[A-Za-z0-9]+([_\.][A-Za-z0-9]+)*@([A-Za-z0-9\-]+\.)+[A-Za-z]{2,6}$/
        if (this.$reg().EmailRegexStr) {
          reg = new RegExp(this.$reg().EmailRegexStr)
        }
        if (
          this.form.ReplaceUserEmailOrPhone &&
          reg.test(this.form.ReplaceUserEmailOrPhone)
        ) {
          callback()
        } else {
          callback(new Error(this.$t('trials:researchForm:formRule:email')))
        }
      }
    }
    return {
      trialId: '',
      form: {
        Sponsor: null, // 申办方
        ResearchProgramNo: null, // 方案号
        TrialCode: null, // 项目编号
        IndicationType: null, // 适应症
        ExperimentName: '',
        SiteId: null, // 研究单位名称
        UserName: null, // 联系人
        Phone: null, // 联系人电话
        EmailOrPhone: '',
        TrialSiteCode: '',
        IsUpdate: false,
        ReplaceUserEmailOrPhone: '',
        VerificationCode: '',
      },
      rules: {
        SiteId: [
          {
            required: true,
            message: this.$t('trials:researchForm:formRule:specify'),
            trigger: ['blur'],
          },
        ],
        UserName: [
          {
            required: true,
            message: this.$t('trials:researchForm:formRule:specify'),
            trigger: ['blur'],
          },
          {
            min: 0,
            max: 50,
            message: this.$t('trials:researchForm:formRule:maxLength'),
            trigger: 'blur',
          },
        ],
        Phone: [{ required: true, validator: checkPhone, trigger: ['blur'] }],
        EmailOrPhone: [
          {
            required: true,
            validator: validateEmail,
            trigger: ['blur', 'change'],
          },
        ],
        ReplaceUserEmailOrPhone: [
          {
            required: true,
            validator: validateReplaceEmail,
            trigger: ['blur'],
          },
        ],
        VerificationCode: [
          {
            required: true,
            message: this.$t('trials:researchForm:formRule:specify'),
            trigger: ['blur'],
          },
        ],
      },
      siteOptions: [],
      loading: false,
      sendDisabled: true,
      btnLoading: false,
      sendTitle: this.$t('trials:researchForm:button:send'),
      count: '',
      timer: null,
      isHaveSiteSurveyRecord: false,
    }
  },
  created() {
    this.$i18n.locale = this.$route.query.lang
    this.setLanguage(this.$route.query.lang)
  },
  mounted() { },
  methods: {
    ...mapMutations({ setLanguage: 'lang/setLanguage' }),
    // 提交
    onSubmit() {
      this.$refs['resetForm'].validate((valid) => {
        if (valid) {
          // 登陆成功并跳转
          this.btnLoading = true
          this.sendDisabled = true
          if (!this.form.IsUpdate) {
            this.form.ReplaceUserEmailOrPhone = ''
          }
          const param = {
            emailOrPhone: this.form.EmailOrPhone,
            verificationCode: this.form.VerificationCode,
          }
          if (this.$route.query.trialId) {
            param.TrialId = this.$route.query.trialId
          }
          verifyEmialGetDoctorInfo(param)
            .then(async (res) => {
              this.btnLoading = false
              zzSessionStorage.clear()
              store.dispatch('user/setToken', res.Result.Token)
              zzSessionStorage.setItem('TokenKey', res.Result.Token)
              var permissions = await getUserPermissions()
              var menuTree = await getUserMenuTree()
              store.dispatch('user/setTree', menuTree.Result)
              store.dispatch('user/setPermissions', permissions.Result)
              // this.$router.push({ path: `/researchForm?trialId=${this.trialId}&trialSiteSurveyId=${res.Result.TrialSiteSurveyId}` })
              if (this.$route.query.trialId) {
                this.$router.push({
                  path: `/curriculumVitae?Id=${res.Result.DoctorId ? res.Result.DoctorId : ''
                    }&tabActive=BasicInfo&ReviewStatus=${res.Result.ReviewStatus
                    }&trialId=${this.$route.query.trialId}&lang=${this.$route.query.lang
                    }`,
                })
              } else {
                this.$router.push({
                  path: `/curriculumVitae?Id=${res.Result.DoctorId ? res.Result.DoctorId : ''
                    }&tabActive=BasicInfo&ReviewStatus=${res.Result.ReviewStatus
                    }&lang=${this.$route.query.lang}`,
                })
              }
            })
            .catch(() => {
              this.btnLoading = false
              this.sendDisabled = false
            })
        } else {
          return false
        }
      })
    },
    // 发送验证码
    handleSendCode() {
      this.sendDisabled = true
      const param = {
        Email: this.form.EmailOrPhone,
      }
      sendEmialVerifyCode(param)
        .then((res) => {
          if (res.IsSuccess) {
            this.getCode()
          } else {
            this.$alert(res.ErrorMessage)
          }
        })
        .catch(() => {
          this.sendDisabled = false
        })
    },
    // 邮箱change事件
    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
      } else {
        this.sendDisabled = true
      }
    },
    getCode() {
      const TIME_COUNT = 60
      if (!this.timer) {
        this.count = TIME_COUNT
        this.sendDisabled = true
        this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= TIME_COUNT) {
            this.count--
            this.sendTitle = `${this.$t('trials:researchForm:button:send')}(${this.count
              }s)`
            this.sendDisabled = true
          } else {
            this.sendDisabled = false
            this.sendTitle = this.$t('trials:researchForm:button:send')
            clearInterval(this.timer)
            this.timer = null
            this.count = null
          }
        }, 1000)
      }
    },
    onCancel() {
      this.$refs['resetForm'].resetFields()
    },
  },
}
</script>
<style lang="scss" scoped>
.question-login-wrapper {
  padding: 20px;

  .box-wrapper {
    width: 50%;
    margin: 20px auto;
    padding: 10px;
    color: #303133;
  }
}

.codeBtn {
  color: #409EFF;
  border-color: #409EFF;
}

.codeBtn.is-disabled,
.codeBtn.is-disabled:focus,
.codeBtn.is-disabled:hover {
  color: #c0c4cc;
  cursor: not-allowed;
  background-image: none;
  background-color: #fff;
  border-color: #ebeef5;
}
</style>
