<template>
  <el-form v-if="isShow" ref="researchBSForm" size="small" :model="form" :rules="rules" style="width:80%">
    <!-- 项目编号 -->
    <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%;"
        :disabled="!(state === 0 && userTypeEnumInt === 0) || isHistory"
        @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" :label="$t('trials:researchForm:form:siteId')">
      <el-input v-model="form.TrialSiteCode" disabled />
    </el-form-item>
    <!-- 联系人 -->
    <el-form-item :label="$t('trials:researchForm:form:contactor')" prop="UserName">
      <el-input v-model="form.UserName" :disabled="!(state === 0 && userTypeEnumInt === 0) || isHistory" />
    </el-form-item>
    <!-- 联系电话 -->
    <el-form-item
      :label="$t('trials:researchForm:form:contactorPhone')"
      prop="Phone"
    >
      <el-input v-model="form.Phone" :disabled="!(state === 0 && userTypeEnumInt === 0) || isHistory" />
    </el-form-item>
    <!-- 联系邮箱 -->
    <el-form-item :label="$t('trials:researchForm:form:contactorEmail')">
      <el-input v-model="form.Email" disabled />
    </el-form-item>

    <!-- <el-divider /> -->
    <!-- 平均刻盘周期（天） -->
    <el-form-item v-if="!notShowFieldList.includes('AverageEngravingCycle')" :label="$t('trials:researchForm:form:engravingCycle')">
      <el-input-number v-model="form.AverageEngravingCycle" :disabled="!(state === 0 && userTypeEnumInt === 0) || isHistory" controls-position="right" :min="0" />
    </el-form-item>
    <!-- 请确认参与本项目影像采集的影像技师具备对应的资质（如：“技师证”，对应设备的“大型设备上岗证”） -->
    <el-form-item v-if="!notShowFieldList.includes('IsConfirmImagingTechnologist')" :label="$t('trials:researchForm:form:isQualified')">
      <el-radio-group v-model="form.IsConfirmImagingTechnologist" :disabled="!(state === 0 && userTypeEnumInt === 0) || isHistory">
        <el-radio
          v-for="item of $d.YesOrNo"
          :key="`IsConfirmImagingTechnologist${item.value}`"
          :label="item.value"
        >{{ item.label }}</el-radio>
      </el-radio-group>
    </el-form-item>
    <!-- 原因 -->
    <el-form-item
      v-if="!notShowFieldList.includes('NotConfirmReson') && form.IsConfirmImagingTechnologist === false"
      :label="$t('trials:researchForm:form:notQualifiedReason')"
    >
      <el-input
        v-model="form.NotConfirmReson"
        type="textarea"
        :autosize="{ minRows: 2, maxRows: 4}"
        :disabled="!(state === 0 && userTypeEnumInt === 0) || isHistory"
      />
    </el-form-item>
    <!-- 研究单位疗效评估人员类型 -->
    <el-form-item v-if="!notShowFieldList.includes('EfficacyEvaluatorType')" :label="$t('trials:researchForm:form:staffType')">
      <el-radio-group v-model="form.EfficacyEvaluatorType" :disabled="!(state === 0 && userTypeEnumInt === 0)|| isHistory">
        <el-radio v-for="item of $d.EfficacyEvaluatorType" :key="`EfficacyEvaluatorType${item.value}`" :label="item.value">{{ item.label }}</el-radio>
      </el-radio-group>
    </el-form-item>
    <!-- 是否严格按照研究单位影像手册参数完成图像采集 -->
    <el-form-item v-if="!notShowFieldList.includes('IsFollowStudyParameters')">
      <span slot="label" v-html="$t('trials:researchForm:form:isFollowStudyParam')" />
      <el-radio-group v-model="form.IsFollowStudyParameters" :disabled="!(state === 0 && userTypeEnumInt === 0) || isHistory">
        <el-radio v-for="item of $d.YesOrNo" :key="`IsFollowStudyParameters${item.value}`" :label="item.value">{{ item.label }}</el-radio>
      </el-radio-group>
    </el-form-item>
    <!-- 不能严格按照研究单位影像手册参数采集图像原因 -->
    <el-form-item
      v-if="!notShowFieldList.includes('NotFollowReson') && !form.IsFollowStudyParameters"
    >
      <span slot="label" v-html="$t('trials:researchForm:form:notFollowStudyParam')" />
      <el-input
        v-model="form.NotFollowReson"
        type="textarea"
        :autosize="{ minRows: 2, maxRows: 4}"
        :disabled="!(state === 0 && userTypeEnumInt === 0) || isHistory"
      />
    </el-form-item>
    <el-form-item>
      <!-- 保存 -->
      <el-button
        v-if="state === 0 && userTypeEnumInt === 0 && !isHistory"
        type="primary"
        :loading="btnLoading"
        size="small"
        @click="handleSave(false)"
      >
        {{ $t('common:button:save') }}
      </el-button>
    </el-form-item>
  </el-form>
