<template>
  <el-form
    ref="clinicalDataForm"
    v-loading="loading"
    :model="form"
    size="small"
    :rules="rules"
    :disabled="type === 'look'"
    label-width="130px"
  >
    <div class="base-dialog-body">
      <el-form-item :label="$t('trials:trials-config:clinicalDataQuestionCfg:table:type')" prop="ClinicalQuestionType">
        <el-select v-model="form.ClinicalQuestionType" clearable @change="((val)=>{typeChange(val, form)})">
          <el-option
            v-for="item of $d.ClinicalQuestionType"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        :label="$t('trials:trials-config:clinicalDataQuestionCfg:table:qsName')"
        prop="QuestionName"
      >
        <el-input v-model="form.QuestionName" />
      </el-form-item>
      <el-form-item
        :label="$t('trials:trials-config:clinicalDataQuestionCfg:table:qsNameEn')"
        prop="QuestionEnName"
      >
        <el-input v-model="form.QuestionEnName" />
      </el-form-item>
      <el-form-item
        v-if="form.ClinicalQuestionType === 'select' || form.ClinicalQuestionType === 'radio' || form.ClinicalQuestionType === 'checkbox'"
        :label="$t('trials:trials-config:clinicalDataQuestionCfg:table:options')"
        prop="TypeValue"
      >
        <el-input
          v-model="form.TypeValue"
          :placeholder="$t('trials:trials-config:clinicalDataQuestionCfg:msg:options')"
        />
      </el-form-item>
      <el-form-item
        v-if="form.ClinicalQuestionType === 'number'"
        :label="$t('trials:trials-config:clinicalDataQuestionCfg:table:decimalPlaces')"
        prop="DigitPlaces"
      >
        <el-radio-group
          v-model="form.DigitPlaces"
          style="line-height: 40px;"
        >
          <el-radio
            v-for="item of $d.DigitPlaces"
            :key="`DigitPlaces${item.value}`"
            :label="item.value"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        v-if="form.ClinicalQuestionType === 'number'"
        :label="$t('trials:trials-config:clinicalDataQuestionCfg:table:unit')"
        prop="Unit"
      >
        <el-input
          v-model="form.Unit"
        />
      </el-form-item>
      <div v-if="form.ClinicalQuestionType === 'number'" style="background: #f8f8f8;padding: 10px 0px;border-radius: 10px;position: relative;margin-bottom: 10px;">
        <!-- 运算类型 -->
        <el-form-item
          :label="$t('trials:readingUnit:qsList:title:customCalculateMark')"
          prop="CustomCalculateMark"
        >
          <el-radio-group
            v-model="form.CustomCalculateMark"
            style="line-height: 40px;"
            @change="(v) => CustomCalculateMarkChange(v)"
          >
            <div>
              <el-radio
                v-for="item of $d.ClinicalCustomCalculateMark"
                v-show="item.value <= 4"
                :key="`CustomCalculateMark${item.value}`"
                :label="item.value"
              >
                {{ item.label }}
              </el-radio>
            </div>
            <div>
              <el-radio
                v-for="item of $d.ClinicalCustomCalculateMark"
                v-show="item.value > 4"
                :key="`CustomCalculateMark${item.value}`"
                :label="item.value"
              >
                {{ item.label }}
              </el-radio>
            </div>
          </el-radio-group>
        </el-form-item>
        <el-table
          v-if="isShow"
          ref="CalculateTable"
          :data="form.CalculateQuestions"
          style="margin: 10px;width: calc(100% - 20px)"
          size="small"
        >
          <!-- 序号 -->
          <el-table-column
            :label="$t('trials:readingUnit:qsList:title:order')"
            min-width="70"
          >
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <!-- 运算类型 -->
          <el-table-column
            :label="$t('trials:readingUnit:qsList:title:customCalculateMark')"
            show-overflow-tooltip
            min-width="70"
          >
            <template>
              {{ $fd('ClinicalCustomCalculateMark', form.CustomCalculateMark) }}
            </template>
          </el-table-column>
          <!-- 问题名称 -->
          <el-table-column
            :label="form.CustomCalculateMark >= 10 ? $t('trials:trials-config:clinicalDataQuestionCfg:title:birthDay') : $t('trials:readingUnit:qsList:title:qsName')"
            prop="TableQuestionId"
            show-overflow-tooltip
            min-width="180"
          >
            <template slot-scope="scope">
              <el-select v-model="scope.row.TableQuestionId" clearable>
                <el-option v-for="item of Questions" :key="item.QuestionId" :disabled="item.QuestionId === scope.row.QuestionId" :label="item.QuestionName" :value="item.QuestionId" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            v-if="form.CustomCalculateMark === 11"
            :label="$t('trials:trials-config:clinicalDataQuestionCfg:table:cutOffDate')"
            prop="TableQuestionId"
            show-overflow-tooltip
            min-width="180"
          >
            <template slot-scope="scope">
              <el-select v-model="scope.row.QuestionId" clearable>
                <el-option v-for="item of Questions" :key="item.QuestionId" :disabled="item.QuestionId === scope.row.TableQuestionId" :label="item.QuestionName" :value="item.QuestionId" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            v-if="form.CustomCalculateMark <= 4"
            :label="$t('common:action:action')"
            prop="TableQuestionId"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <!-- 添加 -->
              <el-button
                icon="el-icon-plus"
                size="mini"
                circle
                :title="$t('trials:readingUnit:qsList:title:add')"
                @click="addCustomCalculateMark(scope.$index)"
              />
              <!-- 删除 -->
              <el-button
                icon="el-icon-minus"
                size="mini"
                circle
                :disabled="form.CalculateQuestions.length <= 2"
                :title="$t('trials:readingUnit:qsList:title:delete')"
                @click="deleteCustomCalculateMark(scope.$index)"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-form-item
        v-if="form.ClinicalQuestionType !== 'group' && form.ClinicalQuestionType !== 'summary'"
        :label="$t('trials:trials-config:clinicalDataQuestionCfg:table:isDisplay')"
        prop="ClinicalQuestionShowEnum"
      >
        <el-radio-group
          v-model="form.ClinicalQuestionShowEnum"
          @change="((val)=>{isShowQuestionChange(val, form)})"
        >
          <el-radio
            v-for="item of $d.ClinicalQuestionShow"
            :key="`ClinicalQuestionShowEnum${item.value}`"
            :label="item.value"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        v-if="form.ClinicalQuestionType !== 'group' && form.ClinicalQuestionType !== 'summary' && form.ClinicalQuestionShowEnum===1"
        :label="$t('trials:trials-config:clinicalDataQuestionCfg:table:isDependence')"
        prop="ParentId"
      >
        <el-select
          v-model="form.ParentId"
          clearable
          @change="((val)=>{parentQuestionChange(val, form)})"
        >
          <el-option
            v-for="item of parentOptions"
            :key="`ParentId${item.QuestionId}`"
            :label="item.QuestionName"
            :value="item.Id"
          />
        </el-select>
      </el-form-item>
      <!-- 显示时依赖父问题触发值 -->
      <el-form-item
        v-if="form.ParentId && form.ClinicalQuestionShowEnum===1"
        :label="$t('trials:trials-config:clinicalDataQuestionCfg:table:displayTriggerVal')"
        prop="ParentTriggerValue"
      >
        <el-select v-model="form.ParentTriggerValue" clearable>
          <el-option
            v-for="item of parentTriggerValOptions"
            :key="item.id"
            :label="item.label"
            :value="item.value.toString()"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="form.ClinicalQuestionType !== 'group' && form.ClinicalQuestionType !== 'summary' && form.ClinicalQuestionType !== 'table'" :label="$t('trials:readingUnit:qsList:title:isRequired')" prop="IsRequired">
        <el-radio-group
          v-model="form.IsRequired"
          :disabled="form.IsJudgeQuestion===true || form.ShowQuestion===2"
          @change="((val)=>{isRequiredChange(val, form)})"
        >
          <el-radio
            v-for="item of $d.QuestionRequired"
            :key="`QuestionRequired${item.value}`"
            :label="item.value"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        v-if="form.ClinicalQuestionType !== 'group' && form.ClinicalQuestionType !== 'summary' && form.IsRequired === 1"
        :label="$t('trials:readingUnit:qsList:title:relevanceId')"
        prop="RelevanceId"
      >
        <el-select
          v-model="form.RelevanceId"
          clearable
          @change="((val)=>{relevanceQuestionChange(val, form)})"
        >
          <el-option
            v-for="item of parentOptions"
            :key="`RelevanceId${item.QuestionId}`"
            :label="item.QuestionName"
            :value="item.Id"
          />
        </el-select>
      </el-form-item>
      <!-- 必填触发值 -->
      <el-form-item
        v-if="form.RelevanceId && form.IsRequired === 1"
        :label="$t('trials:readingUnit:qsList:title:relevanceValueList')"
        prop="RelevanceValue"
      >
        <el-select v-model="form.RelevanceValue" clearable>
          <el-option
            v-for="item of reParentTriggerValOptions"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="form.ClinicalQuestionType !== 'group'"
        prop="GroupId"
        :label="$t('trials:trials-config:clinicalDataQuestionCfg:table:groupName')"
      >
        <el-select v-model="form.GroupId" clearable :disabled="isParentExistGroup">
          <el-option
            v-for="group of groupOptions"
            :key="group.Id"
            :label="group.QuestionName"
            :value="group.Id"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="form.ClinicalQuestionType === 'time' && [2, 3].includes(clinicalInfo.ClinicalDataLevel)"
        :label="$t('trials:trials-config:clinicalDataQuestionCfg:table:isStudyDate')"
        prop="IsCheckDate"
      >
        <el-radio-group
          v-model="form.IsCheckDate"
        >
          <el-radio
            v-for="item of $d.YesOrNo"
            :key="`IsCheckDate${item.value}`"
            :label="item.value"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        v-if="form.ClinicalQuestionType !== 'table' && form.ClinicalQuestionType !== 'group' && form.ClinicalQuestionType !== 'summary' && form.ClinicalQuestionType !== 'number' && form.ClinicalQuestionType !== 'select'"
        :label="$t('trials:trials-config:clinicalDataQuestionCfg:table:maxLength')"
      >
        <el-input-number
          v-model="form.MaxAnswerLength"
          controls-position="right"
          :min="0"
          :max="2000"
        />
      </el-form-item>
      <el-form-item
        v-if="form.ClinicalQuestionType === 'table'"
        :label="$t('trials:trials-config:clinicalDataQuestionCfg:table:maxRowCount')"
      >
        <el-input-number
          v-model="form.MaxQuestionCount"
          controls-position="right"
          :min="0"
          :max="10"
        />
      </el-form-item>
      <el-form-item
        v-if="form.ClinicalQuestionType === 'upload'"
        :label="$t('trials:trials-config:clinicalDataQuestionCfg:table:maxUploadCount')"
      >
        <el-input-number v-model="form.ImageCount" controls-position="right" :min="1" :max="10" />
      </el-form-item>
      <el-form-item
        :label="$t('trials:trials-config:clinicalDataQuestionCfg:table:orderNum')"
        prop="ShowOrder"
      >
        <el-input-number
          v-model="form.ShowOrder"
          controls-position="right"
          :min="0"
        />
      </el-form-item>
    </div>

    <div class="base-dialog-footer" style="text-align:right;margin-top:10px;">
      <el-form-item>
        <!-- 取消 -->
        <el-button
          :disabled="btnLoading"
          size="small"
          type="primary"
          @click="close"
        >
          {{ $t('common:button:cancel') }}
        </el-button>
        <!-- 保存 -->
        <el-button size="small" type="primary" :loading="btnLoading" @click="save">
          {{ $t('common:button:save') }}
        </el-button>
      </el-form-item>
    </div>
  </el-form>
