<template>
  <div class="research_login_m_content">
    <div v-if="IsExpired"></div>
    <div v-else-if="verify" class="LinkVerificationCode_content">
      <el-form ref="codeForm" v-loading="loading" label-position="top" label-width="120px" :model="codeForm"
        :rules="code_rules">
        <div class="basic_content">
          <!-- 项目编号 -->
          <el-form-item :label="$t('trials:researchForm:message:LinkVerificationCode')" prop="LinkVerificationCode">
            <el-input v-model="codeForm.LinkVerificationCode" autocomplete="new-password" />
          </el-form-item>
        </div>
      </el-form>
      <div class="submit_content">
        <el-button size="large" type="primary" @click="getLinkVerificationCodeIsEffective">
          {{ $t('common:button:submit') }}
        </el-button>
      </div>
    </div>
    <template v-else>
      <div class="title">{{ $t('trials:researchForm:title:question') }}</div>
      <el-form ref="loginForm" v-loading="loading" label-position="left" label-width="120px" :model="form"
        :rules="rules">
        <div class="basic_content">
          <!-- 项目编号 -->
          <el-form-item :label="$t('trials:researchForm:form:trialId')">
            <span>{{ form.TrialCode }}</span>
          </el-form-item>
          <!-- 试验方案号 -->
          <el-form-item :label="$t('trials:researchForm:form:researchNo')">
            <span>{{ form.ResearchProgramNo }}</span>
          </el-form-item>
          <!-- 试验名称 -->
          <el-form-item :label="$t('trials:researchForm:form:researchName')">
            <span>{{ form.ExperimentName }}</span>
          </el-form-item>
          <!-- 适应症类型 -->
          <el-form-item :label="$t('trials:researchForm:form:decleareType')">
            <span>{{ form.IndicationType }}</span>
          </el-form-item>
        </div>
        <div class="login_content">
          <el-form-item :label="$t('trials:researchForm:form:siteName')" prop="TrialSiteId">
            <el-select v-model="form.TrialSiteId" filterable style="width:100%;" @change="handleSiteChange">
              <el-option v-for="(item, index) of siteOptions" :key="index" :label="item.TrialSiteAliasName"
                :value="item.TrialSiteId" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="form.TrialSiteId && isHaveSiteSurveyRecord" label="" style="text-align:right;">
            <!-- 更新调研表 -->
            <el-link v-if="!form.IsUpdate" type="primary" @click="form.IsUpdate = true">
              {{ $t('trials:researchForm:button:updateQsForm') }}
            </el-link>
            <!-- 取消更新调研表 -->
            <el-link v-else type="primary" @click="form.IsUpdate = false; form.ReplaceUserEmailOrPhone = ''">
              {{ $t('trials:researchForm:button:cancelUpdateQsForm') }}
            </el-link>
          </el-form-item>

          <!-- 原调研表填写人邮箱 -->
          <el-form-item v-if="form.IsUpdate" :label="$t('trials:researchForm:form:originalEmail')"
            prop="ReplaceUserEmailOrPhone">
            <el-input v-model="form.ReplaceUserEmailOrPhone" autocomplete="new-password" />
          </el-form-item>
          <!-- 联系邮箱 -->
          <el-form-item :label="$t('trials:researchForm:form:contactorEmail')" prop="EmailOrPhone">
            <el-input v-model="form.EmailOrPhone" autocomplete="new-password" />
          </el-form-item>
          <el-form-item :label="$t('trials:researchForm:form:verifyCode')">
            <div class="code_content">
              <el-input v-model="form.VerificationCode" autocomplete="new-password" />
              <el-button type="primary" :disabled="sendDisabled || !form.EmailOrPhone || count > 0"
                @click="handleSendCode">
                {{ this.$t('trials:researchForm:button:send') }} {{ sendTitle ? `${sendTitle}` : null }}
              </el-button>
            </div>
          </el-form-item>
          <div class="submit_content">
            <el-button size="large" type="primary" @click="onSubmit">
              {{ $t('common:button:submit') }}
            </el-button>
          </div>
        </div>
      </el-form>
    </template>
  </div>
