<template>
  <div class="question-login-wrapper">
    <div class="box-wrapper">
      <h2 style="text-align:center;">
        <!-- 中心调研表 -->
        {{ $t('trials:researchForm:title:question') }}
      </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 :maxLength="$inputMax" v-model="form.TrialCode" disabled />
          </el-form-item>
          <!-- 试验方案号 -->
          <el-form-item :label="$t('trials:researchForm:form:researchNo')">
            <el-input :maxLength="$inputMax" v-model="form.ResearchProgramNo" disabled />
          </el-form-item>
          <!-- 试验名称 -->
          <el-form-item :label="$t('trials:researchForm:form:researchName')">
            <el-input :maxLength="$inputMax" v-model="form.ExperimentName" disabled />
          </el-form-item>
          <!-- 适应症类型 -->
          <el-form-item :label="$t('trials:researchForm:form:decleareType')">
            <el-input :maxLength="$inputMax" v-model="form.IndicationType" disabled />
          </el-form-item>
          <!-- 中心名称 -->
          <el-form-item :label="$t('trials:researchForm:form:siteName')" prop="SiteId">
            <el-select v-model="form.SiteId" filterable style="width:100%;" @change="handleSiteChange">
              <el-option
                v-for="(item,index) of siteOptions"
                :key="index"
                :label="item.TrialSiteAliasName"
                :value="item.SiteId"
              />
            </el-select>
          </el-form-item>
          <!-- 中心编号 -->
          <el-form-item v-if="form.SiteId" :label="$t('trials:researchForm:form:siteId')">
            <el-input :maxLength="$inputMax" v-model="form.TrialSiteCode" disabled />
          </el-form-item>
          <el-form-item v-if="form.SiteId && 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 :maxLength="$inputMax" v-model="form.ReplaceUserEmailOrPhone" autocomplete="new-password" />
          </el-form-item>
          <!-- 联系邮箱 -->
          <el-form-item :label="$t('trials:researchForm:form:contactorEmail')" prop="EmailOrPhone">
            <el-input :maxLength="$inputMax" v-model="form.EmailOrPhone" autocomplete="new-password" @change="handleEmailChange" />
          </el-form-item>
          <!-- 验证码 -->
          <el-form-item :label="$t('trials:researchForm:form:verifyCode')" required>
            <el-col :span="20">
              <el-form-item prop="VerificationCode">
                <el-input :maxLength="$inputMax" v-model="form.VerificationCode" autocomplete="new-password" />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-button
                size="small"
                type="primary"
                style="width:100%;"
                :disabled="sendDisabled"
                @click="handleSendCode"
              >{{ sendTitle }}</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 { login, getUserMenuTree, getUserPermissions } from '@/api/user'
import store from '@/store'
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.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.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
    }
  },
  mounted() {
    if (this.$route.query.trialId) {
      this.trialId = this.$route.query.trialId
      this.initPage()
    }
  },
  methods: {
    // 初始化页面
    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]
          }
        })
        this.loading = false
      }).catch(() => { this.loading = false })
    },
    // 提交
    onSubmit() {
      this.$refs['resetForm'].validate(valid => {
        if (valid) {
          // 登陆成功并跳转
          this.btnLoading = true
          this.sendDisabled = true
          if (!this.form.IsUpdate) {
            this.form.ReplaceUserEmailOrPhone = ''
          }
          const param = {
            siteId: this.form.SiteId,
            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 => {
            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}` })
          }).catch(() => {
            this.btnLoading = false
            this.sendDisabled = false
          })
        } else {
          return false
        }
      })
    },
    handleSiteChange(val) {
      this.isHaveSiteSurveyRecord = false
      var selected = this.siteOptions.find(item => item.SiteId === val)
      if (selected) {
        this.form.TrialSiteCode = selected.TrialSiteCode
        this.isHaveSiteSurveyRecord = selected.IsHaveSiteSurveyRecord
      }
    },
    // 发送验证码
    handleSendCode() {
      this.sendDisabled = true
      const param = {
        Email: this.form.EmailOrPhone,
        TrialId: this.trialId
      }
      sendVerifyCode(param).then(res => {
        if (res.IsSuccess) {
          this.getCode()
        } else {
          this.$message.error(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
          }
        }, 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;
  }
}
</style>