</template>
<script>
import { getTrialSiteSelect } from '@/api/trials'
import { addOrUpdateTrialSiteSurvey } from '@/api/research'
export default {
  name: 'QuestionForm',
  props: {
    isHistory: {
      type: Boolean,
      default: false
    }
  },
  data() {
    var checkPhone = (rule, value, callback) => {
      console.log(value)
      // const phoneReg = /^1[3|4|5|7|8][0-9]{9}$/
      const phoneReg = /^[0-9]+$/
      if (!value) {
        callback(new Error(this.$t('trials:researchForm:formRule:specify')))
      } else {
        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)
      }
    }
    return {
      form: {
        Id: '',
        Sponsor: '', // 申办方
        ResearchProgramNo: '', // 方案号
        ExperimentName: '',
        TrialCode: '', // 项目编号
        TrialSiteCode: '',
        TrialSiteAliasName: '',
        IndicationType: '', // 适应症
        TrialSiteId: '', // 研究单位名称
        UserName: '', // 联系人
        Phone: '', // 联系人电话
        Email: '', // 联系人邮箱
        AverageEngravingCycle: '',
        IsConfirmImagingTechnologist: '',
        NotConfirmReson: '',
        EfficacyEvaluatorType: '',
        IsFollowStudyParameters: '',
        NotFollowReson: ''
      },
      rules: {
        TrialSiteId: [
          { required: true, message: this.$t('trials:researchForm:formRule:specify'), trigger: 'blur' }
        ],
        UserName: [
          { required: true, validator: (rule, value, callback) => { !value ? callback(new Error(this.$t('trials:researchForm:formRule:specify'))) : callback() }, trigger: 'blur' },
          { min: 0, max: 50, message: this.$t('trials:researchForm:formRule:maxLength'), trigger: ['blur', 'change'] }
        ],
        Phone: [
          { required: true, validator: checkPhone, trigger: 'blur' }
        ]
      },
      siteOptions: [],
      btnLoading: false,
      state: null,
      userTypeEnumInt: zzSessionStorage.getItem('userTypeEnumInt') * 1,
      isShow: false,
      notShowFieldList: []
    }
  },
  methods: {
    // 保存基本信息
    handleSave(isAutoCommit) {
      return new Promise((resolve, reject) => {
        this.$refs['researchBSForm'].validate(valid => {
          if (valid) {
            this.btnLoading = true
            const param = {
              id: this.form.Id,
              trialId: this.$route.query.trialId,
              trialSiteId: this.form.TrialSiteId,
              userName: this.form.UserName,
              phone: this.form.Phone,
              email: this.form.Email,
              averageEngravingCycle: this.form.AverageEngravingCycle,
              isConfirmImagingTechnologist: this.form.IsConfirmImagingTechnologist,
              notConfirmReson: this.form.NotConfirmReson,
              efficacyEvaluatorType: this.form.EfficacyEvaluatorType,
              isFollowStudyParameters: this.form.IsFollowStudyParameters,
              notFollowReson: this.form.NotFollowReson
            }
            addOrUpdateTrialSiteSurvey(param).then(res => {
              this.btnLoading = false
              if (res.IsSuccess && !isAutoCommit) {
                this.$message.success(this.$t('common:message:savedSuccessfully'))
              }
              resolve(true)
            }).catch(() => {
              this.btnLoading = false
              reject(false)
            })
          } else {
            if (isAutoCommit) {
              this.$message.error(this.$t('trials:researchForm:button:msg1'))
            }
            resolve(false)
          }
        })
      })
    },

    // 初始化
    async initForm(trialInfo, trialSiteSurvey, notShowFieldList) {
      // 获取项目下的site
      const { Result } = await getTrialSiteSelect(this.$route.query.trialId)
      this.siteOptions = Result
      this.form.Id = trialSiteSurvey.Id
      this.form.Sponsor = trialInfo.Sponsor // 申办方
      this.form.ResearchProgramNo = trialInfo.ResearchProgramNo // 方案号
      this.form.ExperimentName = trialInfo.ExperimentName
      this.form.TrialCode = trialInfo.TrialCode // 项目编号
      this.form.TrialSiteCode = trialSiteSurvey.TrialSiteCode
      this.form.TrialSiteAliasName = trialSiteSurvey.TrialSiteAliasName // 项目别称
      this.form.IndicationType = trialInfo.IndicationType // 适应症
      this.form.TrialSiteId = trialSiteSurvey.TrialSiteId
      this.form.UserName = trialSiteSurvey.UserName // 联系人
      this.form.Phone = trialSiteSurvey.Phone // 联系人电话
      this.form.Email = trialSiteSurvey.Email // 联系人邮箱
      this.form.AverageEngravingCycle = trialSiteSurvey.AverageEngravingCycle
      this.form.IsConfirmImagingTechnologist = trialSiteSurvey.IsConfirmImagingTechnologist
      this.form.NotConfirmReson = trialSiteSurvey.NotConfirmReson
      this.form.EfficacyEvaluatorType = trialSiteSurvey.EfficacyEvaluatorType
      this.form.IsFollowStudyParameters = trialSiteSurvey.IsFollowStudyParameters
      this.form.NotFollowReson = trialSiteSurvey.NotFollowReson
      this.state = trialSiteSurvey.State
      this.isShow = true
      if (!notShowFieldList) return
      this.notShowFieldList = notShowFieldList
    },
    handleSiteChange(val) {
      var selected = this.siteOptions.find(item => item.TrialSiteId === val)
      if (selected) {
        this.form.TrialSiteCode = selected.TrialSiteCode
      }
    }
  }
}
</script>
