<template>
  <el-form
    ref="tableQsForm"
    v-loading="loading"
    :model="form"
    size="small"
    :disabled="type === 'look'"
    :rules="rules"
    label-width="120px"
  >
    <div class="base-dialog-body">
      <!-- 类型 -->
      <el-form-item :label="$t('trials:readingUnit:qsList:title:type')" prop="ClinicalTableQuestionType">
        <el-select
          v-model="form.ClinicalTableQuestionType"
          @change="((val)=>{qsTypeChange(val, form)})"
        >
          <el-option
            v-for="item of $d.ClinicalTableQuestionType"
            :key="item.value"
            :value="item.value"
            :label="item.label"
            :disabled="item.label === 'group' || item.label === 'table' || item.label === 'summary' || item.label === 'upload'"
          />
        </el-select>
      </el-form-item>
      <!-- 问题名称 -->
      <el-form-item
        v-if="form.ClinicalTableQuestionType !== 'group'"
        :label="$t('trials:readingUnit:qsList:title:qName')"
        prop="QuestionName"
      >
        <el-input
          v-model="form.QuestionName"
        />
      </el-form-item>
      <!-- 选项 -->
      <el-form-item
        :label="$t('trials:readingUnit:qsList:title:typeValue')"
        v-if="form.ClinicalTableQuestionType === 'select' || form.ClinicalTableQuestionType === 'radio'"
        prop="TypeValue"
      >
        <el-input
          v-model="form.TypeValue"
          :placeholder="$t('trials:readingUnit:qsList:message:msg3')"
        />
      </el-form-item>
      <!-- 小数位数 -->
      <el-form-item
        v-if="form.ClinicalTableQuestionType === 'number'"
        :label="$t('trials:readingUnit:qsList:title:digitPlaces')"
      >
        <el-radio-group
          v-model="form.DigitPlaces"
        >
          <el-radio
            v-for="item of $d.DigitPlaces"
            :key="item.id"
            :label="item.value"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 单位 -->
      <el-form-item
        v-if="form.ClinicalTableQuestionType === 'number'"
        :label="$t('trials:readingUnit:qsList:title:unit')"
      >
        <el-input
          v-model="form.Unit"
        />
      </el-form-item>
      <!-- 问题标记 -->
      <el-form-item
        :label="$t('dictionary:clinicalDataQs:title:qsMark')"
      >
        <el-select
          v-model="form.clinicalTableQuestionMarkEnum"
          @change="((val)=>{qsTypeChange(val, form)})"
        >
          <el-option
            v-for="item of $d.clinicalTableQuestionMark"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          />
        </el-select>
      </el-form-item>
      <!-- 是否必填 -->
      <el-form-item
        :label="$t('trials:readingUnit:qsList:title:isRequired')"
        prop="IsRequired"
      >
        <el-radio-group v-model="form.IsRequired">
          <el-radio v-for="item of $d.QuestionRequired" :key="`IsRequired${item.value}`" :label="item.value">{{ item.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 序号 -->
      <el-form-item :label="$t('trials:qcCfg:table:order')" 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
          size="small"
          type="primary"
          @click="close"
        >
          {{ $t('common:button:cancel') }}
        </el-button>
        <!-- 保存 -->
        <el-button size="small" type="primary" :disabled="type === 'look'" @click="save">
          {{ $t('common:button:save') }}
        </el-button>
      </el-form-item>
    </div>
  </el-form>
</template>
<script>
// import { addOrUpdateReadingTableQuestionSystem, getReadingTableOtherQuestionSystem } from '@/api/trials'
// import { getBasicConfigSelect, getCriterionDictionaryList, getCriterionDictionary } from '@/api/dictionary'
import { addOrUpdateSystemClinicalTableQuestion } from '@/api/dictionary'

export default {
  name: 'AddOrUpdateTableQs',
  props: {
    data: {
      type: Object,
      default() { return {} }
    },
    readingQuestionId: {
      type: String,
      required: true
    },
    clinicalInfo: {
      type: Object,
      default() { return {} }
    },
    clinicalId: {
      type: String,
      required: true
    },
    type: {
      type: String,
      required: true
    }
  },

  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:qcCfg:message:msg1')))
        } else {
          callback()
        }
      }
    }
    return {
      form: {
        Id: '',
        ReadingQuestionId: '',
        QuestionName: '',
        QuestionEnName: '',
        ClinicalTableQuestionType: 'select',
        TypeValue: '',
        ValueType: '',
        Unit: '',
        ParentId: '',
        ParentTriggerValue: '',
        ShowOrder: 0,
        ShowQuestion: null,
        IsRequired: true,
        Remark: '',
        RelevanceId: '',
        RelevanceValue: '',
        DataTableName: '',
        DataTableColumn: '',
        DictionaryCode: '',
        TableQuestionType: null,
        MaxRowCount: null,
        DependParentId: '',
        QuestionMark: null,
        LimitEdit: null,
        GlobalReadingShowType: null,
        // IsEnable: true
      },
      rules: {
        Type: [
          { 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' }],

        TypeValue: [{ required: true, message: this.$t('common:ruleMessage:specify'), trigger: 'blur' },
          { validator: validateTypeVal, trigger: 'blur' },
          { max: 200, message: this.$t('common:ruleMessage:maxLength') + ' 200' }],
        ShowQuestion: [{ required: true, message: this.$t('common:ruleMessage:select'), trigger: 'blur' }],
        IsRequired: [{ 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' }],
        DataTableName: [{ required: true, message: this.$t('common:ruleMessage:select'), trigger: 'blur' }],
        DataTableColumn: [{ required: true, message: this.$t('common:ruleMessage:select'), trigger: 'blur' }],
        // DictionaryCode: [{ required: true, message: '请选择', trigger: 'blur' }],
        DependParentId: [{ required: true, message: this.$t('common:ruleMessage:select'), trigger: 'blur' }]
      },
      loading: false,
      parentOptions: [],
      parentTriggerValOptions: [],
      reParentTriggerValOptions: [],
      tblOptions: [],
      colOptions: [],
      dicList: [],
      CriterionDictionaryList: []
    }
  },
  mounted() {
    this.initForm()
    // this.getCriterionDictionary()
  },
  methods: {
    // getCriterionDictionary() {
    //   getCriterionDictionary({
    //     ReadingCriterionId: this.criterionId,
    //     DictionaryCodeList: ['QuestionMark', 'OrganColumn']
    //   }).then(res => {
    //     this.CriterionDictionaryList = res.Result
    //   })
    // },
    async initForm() {
      if (Object.keys(this.data).length > 0) {
        for (const k in this.form) {
          if (this.data.hasOwnProperty(k)) {
            this.form[k] = this.data[k]
          }
        }

        if (this.form.ParentId) {
          var index = this.parentOptions.findIndex(item => {
            return item.QuestionId === this.form.ParentId
          })
          if (index !== -1) {
            if (this.parentOptions[index].QuestionGenre === 3) {
              this.parentTriggerValOptions = this.$d[this.parentOptions[index].DictionaryCode]
            } else {
              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.QuestionId === this.form.RelevanceId
          })
          if (i !== -1) {
            if (this.parentOptions[index].QuestionGenre === 3) {
              this.reParentTriggerValOptions = this.$d[this.parentOptions[index].DictionaryCode]
            } else {
              const options = []
              this.parentOptions[index].TypeValue.split('|').forEach((item, index) => {
                options.push({ id: index, label: item, value: item })
              })
              this.reParentTriggerValOptions = options
            }
          }
        }
      }
    },
    save() {
      this.$refs.tableQsForm.validate(valid => {
        if (!valid) return
        this.loading = true
        this.form.systemClinicalId = this.clinicalId
        this.form.questionId = this.readingQuestionId
        this.form.IsVerify = true
        addOrUpdateSystemClinicalTableQuestion(this.form).then(res => {
          this.$emit('getList')
          this.loading = false
          this.$emit('close')
          this.$emit('reloadArbitrationRules')
          this.$message.success(this.$t('common:message:savedSuccessfully'))
        })
          .catch((res) => {
            console.log(res)
            this.$confirm(this.$t('trials:readingUnit:qsList:message:msg4')).then(() => {
              this.form.IsVerify = false
              addOrUpdateSystemClinicalTableQuestion(this.form).then(res => {
                this.$emit('getList')
                this.loading = false
                this.$emit('close')
                this.$emit('reloadArbitrationRules')
                this.$message.success(this.$t('common:message:savedSuccessfully'))
              }).catch(() => {
                this.btnLoading = false
              })
            }).catch(() => {
              this.btnLoading = false
            })
          })
      })
    },
    isShowQuestionChange(val, form) {
      if (val === 2) {
        form.IsRequired = 2
        form.ParentId = ''
        form.ParentTriggerValue = ''
      } else {
        form.ParentId = ''
        form.ParentTriggerValue = ''
      }
    },
    isRequiredChange(val, form) {
      if (val !== 1) {
        form.RelevanceId = ''
        form.RelevanceValue = ''
      }
    },
    parentQuestionChange(val, form) {
      if (val) {
        var index = this.parentOptions.findIndex(item => {
          return item.QuestionId === val
        })
        if (index !== -1) {
          if (this.parentOptions[index].QuestionGenre === 3) {
            this.parentTriggerValOptions = this.$d[this.parentOptions[index].DictionaryCode]
          } else {
            const options = []
            this.parentOptions[index].TypeValue.split('|').forEach((item, index) => {
              options.push({ id: index, label: item, value: item })
            })
            this.parentTriggerValOptions = options
          }
        }
      }
      form.ParentTriggerValue = ''
    },
    relevanceQuestionChange(val, form) {
      if (val) {
        var index = this.parentOptions.findIndex(item => {
          return item.QuestionId === val
        })
        if (index !== -1) {
          if (this.parentOptions[index].QuestionGenre === 3) {
            this.reParentTriggerValOptions = this.$d[this.parentOptions[index].DictionaryCode]
          } else {
            const options = []
            this.parentOptions[index].TypeValue.split('|').forEach((item, index) => {
              options.push({ id: index, label: item, value: item })
            })
            this.reParentTriggerValOptions = options
          }
        }
      }
      form.RelevanceValue = ''
    },
    tableQuestionTypeChange(val, form) {
      form.DictionaryCode = ''
      form.DataTableColumn = ''
      form.DataTableName = ''
      form.DependParentId = ''
      form.TypeValue = ''
    },
    dataTableNameChange(val, form) {
      if (val) {
        var index = this.tblOptions.findIndex(item => {
          return item.Id === val
        })
        if (index !== -1) {
          this.colOptions = this.tblOptions[index].Columns
        }
      }
      form.DataTableColumn = ''
    },
    qsTypeChange(val, form) {
      form.TypeValue = ''
      form.ValueType = ''
      form.Unit = ''
      form.TableQuestionType = null
      form.DependParentId = ''
      form.DataTableColumn = ''
      form.DataTableName = ''
      form.DictionaryCode = ''
    },
    close() {
      this.$emit('close')
    }

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