<template>
  <div class="question-login-wrapper">
    <div class="box-wrapper">
      <h2 style="text-align:center;">
        <!-- 中心调研表 -->
        {{ $t('trials:researchForm:title:question') }}
        <!-- <TopLang style="position: fixed;top: 40px;right: 40px" /> -->
      </h2>
      <el-card shadow="hover">
        <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:trialId')">
            <el-input v-model="form.TrialCode" disabled />
          </el-form-item>
          <!-- 试验方案号 -->
          <el-form-item :label="$t('trials:researchForm:form:researchNo')">
            <el-input v-model="form.ResearchProgramNo" disabled />
          </el-form-item>
          <!-- 试验名称 -->
          <el-form-item :label="$t('trials:researchForm:form:researchName')">
            <el-input v-model="form.ExperimentName" disabled />
          </el-form-item>
          <!-- 适应症类型 -->
          <el-form-item :label="$t('trials:researchForm:form:decleareType')">
            <el-input v-model="form.IndicationType" disabled />
          </el-form-item>
          <!-- 中心名称 -->
          <el-form-item :label="$t('trials:researchForm:form:siteName')" prop="TrialSiteId">
            <el-select v-model="form.TrialSiteId" filterable style="width:100%;" @change="handleSiteChange"
              :disabled="isUpload">
              <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" :label="$t('trials:researchForm:form:siteId')">
            <el-input v-model="form.TrialSiteCode" disabled />
          </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" :disabled="isUpload" />
          </el-form-item>
          <!-- 联系邮箱 -->
          <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')" required>
            <el-col style="width: calc(100% - 130px)">
              <el-form-item prop="VerificationCode">
                <el-input v-model="form.VerificationCode" autocomplete="new-password" />
              </el-form-item>
            </el-col>
            <el-col style="width: 120px;margin-left: 10px">
              <el-button size="small" class="codeBtn" style="width:100%;"
                :disabled="sendDisabled || !form.EmailOrPhone || count > 0" @click="handleSendCode">{{
                  this.$t('trials:researchForm:button:send') }} {{ sendTitle ? `${sendTitle}` : null }}</el-button>
            </el-col>
          </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 { getUserMenuTree, getUserPermissions } from '@/api/user'
import store from '@/store'
import TopLang from './topLang'
import { mapGetters, mapMutations } from 'vuex'

export default {
  components: { TopLang },
  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: '',
        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,
      isUpload: false
    }
  },
  computed: {
    ...mapGetters([
      'asyncRoutes',
      'routes',
      'language'
    ])
  },
  mounted() {
    this.$i18n.locale = this.$route.query.lang
    this.setLanguage(this.$route.query.lang)
    this.$updateDictionary()
    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) this.form.EmailOrPhone = email
    }
  },
  methods: {
    ...mapMutations({ setLanguage: 'lang/setLanguage' }),
    // 初始化页面
    async initPage() {
      this.loading = true
      getTrialSurveyInitInfo(this.trialId).then(res => {
        const { Result } = res
        this.siteOptions = Result.TrialSiteSelectList
        Object.keys(this.form).forEach(key => {
          if (Result.hasOwnProperty(key)) {
            this.form[key] = Result[key]
          }
        })
        if (this.isUpload) {
          this.handleSiteChange(this.form.TrialSiteId)
        }
        this.loading = false
      }).catch(() => { this.loading = false })
    },
    // 提交
    onSubmit() {
      this.$refs['resetForm'].validate(valid => {
        if (valid) {
          // 登陆成功并跳转
          this.loading = true
          // this.sendDisabled = 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
          }
          verifySendCode(param).then(async res => {
            zzSessionStorage.clear()
            this.$i18n.locale = this.$route.query.lang
            this.setLanguage(this.$route.query.lang)
            store.dispatch('user/setToken', res.Result.Token)
            zzSessionStorage.setItem('TokenKey', res.Result.Token)
            zzSessionStorage.setItem('userId', res.Result.UserRoleId);
            zzSessionStorage.setItem('identityUserId', res.Result.IdentityUserId);
            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}` })
            this.loading = false
          }).catch(() => {
            this.loading = false
            this.sendDisabled = false
          })
        } else {
          return 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
      }
    },
    // 发送验证码
    handleSendCode() {
      // this.sendDisabled = true
      this.loading = true
      const param = {
        Email: this.form.EmailOrPhone,
        TrialId: this.trialId
      }
      sendVerifyCode(param).then(res => {
        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(() => {
        // this.sendDisabled = false
        this.loading = 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 ? this.sendDisabled = false : ''
      // } else {
      //   !this.sendDisabled ? 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.sendTitle = `(${this.count}s)`
            this.count--
            // this.sendDisabled = true
          } else {
            this.sendDisabled = false
            this.sendTitle = ''
            clearInterval(this.timer)
            this.timer = null
          }
        }, 1000)
      }
    },
    onCancel() {
      this.$refs['resetForm'].resetFields()
    }
  }
}
</script>
<style lang="scss" scoped>
.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;
}

.question-login-wrapper {
  padding: 20px;

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