</template>
<script>
import { addOrUpdateTrialClinicalQuestion, getTrialClinicalOtherQuestionList, getTrialClinicalGroupQuestionList, getClinicalCalculateQuestions } from '@/api/dictionary'
export default {
  name: 'AddOrUpdateClinicalData',
  props: {
    clinicalId: {
      type: String,
      default() { return '' }
    },
    clinicalInfo: {
      type: Object,
      default() { return {} }
    },
    list: {
      type: Array,
      default() { return [] }
    },
    data: {
      type: Object,
      default() { return {} }
    },
    type: {
      type: String,
      default() { return '' }
    }
  },
  data() {
    var validateTypeVal = (rule, value, callback) => {
      if (value === '') {
        callback(new Error(this.$t('common:ruleMessage:specify')))
      } else {
        var arr = value.split('|')
        if (new Set(arr).size !== arr.length) {
          callback(new Error(this.$t('trials:trials-config:clinicalDataQuestionCfg:title:optionsValidate')))
        } else {
          callback()
        }
      }
    }
    return {
      validateTypeVal: validateTypeVal,
      form: {
        Id: '',
        TrialClinicalId: null,
        DigitPlaces: null,
        QuestionName: '',
        QuestionEnName: '',
        ClinicalQuestionType: null,
        ValueType: '',
        Unit: '',
        TypeValue: '',
        ParentId: '',
        ParentTriggerValue: '',
        ShowOrder: 1,
        ClinicalQuestionShowEnum: 0,
        CalculateQuestions: [],
        IsRequired: 2,
        GroupName: '',
        GroupEnName: '',
        Remark: '',
        ImageCount: 1,
        QuestionType: null,
        MaxQuestionCount: 0,
        MaxAnswerLength: 0,
        IsCheckDate: false,
        LimitEdit: 0,
        GroupId: null,
        CustomCalculateMark: -1,
        RelevanceId: '',
        RelevanceValue: ''
      },
      rules: {
        ClinicalQuestionType: [
          { required: true, message: this.$t('common:ruleMessage:select'), trigger: 'blur' }
        ],
        GroupId: [
          { required: true, message: this.$t('common:ruleMessage:select'), trigger: 'blur' }
        ],
        LesionType: [
          { required: true, message: this.$t('common:ruleMessage:select'), trigger: 'blur' }
        ],
        QuestionName: [{ required: true, message: this.$t('common:ruleMessage:specify'), trigger: 'blur' },
          { max: 300, message: `${this.$t('common:ruleMessage:maxLength')} 300` }],
        QuestionGenre: [{ required: true, message: this.$t('common:ruleMessage:select'), trigger: 'blur' }],
        TypeValue: [{ required: true, message: this.$t('common:ruleMessage:specify'), trigger: 'blur' },
          { validator: validateTypeVal, trigger: 'blur' },
          { max: 500, message: `${this.$t('common:ruleMessage:maxLength')} 500` }],
        DictionaryCode: [{ required: true, message: this.$t('common:ruleMessage:select'), trigger: 'blur' }],
        IsCheckDate: [{ required: true, message: this.$t('common:ruleMessage:select'), trigger: 'blur' }],
        ClinicalQuestionShowEnum: [{ required: true, message: this.$t('common:ruleMessage:select'), trigger: 'blur' }],
        IsRequired: [{ required: true, message: this.$t('common:ruleMessage:select'), trigger: 'blur' }],
        DigitPlaces: [{ required: true, message: this.$t('common:ruleMessage:select'), trigger: 'blur' }],
        ParentId: [{ required: true, message: this.$t('common:ruleMessage:select'), trigger: 'blur' }],
        ParentTriggerValue: [
          { required: true, message: this.$t('common:ruleMessage:select'), trigger: 'blur' }
        ],
        RelevanceId: [{ required: true, message: this.$t('common:ruleMessage:select'), trigger: 'blur' }],
        RelevanceValue: [{ required: true, message: this.$t('common:ruleMessage:select'), trigger: 'blur' }],
        GroupName: [{ required: true, message: this.$t('common:ruleMessage:specify'), trigger: 'blur' },
          { max: 50, message: `${this.$t('common:ruleMessage:maxLength')} 50` }]
      },
      Questions: [],
      loading: false,
      btnLoading: false,
      parentOptions: [],
      parentTriggerValOptions: [],
      groupOptions: [],
      isParentExistGroup: false,
      lesionTypes: [],
      dicList: [],
      CriterionDictionaryList: [],
      isShow: false
    }
  },
  mounted() {
    this.initForm()
    this.getClinicalCalculateQuestions()
  },
  methods: {
    getClinicalCalculateQuestions() {
      getClinicalCalculateQuestions({
        TrialClinicalId: this.clinicalId,
        ClinicalQuestionType: 'time'
      }).then(res => {
        this.Questions = res.Result
      })
    },
    addCustomCalculateMark(index) {
      this.form.CalculateQuestions.splice(index + 1, 0, {
        IsTable: false,
        QuestionId: null,
        TableQuestionId: null
      })
    },
    deleteCustomCalculateMark(index) {
      this.form.CalculateQuestions.splice(index, 1)
    },
    CustomCalculateMarkChange() {
      this.isShow = false
      console.log(this.form.CustomCalculateMark)
      if (this.form.CustomCalculateMark < 0) {
        this.form.CalculateQuestions = []
        return
      }
      if (this.form.CustomCalculateMark === 10) {
        this.form.CalculateQuestions = [
          {
            IsTable: false,
            QuestionId: null,
            TableQuestionId: null
          }]
        this.$nextTick(() => {
          this.isShow = true
        })
        return
      }
      if (this.form.CustomCalculateMark <= 4) {
        this.form.CalculateQuestions = [
          {
            IsTable: false,
            QuestionId: null,
            TableQuestionId: null
          }, {
            IsTable: false,
            QuestionId: null,
            TableQuestionId: null
          }
        ]
      } else {
        this.form.CalculateQuestions = [
          {
            IsTable: true,
            QuestionId: null,
            TableQuestionId: null
          }
        ]
      }
      this.$nextTick(() => {
        this.isShow = true
      })
    },
    isRequiredChange(val, form) {
      if (val !== 1) {
        form.RelevanceId = ''
        form.RelevanceValue = ''
      }
    },
    async initForm() {
      await this.getGroupOptions()
      await this.getParentQuestions()
      await this.getBasicConfigSelect()
      if (Object.keys(this.data).length > 0) {
        for (const k in this.form) {
          if (k === 'CalculateQuestions' && this.data[k] !== undefined) {
            this.form[k] = JSON.parse(this.data[k])
            this.isShow = true
          } else {
            if (this.data.hasOwnProperty(k)) {
              this.form[k] = this.data[k]
            }
          }
        }
        if (this.form.ParentId !== '' && this.form.ParentId !== null && this.form.GroupName !== '') {
          this.isParentExistGroup = true
        }
        if (this.form.ParentId) {
          var index = this.parentOptions.findIndex(item => {
            return item.Id === this.form.ParentId
          })
          if (index !== -1) {
            const options = []
            this.parentOptions[index].TypeValue.split('|').forEach((item, index) => {
              options.push({ id: index, label: item, value: item })
            })
            this.parentTriggerValOptions = options
          }
        }
        if (this.form.RelevanceId) {
          var i = this.parentOptions.findIndex(item => {
            return item.Id === this.form.RelevanceId
          })
          if (i !== -1) {
            const options = []
            this.parentOptions[index].TypeValue.split('|').forEach((item, index) => {
              options.push({ id: index, label: item, value: item })
            })
            this.reParentTriggerValOptions = options
          }
        }
      }
      if (!this.form.Id) {
        if (this.list.length > 0) {
          const max = Math.max(...this.list.map(item => item.ShowOrder))
          this.form.ShowOrder = max + 1
        }
      }
    },
    save() {
      this.$refs.clinicalDataForm.validate(valid => {
        if (!valid) return
        this.btnLoading = true
        this.form.TrialClinicalId = this.clinicalId
        if (this.form.ClinicalQuestionType !== 'upload') {
          this.form.ImageCount = 0
        }
        var params = Object.assign({}, this.form)
        params.CalculateQuestions = JSON.stringify(this.form.CalculateQuestions)
        params.IsVerify = true
        addOrUpdateTrialClinicalQuestion(params).then(res => {
          this.btnLoading = false
          this.$emit('getList')
          this.$emit('close')
          this.$message.success(this.$t('common:message:savedSuccessfully'))
        })
          .catch((res) => {
            this.$confirm(this.$t('trials:trials-config:clinicalDataQuestionCfg:msg:questionOfHomonyms')).then(() => {
              params.IsVerify = false
              addOrUpdateTrialClinicalQuestion(params).then(res => {
                this.btnLoading = false
                this.$emit('getList')
                this.$emit('close')
                this.$message.success(this.$t('common:message:savedSuccessfully'))
              }).catch(() => {
                this.btnLoading = false
              })
            }).catch(() => {
              this.btnLoading = false
            })
          })
      })
    },
    getBasicConfigSelect() {
      this.dicList = this.$d
    },
    getGroupOptions() {
      return new Promise((resolve, reject) => {
        this.loading = true
        var param = {
          TrialClinicalId: this.clinicalId
        }
        getTrialClinicalGroupQuestionList(param).then(res => {
          this.groupOptions = res.Result
          this.loading = false
          resolve()
        }).catch(() => {
          this.loading = false
          reject()
        })
      })
    },
    getParentQuestions() {
      return new Promise((resolve, reject) => {
        this.loading = true
        var param = {
          TrialClinicalId: this.clinicalId
        }
        getTrialClinicalOtherQuestionList(param).then(res => {
          this.parentOptions = res.Result
          this.loading = false
          resolve()
        }).catch(() => {
          this.loading = false
          reject()
        })
      })
    },
    typeChange(val, data) {
      if (val === 'table') {
        data.IsRequired = 2
      } else {
        data.LesionType = null
      }
      data.TypeValue = ''
      data.ValueType = ''
      data.Unit = ''
    },
    isShowQuestionChange(val, form) {
      if (val === 2) {
        form.IsRequired = 2
        form.ParentId = ''
        form.ParentTriggerValue = ''
      } else {
        form.ParentId = ''
        form.ParentTriggerValue = ''
      }
    },
    parentQuestionChange(val, form) {
      console.log(val)
      if (val) {
        var index = this.parentOptions.findIndex(item => {
          return item.Id === val
        })
        if (index !== -1) {
          var options = []
          this.parentOptions[index].TypeValue.split('|').forEach((item, index) => {
            options.push({ id: index, label: item, value: item })
          })
          this.parentTriggerValOptions = options
        }
      } else {
        form.GroupName = ''
        form.GroupEnName = ''
      }
      form.ParentTriggerValue = ''
    },
    relevanceQuestionChange(val, form) {
      if (val) {
        var index = this.parentOptions.findIndex(item => {
          return item.Id === val
        })
        if (index !== -1) {
          var options = []
          this.parentOptions[index].TypeValue.split('|').forEach((item, index) => {
            options.push({ id: index, label: item, value: item })
          })
          this.reParentTriggerValOptions = options
        }
      }
      form.RelevanceValue = ''
    },
    close() {
      this.$emit('close')
    }

  }
}
</script>
<style lang="scss" scoped>
</style>
