<!-- eslint-disable -->
<template>
  <el-form
    ref="trialForm"
    v-loading="loading"
    label-width="190px"
    :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 :maxLength="$inputMax" 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 :maxLength="$inputMax" 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 :maxLength="$inputMax" 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 :maxLength="$inputMax" v-model="trialForm.MainResearchUnit" />-->
<!--      </el-form-item>-->
      <!-- 负责人PI -->
      <el-form-item :label="$t('trials:trials-list:form:pi')" prop="HeadPI">
        <el-input :maxLength="10" 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>-->
<!--      &lt;!&ndash; DeclarationType &ndash;&gt;-->
<!--      <el-form-item :label="$t('trials:trials-list:form:declarationType')" prop="DeclarationTypeId">-->
<!--        <el-select v-model="trialForm.DeclarationTypeId" @change="handleDeclarationTypeChange">-->
<!--          <el-option-->
<!--            v-for="item of $d.DeclarationType"-->
<!--            :key="item.id"-->
<!--            :label="item.label"-->
<!--            :value="item.id"-->
<!--          />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
<!--      &lt;!&ndash; Phase &ndash;&gt;-->
<!--      <el-form-item :label="$t('trials:trials-list:form:phase')" prop="PhaseId">-->
<!--        <el-select v-model="trialForm.PhaseId" @change="handlePhaseChange">-->
<!--          &lt;!&ndash; <el-option-->
<!--            v-for="item in phase"-->
<!--            :key="item.Id"-->
<!--            :label="item.Value"-->
<!--            :value="item.Id"-->
<!--          /> &ndash;&gt;-->
<!--          <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">-->
<!--          &lt;!&ndash; <el-option-->
<!--            v-for="item of dictionaryList.IndicationType"-->
<!--            :key="item.Id"-->
<!--            :label="item.Value"-->
<!--            :value="item.Id"-->
<!--          /> &ndash;&gt;-->
<!--          <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="Indication">
        <!--        <el-input :maxLength="$inputMax" v-model="trialForm.Indication" />-->
        <el-select v-if="trialForm.Indication !== 'Other' && trialForm.Indication !== '其它' " v-model="trialForm.Indication">
          <el-option
            v-for="item of $d.Indication"
            v-show="indicationGrouping === item.raw.ChildGroup"
            :key="item.id"
            :label="item.label"
            :value="item.label"
          />
        </el-select>
        <el-row v-if="trialForm.Indication === 'Other' || trialForm.Indication === '其它' ">
          <el-col :span="12">
            <el-select v-model="trialForm.Indication" style="width: 200px;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.label"
              />
            </el-select>
          </el-col>
          <el-col :span="12">
            <el-input :maxLength="$inputMax" v-model="trialForm.IndicationOther" />
          </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>-->
<!--      &lt;!&ndash; Expected Patients Num &ndash;&gt;-->
<!--      <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>-->
<!--      &lt;!&ndash; Timepoints Per Patient &ndash;&gt;-->
<!--      <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>-->
<!--      &lt;!&ndash; Visits &ndash;&gt;-->
<!--      <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>-->
<!--      &lt;!&ndash; Expedited &ndash;&gt;-->
<!--      <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>-->
<!--      &lt;!&ndash; Turnaround Time &ndash;&gt;-->
<!--&lt;!&ndash;      <el-form-item :label="$t('trials:trials-list:form:projectCycle')" prop="ProjectCycle">&ndash;&gt;-->
<!--&lt;!&ndash;        <el-input :maxLength="$inputMax" v-model="trialForm.ProjectCycle" />&ndash;&gt;-->
<!--&lt;!&ndash;      </el-form-item>&ndash;&gt;-->
<!--    </el-row>-->
<!--    <el-row>-->

