<!-- eslint-disable -->
<template>
  <el-form
    ref="trialForm"
    v-loading="loading"
    label-width="250px"
    :rules="trialFormRules"
    class="demo-ruleForm trial-Form"
    :model="trialForm"
    label-position="right"
    :inline="true"
  >
    <el-row>
      <!-- 项目编号 -->
      <el-form-item v-if="trialForm.Id!== ''" :label="$t('trials:trials-list:form:trialId')">
        <el-input v-model="trialForm.TrialCode" disabled />
      </el-form-item>
      <!-- 项目类型 -->
      <el-form-item :label="$t('trials:trials-list:form:trialType')" prop="TrialType">
        <el-radio-group v-model="trialForm.TrialType " :disabled="trialForm.Id!== ''">
          <el-radio v-for="item of $d.TrialType" :disabled="isTestUser && (item.value === 1 || item.value === 2)" :key="item.id" :label="item.value">{{ item.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-row>
    <el-row>
      <!-- 试验名称 -->
      <el-form-item :label="$t('trials:trials-list:form:experimentName')" prop="ExperimentName">
        <el-input v-model="trialForm.ExperimentName" type="textarea" :autosize="{ minRows: 1, maxRows: 4}" />
      </el-form-item>
      <!-- 研究方案号 -->
      <el-form-item :label="$t('trials:trials-list:form:researchNumber')" prop="ResearchProgramNo">
        <el-input v-model="trialForm.ResearchProgramNo" />
      </el-form-item>
    </el-row>
    <el-row>
      <!-- 主研单位 -->
      <el-form-item :label="$t('trials:trials-list:form:researchUnit')" prop="MainResearchUnit">
        <el-input v-model="trialForm.MainResearchUnit" />
      </el-form-item>
      <!-- 负责人PI -->
      <el-form-item :label="$t('trials:trials-list:form:pi')" prop="HeadPI">
        <el-input v-model="trialForm.HeadPI" />
      </el-form-item>
    </el-row>
    <el-row>
      <!-- 申办方 -->
      <el-form-item :label="$t('trials:trials-list:form:sponsor')">
        <el-select v-model="trialForm.SponsorId">
          <el-option
            v-for="(item) in sponsorList"
            :key="item.Id"
            :label="item.SponsorName"
            :value="item.Id"
          />
        </el-select>
      </el-form-item>
      <!-- CRO -->
      <el-form-item :label="$t('trials:trials-list:form:cro')">
        <el-select v-model="trialForm.CROId">
          <el-option
            v-for="(item) of croList"
            :key="item.Id"
            :label="item.CROName"
            :value="item.Id"
          />
        </el-select>
      </el-form-item>
    </el-row>
    <el-row>
      <!-- DeclarationType -->
      <el-form-item :label="$t('trials:trials-list:form:declarationType')" prop="DeclarationTypeEnumList">
        <el-select
          v-model="trialForm.DeclarationTypeEnumList"
          size="small"
          multiple
          clearable
          @change="handleDeclarationTypeChange"
          style="width: 100%"
        >
          <el-option v-for="item of $d.DeclarationType" :key="item.value" :value="item.value" :label="item.label" />
        </el-select>
      </el-form-item>
      <!-- Phase -->
      <el-form-item :label="$t('trials:trials-list:form:phase')" prop="PhaseId">
        <el-select v-model="trialForm.PhaseId" @change="handlePhaseChange">
          <!-- <el-option
            v-for="item in phase"
            :key="item.Id"
            :label="item.Value"
            :value="item.Id"
          /> -->
          <el-option
            v-for="item of $d.Trial_Phase"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-row>
    <el-row>
      <!-- 适应症类型 IndicationType -->
      <el-form-item :label="$t('trials:trials-list:form:indicationType')" prop="IndicationTypeId">
        <el-select v-model="trialForm.IndicationTypeId" @change="handleIndicationTypeChange">
          <!-- <el-option
            v-for="item of dictionaryList.IndicationType"
            :key="item.Id"
            :label="item.Value"
            :value="item.Id"
          /> -->
          <el-option
            v-for="item of $d.IndicationType"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <!-- Indication -->
      <el-form-item  :label="$t('trials:trials-list:form:indication')" prop="IndicationEnum">
        <!--        <el-input v-model="trialForm.Indication" />-->
        <el-select :disabled="!trialForm.IndicationTypeId" v-if="![37, 38, 39].includes(trialForm.IndicationEnum)" v-model="trialForm.IndicationEnum">
          <el-option
            v-for="item of $d.Indication"
            v-show="indicationGrouping === item.raw.ChildGroup"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-row v-if="[37, 38, 39].includes(trialForm.IndicationEnum)">
          <el-col :span="12">
            <el-select :disabled="!trialForm.IndicationTypeId" v-model="trialForm.IndicationEnum" style="width: 100%;margin-right: 10px;">
              <el-option
                v-for="item of $d.Indication"
                v-show="indicationGrouping === item.raw.ChildGroup"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-col>
          <el-col :span="12">
            <el-input :disabled="!trialForm.IndicationTypeId" v-model="trialForm.Indication" />
          </el-col>
        </el-row>
      </el-form-item>
    </el-row>
    <el-row>
      <!-- Modality -->
      <el-form-item :label="$t('trials:trials-list:form:modality')">
        <el-select v-model="trialForm.ModalityIds" multiple>
          <!-- <el-option
            v-for="item of dictionaryList.Modality"
            :key="item.Id"
            :label="item.Value"
            :value="item.Id"
          /> -->
          <el-option
            v-for="item of $d.Modality"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <!-- Sites -->
      <el-form-item :label="$t('trials:trials-list:form:siteCount')">
        <el-input-number v-model="trialForm.PlanSiteCount" controls-position="right" :min="0" />
      </el-form-item>

    </el-row>
    <el-row>
      <!-- Expected Patients Num -->
      <el-form-item :label="$t('trials:trials-list:form:patientsNum')">
        <el-input-number
          v-model="trialForm.ExpectedPatients"
          controls-position="right"
          :min="0"
          @change="handleExpectedPatientsChange"
        />
      </el-form-item>
      <!-- Timepoints Per Patient -->
      <el-form-item :label="$t('trials:trials-list:form:timePointsPerPatient')">
        <el-input-number
          v-model="trialForm.TimePointsPerPatient"
          controls-position="right"
          :min="0"
          @change="handleTpPerPatientChange"
        />
      </el-form-item>
    </el-row>
    <el-row>
      <!-- Visits -->
      <el-form-item :label="$t('trials:trials-list:form:visitCount')">
        <el-input-number v-model="trialForm.PlanVisitCount" controls-position="right" :min="0" />
      </el-form-item>

    </el-row>
    <el-row>

      <!-- Expedited -->
      <el-form-item :label="$t('trials:trials-list:form:expedited')" prop="Expedited">
        <el-select v-model="trialForm.Expedited">
          <el-option
            v-for="item in expeditedOption"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <!-- Turnaround Time -->
      <el-form-item :label="$t('trials:trials-list:form:projectCycle')" prop="ProjectCycle">
        <el-input v-model="trialForm.ProjectCycle" />
      </el-form-item>
    </el-row>
    <el-row>

      <!-- Total Reviewers -->
      <el-form-item :label="$t('trials:trials-list:form:totalReviewers')">
        <el-input-number v-model="trialForm.TotalReviewers" controls-position="right" :min="0" />
      </el-form-item>
      <!-- Type of Reviewers -->
      <el-form-item :label="$t('trials:trials-list:form:typeofReviewers')">
        <el-select
          v-model="trialForm.AttendedReviewerTypeEnumList"
          size="small"
          multiple
          clearable
        >
          <el-option v-for="item of $d.AttendedReviewerType" :key="item.value" :value="item.value" :label="item.label" />
        </el-select>
<!--        <el-row v-if="trialForm.AttendedReviewerTypeEnumList.includes(2)">-->
<!--          <el-col :span="12">-->
<!--            <el-select-->
<!--              v-model="trialForm.AttendedReviewerTypeEnumList"-->
<!--              size="small"-->
<!--              multiple-->
<!--              clearable-->
<!--              style="width: 100%"-->
<!--            >-->
<!--              <el-option v-for="item of $d.AttendedReviewerType" :key="item.value" :value="item.value" :label="item.label" />-->
<!--            </el-select>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-input  size="small" v-model="trialForm.AttendedReviewerTypeOther"/>-->
<!--          </el-col>-->
<!--        </el-row>-->
      </el-form-item>
    </el-row>
    <el-row style="margin-left:190px">
      <el-form-item label="">
        <el-button type="primary" :disabled="btnLoading" @click="handleCancel">
          {{ $t('trials:trials-list:form:cancel') }}
        </el-button>
        <el-button type="primary" :loading="btnLoading" @click="handleSave">
          {{ $t('trials:trials-list:form:save') }}
        </el-button>
      </el-form-item>
    </el-row>
  </el-form>
</template>
<script>
import store from '@/store'
import { mapGetters, mapState } from 'vuex'
import { getTrialInfo, addOrUpdateTrial } from '@/api/trials'
import { getBasicDataSelects } from '@/api/dictionary/dictionary'
export default {
  name: 'TrialForm',
  props: {
    trialId: {
      type: String,
      default: ''
    }
  },
  data() {
    const comfirmIndication = (rule, value, callback) => {
      if ([37, 38, 39].includes(value)) {
        if (!this.trialForm.Indication) {
          return callback(new Error(this.$t('common:ruleMessage:specify')))
        }
      }
      callback()
    }
    const comfirmDeclarationType = (rule, value, callback) => {
      console.log(value)
      if (value.includes(-1)) {
        if (!this.trialForm.DeclarationTypeOther) {
          return callback(new Error(this.$t('common:ruleMessage:specify')))
        }
      }
      callback()
    }
    const comfirmAttendedReviewerType = (rule, value, callback) => {
      if (value.includes(2)) {
        if (!this.trialForm.AttendedReviewerTypeOther) {
          return callback(new Error(this.$t('common:ruleMessage:specify')))
        }
      }
      callback()
    }
    return {
      trialForm: {
        Id: '',
        TrialCode: '',
        TrialType: null,
        SponsorId: '',
        // CriterionIds: [],
        CROId: '',
        ReviewModeId: '',
        ReviewTypeIds: [],

        // 默认值0
        Expedited: '',

        ModalityIds: [],
        Note: '',
        ExpectedPatients: '',
        TimePointsPerPatient: '',
        ProjectCycle: '',
        TotalReviewers: '',
        DeclarationTypeId: '',
        IndicationTypeId: '',
        PhaseId: '',
        AttendedReviewerType: '',
        IsLocked: false,
        ResearchProgramNo: '',
        ExperimentName: '',
        MainResearchUnit: '',
        HeadPI: '',
        PlanSiteCount: null,
        PlanVisitCount: null,
        IndicationEnum: null,
        Indication: null,
        AttendedReviewerTypeEnumList: [],
        DeclarationTypeEnumList: [],
        DeclarationTypeOther: null,
        AttendedReviewerTypeOther: null,
      },
      indicationGrouping: null,
      trialFormRules: {
        Code: [
          { required: true, message: this.$t('common:ruleMessage:specify'), trigger: 'blur' },
          { max: 50, message: `${this.$t('common:ruleMessage:maxLength')} 50` }
        ],
        TrialType: [
          { required: true, message: this.$t('common:ruleMessage:specify'), trigger: 'blur' }
        ],
        ResearchProgramNo: [
          { required: true, message: this.$t('common:ruleMessage:specify'), trigger: 'blur' },
          { max: 100, message: `${this.$t('common:ruleMessage:maxLength')} 100` }
        ],
        ExperimentName: [
          { required: true, message: this.$t('common:ruleMessage:specify'), trigger: 'blur' },
          { max: 100, message: `${this.$t('common:ruleMessage:maxLength')} 100` }
        ],
        IndicationEnum: [
          { required: true, message: this.$t('common:ruleMessage:specify'), trigger: 'blur' },
          { validator: comfirmIndication, trigger: 'blur' }
        ],
        ProjectCycle: [{ max: 50, message: `${this.$t('common:ruleMessage:maxLength')} 50` }],
        ReviewModeId: [
          { required: true, message: this.$t('common:ruleMessage:select'), trigger: ['blur', 'change'] }
        ],
        Expedited: [
          { required: true, message: this.$t('common:ruleMessage:select'), trigger: ['blur', 'change'] }
        ],
        Note: [{ max: 500, message: `${this.$t('common:ruleMessage:maxLength')} 500` }],
        ModalityIds: [
          { required: true, message: this.$t('common:ruleMessage:select'), trigger: ['blur', 'change'] }
        ],
        PhaseId: [{ required: true, message: this.$t('common:ruleMessage:select'), trigger: ['blur', 'change'] }],
        IndicationTypeId: [{ required: true, message: this.$t('common:ruleMessage:select'), trigger: ['blur', 'change'] }],
        DeclarationTypeEnumList: [
          { required: true, message: this.$t('common:ruleMessage:select'), trigger: ['blur', 'change'] },
          ],
        ReviewTypeIds: [
          { required: true, message: this.$t('common:ruleMessage:select'), trigger: ['blur', 'change'] }
        ]
      },
      btnLoading: false,
      isLock: false,
      expeditedOption: this.$d.YesOrNoForInt,
      loading: false,
      declarationNum: null,
      indicationNum: null,
      phaseNum: null,
      dictionaryList: {}
    }
  },
  computed: {
    ...mapGetters(['sponsorList', 'croList']),
    ...mapState('user', ['isTestUser'])
  },
  mounted() {
    this.initPage()
    console.log(this.isTestUser, 'isTestUser')
  },
  methods: {
    initForm() {
      this.loading = true
      getTrialInfo(this.trialId).then(res => {
        this.loading = false
        if (res.IsSuccess) {
          for (var item in this.trialForm) {
              res.Result[item] === '00000000-0000-0000-0000-000000000000' ? '' : this.$set(this.trialForm, item, res.Result[item])
            if (item === 'IndicationTypeId') {
              this.indicationGrouping = this.$d.IndicationType.filter(v => v.id === res.Result[item])[0].raw.ChildGroup
            }
          }
        }
      }).catch(() => { this.loading = false })
    },
    handleSave() {
      this.$refs.trialForm.validate(valid => {
        if (valid) {
          this.btnLoading = true
          if (!this.trialForm.Id) {
            this.trialForm.TrialCode = `${this.declarationNum}${this.indicationNum}${this.phaseNum}`
            console.log(this.trialForm.TrialCode)
          }
          var params = JSON.parse(JSON.stringify(this.trialForm))
          console.log(params)
          addOrUpdateTrial(params).then(res => {
            this.btnLoading = false
            if (!this.trialForm.Id) {
              this.trialForm.Id = res.Result
              this.$message.success(this.$t('trials:trials-list:message:addedSuccessfully'))
            } else {
              this.$message.success(this.$t('trials:trials-list:message:updatedSuccessfully'))
            }

            this.$emit('getList')
            this.$emit('closeDialog')
          }).catch(() => {
            this.btnLoading = false
          })
        }
      })
    },
    handleCancel() {
      this.$emit('closeDialog')
      // this.$refs['trialForm'].resetFields()
    },
    handleDeclarationTypeChange(val) {
      console.log(val)
      if (val.length === 1) {
        // this.declarationNum = this.dictionaryList.DeclarationType.filter(item => item.Idd === val)[0].ShowOrder
        this.declarationNum = this.$d.DeclarationType.filter(item => item.value === val[0])[0].raw.ShowOrder
        if (this.trialForm.Id) {
          const ids = [...this.trialForm.TrialCode]
          ids[2] = this.declarationNum
          this.trialForm.TrialCode = ids.join('')
        }
      } else {
        this.declarationNum = 'X'
        if (this.trialForm.Id) {
          const ids = [...this.trialForm.TrialCode]
          ids[2] = this.declarationNum
          this.trialForm.TrialCode = ids.join('')
        }
      }
    },
    handleIndicationTypeChange(val) {
      this.indicationGrouping = null
      if (val) {
        // this.indicationNum = this.dictionaryList.IndicationType.filter(item => item.Id === val)[0].ShowOrder
        this.indicationNum = this.$d.IndicationType.filter(item => item.id === val)[0].raw.ShowOrder
        if (this.trialForm.Id) {
          const ids = [...this.trialForm.TrialCode]
          ids[3] = this.indicationNum
          this.trialForm.TrialCode = ids.join('')
        }
        this.indicationGrouping = this.$d.IndicationType.filter(item => item.id === val)[0].raw.ChildGroup
      }
      this.trialForm.Indication = null
    },
    handlePhaseChange(val) {
      if (val) {
        // const phase = this.dictionaryList['Trial_Phase']
        // this.phaseNum = phase.filter(item => item.Id === val)[0].ShowOrder
        this.phaseNum = this.$d.Trial_Phase.filter(item => item.id === val)[0].raw.ShowOrder
        if (this.trialForm.Id) {
          const ids = [...this.trialForm.TrialCode]
          ids[4] = this.phaseNum
          this.trialForm.TrialCode = ids.join('')
        }
      }
    },
    handleExpectedPatientsChange(val) {
      this.trialForm.PlanVisitCount = val * this.trialForm.TimePointsPerPatient
    },
    handleTpPerPatientChange(val) {
      this.trialForm.PlanVisitCount = val * this.trialForm.ExpectedPatients
    },
    async initPage() {
      this.loading = true
      await this.getDicData()
      await store.dispatch('global/getSponsorList')
      await store.dispatch('global/getCROList')
      if (this.trialId) {
        this.trialForm.Id = this.trialId
        this.initForm()
      }
      this.loading = false
    },
    getDicData() {
      getBasicDataSelects(['DeclarationType', 'IndicationType', 'Modality', 'ReviewMode', 'ReviewType', 'Trial_Phase']).then(res => {
        this.dictionaryList = { ...res.Result }
      })
    }
  }
}
</script>
<style>
.trial-Form .el-input,
.trial-Form .el-select,
.trial-Form .el-radio-group,
.trial-Form .el-input-number,
.trial-Form .el-textarea {
  width: 340px;
}
.trial-Form .el-col .el-input{
  width: 165px;
  margin-right: 10px;
}
</style>
