<template>
  <div class="form-container">
    <div class="title-wrapper">
      <p>{{ $t('system:TrialExperience:title:Clinical Trial Experience') }}</p>
      <el-button
        :disabled="$route.query.ReviewStatus === '1'"
        class="add"
        size="small"
        @click="handleAddClinicalTrial"
        >{{ $t('common:button:add') }}</el-button
      >
    </div>
    <div style="padding: 0 40px">
      <el-table
        ref="clinicalTrialTbl"
        v-loading="loading"
        :data="clinicalTrialList"
        class="table"
        size="small"
      >
        <el-table-column type="index" width="40" />
        <el-table-column
          prop="Phase"
          :label="$t('system:TrialExperience:title:Phase')"
          min-width="50"
        >
          <template slot-scope="scope">
            {{
              scope.row.OtherStages ? scope.row.OtherStages : scope.row.Phase
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="EvaluationCriteriaList"
          :label="$t('system:TrialExperience:title:Review Criteria')"
          min-width="100"
        >
          <template slot-scope="scope">
            {{
              scope.row.EvaluationCriteriaList.length > 0
                ? scope.row.EvaluationCriteriaList.join(', ')
                : ''
            }}
            <span v-if="scope.row.OtherCriterion">
              {{
                scope.row.EvaluationCriteriaList.length > 0
                  ? `, ${scope.row.OtherCriterion}`
                  : scope.row.OtherCriterion
              }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="EvaluationCriteriaList"
          :label="$t('system:TrialExperience:title:Starting And Ending Date')"
          min-width="100"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.StartTime"
              >{{ scope.row.StartTime.split('-')[0] }} ~
              {{
                scope.row.EndTime ? scope.row.EndTime.split('-')[0] : '至今'
              }}</span
            >
          </template>
        </el-table-column>
        <el-table-column
          prop="VisitReadingCount"
          :label="$t('system:TrialExperience:title:Visit Reading Count')"
          min-width="70"
        />
        <el-table-column
          prop="EvaluationContent"
          :label="$t('system:TrialExperience:Indication')"
          min-width="70"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.EvaluationContent">
              {{ scope.row.EvaluationContent }}
            </span>
            <span v-else>
              {{ $fd('Indication', scope.row.IndicationEnum) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('system:TrialExperience:Operation')"
          min-width="200"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              :disabled="$route.query.ReviewStatus === '1'"
              @click="handleEdit(scope.row)"
            >
              {{ $t('common:button:edit') }}
            </el-button>
            <el-button
              type="text"
              size="small"
              :disabled="$route.query.ReviewStatus === '1'"
              @click="handleDel(scope.row)"
            >
              {{ $t('common:button:delete') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="title-wrapper" style="margin-top: 10px">
      <p>{{ $t('system:TrialExperience:title:GCP Certificate') }}</p>
    </div>
    <div style="margin-left: 40px; width: 40%">
      <gcp-certificate
        :doctor-id="doctorId"
        :gcp="GCP"
        :gcp-id="GCPID"
        :DATA="GCPData"
      />
    </div>
    <div class="title-wrapper" style="margin-top: 10px">
      <p>{{ $t('system:TrialExperience:title:Other Relevant Experience') }}</p>
    </div>
    <div style="padding: 0 40px">
      <el-row type="flex" justify="space-between">
        <el-col :span="11">
          <el-input
            v-model="OtherClinicalExperience"
            type="textarea"
            rows="8"
            placeholder="Please specify in English"
            size="small"
            :maxlength="4000"
          />
        </el-col>
        <el-col :span="11">
          <el-input
            v-model="OtherClinicalExperienceCN"
            :disabled="$route.query.ReviewStatus === '1'"
            type="textarea"
            rows="8"
            placeholder="请用中文注明"
            size="small"
            :maxlength="4000"
          />
        </el-col>
      </el-row>
      <el-button
        type="primary"
        size="small"
        style="margin-top: 20px"
        :disabled="isBtnDisabled || $route.query.ReviewStatus === '1'"
        @click="handleSaveOtherClinical"
      >
        {{ $t('common:button:save') }}</el-button
      >
    </div>
    <el-dialog
      v-if="clinicalTrialDialogVisible"
      :title="clinicalTrialDialogTitle"
      :visible.sync="clinicalTrialDialogVisible"
      width="480px"
      :close-on-click-modal="false"
      append-to-body
    >
      <el-form
        ref="clinicalTrialForm"
        label-width="150px"
        :rules="clinicalTrialRules"
        class="demo-ruleForm"
        :model="clinicalTrialForm"
        size="small"
      >
        <el-form-item
          :label="$t('system:TrialExperience:label:Phase')"
          prop="PhaseId"
        >
          <el-select
            v-model="clinicalTrialForm.PhaseId"
            clearable
            placeholder=""
          >
            <el-option
              v-for="item of dictionaryList.Trial_Phase"
              :key="item.Id"
              :label="item.Value"
              :value="item.Id"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="OtherStages" v-if="Trial_Phase_isOther">
          <el-input
            v-model="clinicalTrialForm.OtherStages"
            clearable
            :placeholder="
              $t('curriculumVitae:clinicalTrials:placeholder:byStagesOther')
            "
            :maxlength="400"
          ></el-input>
        </el-form-item>
        <el-form-item
          :label="$t('system:TrialExperience:label:Review Criteria')"
          prop="EvaluationCriteriaIdList"
        >
          <el-select
            v-model="clinicalTrialForm.EvaluationCriteriaIdList"
            multiple
          >
            <!-- <el-option v-for="(key,value) of dictionaryList.CriterionType" :key="value" :label="key" :value="value" /> -->
            <el-option
              v-for="item in CriterionType"
              :key="item.Id"
              :label="item.Value"
              :value="item.Id"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="OtherCriterion" v-if="ReadingStandard_isOther">
          <el-input
            v-model="clinicalTrialForm.OtherCriterion"
            clearable
            :placeholder="
              $t('curriculumVitae:clinicalTrials:placeholder:criterionOther')
            "
            :maxlength="400"
          ></el-input>
        </el-form-item>
        <el-form-item
          :label="$t('system:TrialExperience:label:Start Time')"
          prop="StartTime"
        >
          <el-date-picker
            v-model="clinicalTrialForm.StartTime"
            type="year"
            value-format="yyyy"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item
          :label="$t('system:TrialExperience:label:End Time')"
          prop="EndTime"
        >
          <el-date-picker
            v-model="clinicalTrialForm.EndTime"
            type="year"
            value-format="yyyy"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item
          :label="$t('system:TrialExperience:Visit Reading Count')"
          prop="VisitReadingCount"
        >
          <el-input
            style="width: 100%"
            oninput="value=value.replace(/[^\d]/g,'')"
            v-model="clinicalTrialForm.VisitReadingCount"
            controls-position="right"
            :min="0"
          />
        </el-form-item>
        <!-- 适应症类型 IndicationType -->
        <el-form-item
          :label="$t('system:TrialExperience:indicationType')"
          prop="IndicationTypeId"
        >
          <el-select
            v-model="clinicalTrialForm.IndicationTypeId"
            @change="handleIndicationTypeChange"
          >
            <el-option
              v-for="item of $d.IndicationType"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          :label="$t('system:TrialExperience:Indication')"
          prop="IndicationEnum"
        >
          <el-select
            v-model="clinicalTrialForm.IndicationEnum"
            :disabled="!clinicalTrialForm.IndicationTypeId"
          >
            <el-option
              v-for="item of IndicationOptions"
              :key="item.id"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="EvaluationContent" v-if="IndicationEnum_isOther">
          <el-input
            v-model="clinicalTrialForm.EvaluationContent"
            clearable
            :maxlength="400"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          size="small"
          :loading="isDisabled"
          @click="handleSave"
          >{{ $t('common:button:save') }}</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
// import UploadFile from '@/components/UploadFile'
import {
  getTrialExperience,
  addOrUpdateTrialExperience,
  deleteTrialExperience,
  updateOtherExperience,
} from '@/api/reviewers'
import { getBasicDataSelects } from '@/api/dictionary/dictionary'
import GcpCertificate from './GcpCertificate.vue'
import moment from 'moment'
const getClinicalTrialDefault = () => {
  return {
    PhaseId: '',
    EvaluationCriteriaIdList: [],
    EvaluationContent: '',
    VisitReadingCount: 0,
    StartTime: null,
    EndTime: null,
    OtherStages: '',
    OtherCriterion: '',
    IndicationEnum: null,
    IndicationTypeId: null,
  }
}
export default {
  name: 'TrialExperience',
  components: { GcpCertificate },
  props: {
    reviewerId: {
      type: String,
    },
  },
  data() {
    return {
      loading: false,
      clinicalTrialList: [],
      clinicalTrialDialogTitle: '',
      clinicalTrialDialogVisible: false,
      clinicalTrialForm: getClinicalTrialDefault(),
      clinicalTrialRules: {
        PhaseId: [
          {
            required: true,
            message: 'Please select',
            trigger: ['blur', 'change'],
          },
        ],
        EvaluationCriteriaIdList: [
          {
            required: true,
            message: 'Please select',
            trigger: ['blur', 'change'],
          },
        ],
        VisitReadingCount: [
          { required: true, message: 'Please specify', trigger: 'blur' },
        ],
        EvaluationContent: [
          { required: true, message: 'Please specify', trigger: 'blur' },
          {
            max: 400,
            message: this.$t('form:rules:maxLength:400'),
            trigger: 'blur',
          },
        ],
        IndicationEnum: [
          { required: true, message: 'Please select', trigger: 'blur' },
        ],
        StartTime: [
          { required: true, message: 'Please specify', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (
                value &&
                this.clinicalTrialForm.EndTime &&
                moment(value).isAfter(moment(this.clinicalTrialForm.EndTime))
              ) {
                callback(
                  new Error(
                    this.$t('system:TrialExperience:rule:startBeforeEnd')
                  )
                )
              } else {
                callback()
              }
            },
            trigger: 'blur',
          },
        ],
        EndTime: [
          {
            validator: (rule, value, callback) => {
              if (
                value &&
                this.clinicalTrialForm.StartTime &&
                moment(value).isBefore(moment(this.clinicalTrialForm.StartTime))
              ) {
                callback(
                  new Error(
                    this.$t('system:TrialExperience:rule:endBeforeStart')
                  )
                )
              } else {
                callback()
              }
            },
            trigger: 'blur',
          },
        ],
        OtherStages: [
          {
            required: true,
            message: 'Please input',
            trigger: ['blur', 'change'],
          },
          {
            max: 400,
            message: this.$t('form:rules:maxLength:400'),
            trigger: 'blur',
          },
        ],
        OtherCriterion: [
          {
            required: true,
            message: 'Please input',
            trigger: ['blur', 'change'],
          },
          {
            max: 400,
            message: this.$t('form:rules:maxLength:400'),
            trigger: 'blur',
          },
        ],
      },
      GCP: 0,
      GCPID: '',
      OtherClinicalExperience: '',
      OtherClinicalExperienceCN: '',
      isDisabled: false,
      doctorId: this.$route.query.Id || this.reviewerId,
      isBtnDisabled: false,
      selectId: '00000000-0000-0000-0000-000000000000',
      dictionaryList: {},
      otherId: 'ef84e9cb-f1a6-49d7-b6da-34be2c12abd5',
      GCPData: {},
    }
  },
  computed: {
    IndicationOptions() {
      console.log(
        this.$d.IndicationType,
        this.clinicalTrialForm.IndicationTypeId
      )
      if (!this.clinicalTrialForm.IndicationTypeId) return []
      let indicationGroupingArr = this.$d.IndicationType.filter(
        (item) => item.id === this.clinicalTrialForm.IndicationTypeId
      )
      let indicationGrouping = null
      if (
        Array.isArray(indicationGroupingArr) &&
        indicationGroupingArr.length > 0
      ) {
        indicationGrouping = indicationGroupingArr[0].raw.ChildGroup
      }
      let arr =
        this.$d.Indication.filter(
          (item) => indicationGrouping === item.raw.ChildGroup
        ) || []
      return arr
    },
    IndicationEnum_isOther() {
      if (!this.clinicalTrialForm.IndicationEnum) return false
      let value = this.$d.Indication.find(
        (item) => item.value === this.clinicalTrialForm.IndicationEnum
      ).label
      return value === '其它' || value === 'Other'
    },
    Trial_Phase_isOther() {
      if (!this.clinicalTrialForm.PhaseId) return false
      let value = this.dictionaryList.Trial_Phase.find(
        (item) => item.Id === this.clinicalTrialForm.PhaseId
      ).Value
      return value === '其它' || value === 'Other'
    },
    ReadingStandard_isOther() {
      if (
        !this.clinicalTrialForm.EvaluationCriteriaIdList ||
        this.clinicalTrialForm.EvaluationCriteriaIdList.length <= 0
      )
        return false
      return this.clinicalTrialForm.EvaluationCriteriaIdList.includes(
        this.otherId
      )
    },
    CriterionType() {
      if (!this.dictionaryList.CriterionType) return []
      return [
        ...this.dictionaryList.CriterionType,
        {
          Id: this.otherId,
          Value: 'Other',
        },
      ]
    },
  },
  watch: {
    reviewerId() {
      if (this.reviewerId) {
        this.doctorId = this.reviewerId
        this.initForm()
      }
    },
    Trial_Phase_isOther() {
      if (!this.Trial_Phase_isOther) {
        this.clinicalTrialForm.OtherStages = null
      }
    },
    ReadingStandard_isOther() {
      if (!this.ReadingStandard_isOther) {
        this.clinicalTrialForm.OtherCriterion = null
      }
    },
    IndicationEnum_isOther() {
      if (!this.IndicationEnum_isOther) {
        this.clinicalTrialForm.EvaluationContent = null
      }
    },
  },
  created() {
    this.initForm()
  },
  methods: {
    async initForm() {
      await this.getDicData()
      const id = this.$route.query.Id || this.reviewerId
      if (id) {
        this.loading = true
        let data = {
          DoctorId: id,
        }
        if (this.$route.query.trialId) {
          data.TrialId = this.$route.query.trialId
        }
        getTrialExperience(data)
          .then((res) => {
            this.clinicalTrialList = res.Result.ClinicalTrialExperienceList
            this.GCP = res.Result.GCP
            this.GCPID = res.Result.GCPId
            this.GCPData = {
              GCPAgencies: res.Result.GCPAgencies,
              GCPTime: res.Result.GCPTime,
            }
            this.OtherClinicalExperience = res.Result.OtherClinicalExperience
            this.OtherClinicalExperienceCN =
              res.Result.OtherClinicalExperienceCN
            this.loading = false
          })
          .catch(() => {
            this.loading = false
          })
      }
    },
    getDicData() {
      getBasicDataSelects(['Trial_Phase', 'CriterionType']).then((res) => {
        this.dictionaryList = { ...res.Result }
      })
    },
    handleAddClinicalTrial() {
      this.clinicalTrialDialogTitle = 'New'
      this.clinicalTrialDialogVisible = true
      this.clinicalTrialForm.Id = null
      this.clinicalTrialForm = Object.assign({}, getClinicalTrialDefault())
    },
    handleEdit(row) {
      const {
        Id,
        PhaseId,
        EvaluationCriteriaIdList,
        EvaluationContent,
        StartTime,
        EndTime,
        VisitReadingCount,
        OtherStages,
        OtherCriterion,
        IndicationEnum,
        IndicationTypeId,
      } = row
      this.clinicalTrialForm = Object.assign({}, getClinicalTrialDefault())
      this.clinicalTrialDialogTitle = 'Edit'
      this.clinicalTrialDialogVisible = true
      this.clinicalTrialForm.Id = Id
      this.clinicalTrialForm.StartTime = StartTime
      this.clinicalTrialForm.EndTime = EndTime
      this.clinicalTrialForm.PhaseId = PhaseId
      this.clinicalTrialForm.VisitReadingCount = VisitReadingCount
      this.clinicalTrialForm.EvaluationCriteriaIdList = EvaluationCriteriaIdList
      this.clinicalTrialForm.EvaluationContent = EvaluationContent
      this.clinicalTrialForm.OtherStages = OtherStages
      this.clinicalTrialForm.OtherCriterion = OtherCriterion
      this.clinicalTrialForm.IndicationEnum = IndicationEnum
      this.clinicalTrialForm.IndicationTypeId = IndicationTypeId
    },
    handleSave() {
      this.$refs.clinicalTrialForm.validate((valid) => {
        if (valid) {
          this.isDisabled = true
          this.clinicalTrialForm.DoctorId =
            this.$route.query.Id || this.reviewerId
          var dateTime
          if (this.clinicalTrialForm.StartTime) {
            dateTime = new Date(this.clinicalTrialForm.StartTime)
            this.clinicalTrialForm.StartTime =
              moment(new Date(dateTime.setDate(dateTime.getDate() + 1))).format(
                'YYYY'
              ) + '-01'
          }
          if (this.clinicalTrialForm.EndTime) {
            dateTime = new Date(this.clinicalTrialForm.EndTime)
            this.clinicalTrialForm.EndTime =
              moment(new Date(dateTime.setDate(dateTime.getDate() + 1))).format(
                'YYYY'
              ) + '-01'
          }
          if (this.$route.query.trialId) {
            this.clinicalTrialForm.TrialId = this.$route.query.trialId
          }
          addOrUpdateTrialExperience(this.clinicalTrialForm)
            .then((res) => {
              this.isDisabled = false
              this.initForm()
              if (this.clinicalTrialForm.Id) {
                this.$message({
                  message: 'Updated successfully',
                  type: 'success',
                })
              } else {
                this.$message({
                  message: 'Addedd successfully',
                  type: 'success',
                })
              }
              this.clinicalTrialDialogVisible = false
            })
            .catch(() => {
              this.isDisabled = false
            })
        }
      })
    },
    handleDel(row) {
      this.$confirm('Confirm to delete?', {
        type: 'warning',
        distinguishCancelAndClose: true,
      })
        .then(() => {
          deleteTrialExperience(row.Id).then((res) => {
            this.clinicalTrialList.splice(
              this.clinicalTrialList.findIndex((item) => item.Id === row.Id),
              1
            )
            this.$message.success('Deleted successfully !')
          })
        })
        .catch((action) => {})
    },
    handleSaveOtherClinical() {
      const param = {
        DoctorId: this.doctorId,
        OtherClinicalExperience: this.OtherClinicalExperience,
        OtherClinicalExperienceCN: this.OtherClinicalExperienceCN,
      }
      if (this.$route.query.trialId) {
        param.TrialId = this.$route.query.trialId
      }
      updateOtherExperience(param).then((res) => {
        if (res.IsSuccess) {
          if (this.id) {
            this.$message.success('Updated successfully')
          } else {
            this.$message.success('Addedd successfully')
          }
        }
      })
    },
    handleIndicationTypeChange(val) {
      this.clinicalTrialForm.EvaluationContent = null
      this.clinicalTrialForm.IndicationEnum = null
    },
  },
}
</script>