<!--      &lt;!&ndash; Total Reviewers &ndash;&gt;-->
<!--&lt;!&ndash;      <el-form-item :label="$t('trials:trials-list:form:totalReviewers')">&ndash;&gt;-->
<!--&lt;!&ndash;        <el-input-number v-model="trialForm.TotalReviewers" controls-position="right" :min="0" />&ndash;&gt;-->
<!--&lt;!&ndash;      </el-form-item>&ndash;&gt;-->
<!--      &lt;!&ndash; Type of Reviewers &ndash;&gt;-->
<!--      <el-form-item :label="$t('trials:trials-list:form:typeofReviewers')">-->
<!--        <el-select-->
<!--          v-model="trialForm.AttendedReviewerType"-->
<!--          size="small"-->
<!--          clearable-->
<!--          class="mr"-->
<!--        >-->
<!--          <el-option v-for="item of $d.AttendedReviewerType" :key="item.value" :value="item.value" :label="item.label" />-->
<!--        </el-select>-->
<!--      </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 (value === '其它' || value === 'Other') {
        if (!this.trialForm.IndicationOther) {
          return callback(new Error('请输入适应症'))
        }
      }
      callback()
    }
    return {
      trialForm: {
        Id: '',
        TrialCode: '',
        TrialType: 1,
        SponsorId: '',
        // CriterionIds: [],
        CROId: '',
        ReviewModeId: '',
        ReviewTypeIds: [],

        // 默认值0
        Expedited: 0,

        ModalityIds: [],
        Note: '',
        ExpectedPatients: 0,
        TimePointsPerPatient: 0,
        ProjectCycle: '',
        TotalReviewers: 0,
        DeclarationTypeId: '742e0000-3e2c-0016-b5ca-08da6222442f',
        IndicationTypeId: '437a81b3-c5ad-49fd-82a1-8f441c4ba8da',
        PhaseId: 'b1509dde-234a-46ce-cf13-08d9c120c961',
        AttendedReviewerType: 0,
        IsLocked: false,
        ResearchProgramNo: '111',
        ExperimentName: '',
        MainResearchUnit: '',
        HeadPI: '',
        PlanSiteCount: null,
        PlanVisitCount: null,
        Indication: null,
        IndicationOther: 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' }
        ],
        HeadPI: [
          { max: 10, message: `${this.$t('common:ruleMessage:maxLength')} 10` }
        ],
        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` }
        ],
        Indication: [
          { required: true, message: this.$t('common:ruleMessage:specify'), trigger: 'blur' },
          { max: 50, message: `${this.$t('common:ruleMessage:maxLength')} 50` },
          { 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'] }],
        DeclarationTypeId: [{ 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()
    this.handleIndicationTypeChange('437a81b3-c5ad-49fd-82a1-8f441c4ba8da')
    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) {
            if (item === 'IndicationOther') return
            if (item === 'Indication') {
              if (~res.Result['Indication'].indexOf('-')) {
                var arr = res.Result['Indication'].split('-')
                this.$set(this.trialForm, 'IndicationOther', arr[1])
                this.trialForm['Indication'] = arr[0]
              } else {
                this.trialForm[item] =
                  res.Result[item] === '00000000-0000-0000-0000-000000000000'
                    ? ''
                    : res.Result[item]
              }
            } else {
              this.trialForm[item] =
                res.Result[item] === '00000000-0000-0000-0000-000000000000'
                  ? ''
                  : 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 = Object.assign({}, this.trialForm)
          if (params.Indication === '其它' || params.Indication === 'Other') {
            params.Indication = params.Indication + '-' + params.IndicationOther
          }
          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) {
      if (val) {
        // this.declarationNum = this.dictionaryList.DeclarationType.filter(item => item.Idd === val)[0].ShowOrder
        this.declarationNum = this.$d.DeclarationType.filter(item => item.id === val)[0].raw.ShowOrder
        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: 400px;
}
.trial-Form .el-col .el-input{
  width: 195px;
  margin-right: 10px;
}
</style>