</template>
<script>
import { sendVerifyCode, verifySendCode, getTrialSurveyInitInfo } from '@/api/research'
import { getUserMenuTree, getUserPermissions } from '@/api/user'
import store from '@/store'
import { mapGetters, mapMutations } from 'vuex'
import {
  getLinkLinkExpirationTime,
  getLinkVerificationCodeIsEffective
} from '@/api/trials'
export default {
  name: 'ResearchMobileLogin',
  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)) {
          callback()
        } else {
          callback(new Error(this.$t('trials:researchForm:formRule:email')))
        }
      }
    }
    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: '',
      IsExpired: true,
      verify: true,
      codeForm: {
        LinkVerificationCode: null,
      },
      code_rules: {
        LinkVerificationCode: [
          { required: true, message: this.$t('trials:researchForm:formRule:specify'), trigger: ['blur'] }
        ],
      },
      form: {
        Sponsor: null, // 申办方
        ResearchProgramNo: null, // 方案号
        TrialCode: null, // 项目编号
        IndicationType: null, // 适应症
        ExperimentName: '',
        TrialSiteId: null, // 研究单位名称
        UserName: null, // 联系人
        Phone: '', // 联系人电话
        EmailOrPhone: '',
        TrialSiteCode: '',
        IsUpdate: false,
        ReplaceUserEmailOrPhone: '',
        VerificationCode: ''
      },
      rules: {
        TrialSiteId: [
          { 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, validator: (rule, value, callback) => { !value ? callback(new Error(this.$t('trials:researchForm:formRule:specify'))) : callback() }, trigger: ['blur'] }]
      },
      siteOptions: [],
      loading: false,
      sendDisabled: false,
      btnLoading: false,
      sendTitle: '',
      count: '',
      timer: null,
      msg: '',
      lang: 'zh',
      isHaveSiteSurveyRecord: false
    }
  },
  computed: {
    ...mapGetters([
      'asyncRoutes',
      'routes',
      'language'
    ])
  },
  mounted() {
    let lang = this.$route.query.lang
    if (!lang) {
      const language = navigator.language
      lang = 'en'
      if (language.includes("zh")) {
        lang = 'zh'
      }
    }
    this.$i18n.locale = lang
    this.setLanguage(lang)
    this.$updateDictionary()
    this.getLinkTimeIsExpired()
  },
  methods: {
    ...mapMutations({ setLanguage: 'lang/setLanguage' }),
    async getLinkTimeIsExpired() {
      try {
        let data = {
          TrialId: this.$route.query.trialId,
        }
        let res = await getLinkLinkExpirationTime(data)
        if (res.IsSuccess) {
          if (res.Result.IsExpired) {
            return this.$router.replace('/link_expired')
            //    return this.$confirm(this.$t("trials:researchForm:confirm:linkIsExpired"), '', {
            //   type: 'warning'
            // })
            // return this.IsExpired = true
          }
          // this.customPrompt()
          this.IsExpired = false
        }
      } catch (err) {
        console.log(err)
      }
    },
    async getLinkVerificationCodeIsEffective() {
      try {
        let validate = await this.$refs.codeForm.validate()
        if (!validate) return false
        let data = {
          TrialId: this.$route.query.trialId,
          LinkVerificationCode: this.codeForm.LinkVerificationCode
        }
        let res = await getLinkVerificationCodeIsEffective(data)
        if (res.IsSuccess) {
          if (!res.Result.IsEffective) {
            return false
          }
          this.verify = false
          if (this.$route.query.trialId) {
            this.trialId = this.$route.query.trialId
            this.initPage()
          }
          if (this.$route.query.isUpload) {
            this.isUpload = true
            this.form.IsUpdate = true
            let { email, oldEMail, trialSiteId } = this.$route.query
            if (trialSiteId) this.form.TrialSiteId = trialSiteId
            if (oldEMail) this.form.ReplaceUserEmailOrPhone = oldEMail
            if (email && email !== 'null') {
              this.form.EmailOrPhone = email
            } else {
              this.form.EmailOrPhone = oldEMail
            }
            if ((email && email !== 'null') || (oldEMail && oldEMail !== 'null')) {
              this.isNeedUpload = false
            }
          }
        }
        return true
      } catch (err) {
        return false
        console.log(err)
      }
    },
    async customPrompt(name) {
      try {
        const that = this
        // 请输入标记名称
        let message = this.$t('trials:researchForm:message:LinkVerificationCode')
        const { value } = await this.$prompt(message, '', {
          showClose: false,
          cancelButtonText: this.$t('common:button:cancel'),
          confirmButtonText: this.$t('trials:researchForm:button:saveLinkCode'),
          showCancelButton: false,
          closeOnClickModal: false,
          closeOnPressEscape: false,
          inputValue: name,
          beforeClose: async (action, instance, done) => {
            if (action === 'confirm') {
              const value = instance.inputValue
              if (!value) {
                that.$message.error(this.$t('trials:researchForm:error:noValue'))
              } else {
                let flag = await this.getLinkVerificationCodeIsEffective(value)
                if (!flag) {
                  that.$message.error(this.$t('trials:researchForm:confirm:isEffective'))
                } else {
                  done()
                }
              }
            } else {
              done()
            }
          }
        })
        this.getLinkVerificationCodeIsEffective(value)
      } catch (err) {
        console.log(err)
        return null
      }
    },
    // 初始化页面
    async initPage() {
      try {
        this.loading = true
        const res = await getTrialSurveyInitInfo(this.trialId)
        this.loading = false
        if (res.IsSuccess) {
          this.siteOptions = res.Result.TrialSiteSelectList
        }
        Object.keys(this.form).forEach(key => {
          if (res.Result.hasOwnProperty(key)) {
            this.form[key] = res.Result[key]
          }
        })
      } catch (e) {
        this.loading = false
        console.log(e)
      }
    },
    // 提交
    async onSubmit() {
      const validate = await this.$refs.loginForm.validate()
      if (!validate) return
      try {
        this.loading = true
        if (!this.form.IsUpdate) {
          this.form.ReplaceUserEmailOrPhone = ''
        }
        const param = {
          trialSiteId: this.form.TrialSiteId,
          userName: this.form.UserName,
          phone: this.form.Phone,
          verificationType: 0,
          emailOrPhone: this.form.EmailOrPhone,
          verificationCode: this.form.VerificationCode,
          isUpdate: this.form.IsUpdate,
          replaceUserEmailOrPhone: this.form.ReplaceUserEmailOrPhone,
          trialId: this.trialId
        }
        const res = await verifySendCode(param)

        if (res.IsSuccess) {
          zzSessionStorage.clear()
          // this.$i18n.locale = this.$route.query.lang
          // this.setLanguage(this.$route.query.lang)
          let lang = this.$route.query.lang
          if (!lang) {
            const language = navigator.language
            lang = 'en'
            if (language.includes("zh")) {
              lang = 'zh'
            }
          }
          this.$i18n.locale = lang
          this.setLanguage(lang)
          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: `/researchDetail_m?trialId=${this.trialId}&trialSiteSurveyId=${res.Result.TrialSiteSurveyId}` })
          this.loading = false
        }
      } catch (e) {
        this.loading = false
        this.sendDisabled = false
      }
    },
    handleSiteChange(val) {
      this.isHaveSiteSurveyRecord = false
      var selected = this.siteOptions.find(item => item.TrialSiteId === val)
      if (selected) {
        this.form.TrialSiteCode = selected.TrialSiteCode
        this.isHaveSiteSurveyRecord = selected.IsHaveSiteSurveyRecord
      }
    },
    // 发送验证码
    async handleSendCode() {
      try {
        this.loading = true
        const param = {
          Email: this.form.EmailOrPhone,
          TrialId: this.trialId
        }
        const res = await sendVerifyCode(param)
        if (res.IsSuccess) {
          this.getCode()
          this.loading = false
          const msg = this.$t('trials:researchForm:tip:sendCode').replace('xxx', this.form.EmailOrPhone)
          this.$message.success(msg)
        } else {
          this.$alert(res.ErrorMessage)
        }
      } catch (e) {
        this.loading = false
        console.log(e)
      }
    },
    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.sendTitle = `(${this.count}s)`
            this.count--
          } else {
            this.sendDisabled = false
            this.sendTitle = ''
            clearInterval(this.timer)
            this.timer = null
          }
        }, 1000)
      }
    },
    onCancel() {
      this.$refs['loginForm'].resetFields()
    }
  }
}
</script>
<style lang="scss" scoped>
.research_login_m_content {
  background-color: #f5f7fa;

  .title {
    margin-bottom: 5px;
    line-height: 80px;
    font-size: 28px;
    font-weight: bold;
    text-align: center;
    background: #fff;
  }

  .basic_content {
    padding: 0 20px;
    background: #fff;
  }

  .login_content {
    padding: 5px 20px;
    margin-top: 5px;
    background: #fff;

    ::v-deep .el-form-item {
      padding-bottom: 20px;
    }
  }

  .code_content {
    display: flex;
    flex-direction: row;
    justify-content: flex-start;

    .el-input {
      margin-right: 10px;
    }
  }

  .submit_content {
    margin-top: 20px;
    text-align: center;
  }

  ::v-deep .el-form-item {
    margin-bottom: 0px;
    padding-top: 5px;
    border-bottom: 1px solid #f5f7fa;

    .el-form-item__content {
      color: #82848a;
    }
  }


}

.LinkVerificationCode_content {
  position: fixed;
  top: 40%;
  bottom: 40%;
  right: 0;
  left: 0;
}
</style>
