<template>
  <el-form
    ref="clinicalDataForm"
    v-loading="loading"
    :model="form"
    size="small"
    :rules="rules"
    :disabled="type === 'look'"
    label-width="140px"
  >
    <div class="base-dialog-body">
      <!-- 类型 -->
      <el-form-item label="类型" prop="Type">
        <el-select
          v-model="form.Type"
          clearable
          @change="
            (val) => {
              typeChange(val, form)
            }
          "
        >
          <el-option
            v-for="item of $d.Criterion_Question_Type"
            v-show="item.value !== 'class'"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          />
        </el-select>
      </el-form-item>
      <!-- 分组名称 -->
      <el-form-item
        v-if="form.Type === 'group'"
        label="分组名称"
        prop="GroupName"
      >
        <el-input v-model="form.GroupName" />
      </el-form-item>
      
      <el-form-item
        v-if="form.Type === 'group'"
        label="分组名称（EN）"
        prop="GroupEnName"
      >
        <el-input v-model="form.GroupEnName" />
      </el-form-item>
      <el-form-item
        v-if="form.Type !== 'group'"
        label="问题名称"
        prop="QuestionName"
        :rules="[
          { required: true, message: this.$t('common:ruleMessage:specify'), trigger: 'blur' },
          { max: form.Type === 'summary' ? 300 : 100, message: `${this.$t('common:ruleMessage:maxLength')} ${form.Type === 'summary' ? 300 : 100}` }
        ]"
      >
        <el-input v-model="form.QuestionName" />
      </el-form-item>

      <el-form-item
        v-if="form.Type !== 'group'"
        label="问题名称（EN）"
        prop="QuestionEnName"
        :rules="[
          { max: form.Type === 'summary' ? 300 : 100, message: `${this.$t('common:ruleMessage:maxLength')} ${form.Type === 'summary' ? 300 : 100}` }
        ]"
      >
        <el-input v-model="form.QuestionEnName" />
      </el-form-item>
      <el-divider content-position="left">公有属性</el-divider>
      <el-form-item 
        v-if="form.Type !== 'group'" 
        label="问题分组"
        :rules="[
          { required: true, message: this.$t('common:ruleMessage:select'), trigger: 'blur' }
        ]"
      >
        <el-select
          v-model="form.GroupId"
          clearable
          :disabled="isParentExistGroup"
        >
          <el-option
            v-for="group of groupOptions"
            :key="group.GroupId"
            :label="group.GroupName"
            :value="group.GroupId"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="form.Type !== 'group'"
        label="是否显示"
        prop="ShowQuestion"
      >
        <el-radio-group
          v-model="form.ShowQuestion"
          @change="
            (val) => {
              isShowQuestionChange(val, form)
            }
          "
        >
          <el-radio
            v-for="item of $d.ShowQuestion"
            :key="`ShowQuestion${item.value}`"
            :label="item.value"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 显示时依赖父问题 -->
      <el-form-item
        v-if="form.Type !== 'group' && form.ShowQuestion === 1"
        label="显示依赖父问题"
        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.QuestionId"
          />
        </el-select>
      </el-form-item>
      <!-- 显示时依赖父问题触发值 -->
      <el-form-item
        v-if="form.ParentId && form.ShowQuestion === 1"
        label="显示触发值"
        prop="ParentTriggerValueList"
      >
        <el-select v-model="form.ParentTriggerValueList" clearable multiple>
          <el-option
            v-for="item of parentTriggerValOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value + ''"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="form.Type !== 'group' && form.Type !== 'table' && form.Type !== 'basicTable'"
        label="是否必填"
        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.Type !== 'group' && form.IsRequired === 1"
        label="必填依赖父问题"
        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.QuestionId"
          />
        </el-select>
      </el-form-item>
      <!-- 必填依赖的父问题触发值 -->
      <el-form-item
        v-if="form.RelevanceId && form.IsRequired === 1"
        label="必填触发值"
        prop="RelevanceValueList"
      >
        <el-select v-model="form.RelevanceValueList" clearable multiple>
          <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.Type === 'select' ||
          form.Type === 'radio' ||
          form.Type === 'calculation' ||
          form.Type === 'number'
        "
        label="是否裁判问题"
        prop="IsJudgeQuestion"
        :rules="[
          { required: true, message: this.$t('common:ruleMessage:select'), trigger: 'blur' }
        ]"
      >
        <el-radio-group
          v-model="form.IsJudgeQuestion"
          @change="
            (val) => {
              isJudgeQuestionChange(val, form)
            }
          "
        >
          <el-radio
            v-for="item of $d.YesOrNo"
            :key="`YesOrNo${item.value}`"
            :label="item.value"
            >{{ item.label }}</el-radio
          >
        </el-radio-group>
      </el-form-item>
      <el-form-item label="导出标识" prop="ExportIdentification">
        <el-radio-group 
          v-model="form.ExportIdentification"
          @change="
            (val) => {
              form.ExportResult = []
            }
          "
        >
          <el-radio
            v-for="item of $d.ExportIdentification"
            :key="`ExportIdentification${item.value}`"
            :label="item.value"
            >{{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="导出结果" v-if="form.ExportIdentification" prop="ExportResult">
        <el-select v-model="form.ExportResult" multiple>
          <el-option
            v-for="item in $d.ExportResult"
            :key="`ExportResult${item.value}`"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item 
        label="限制编辑" 
        v-if="form.Type === 'radio' || form.Type === 'select' || form.Type === 'input' || form.Type === 'textarea' || form.Type === 'upload' || form.Type === 'number' || form.Type === 'screenshot'"
        prop="LimitEdit"
        :rules="[
          { required: true, message: this.$t('common:ruleMessage:select'), trigger: 'blur' }
        ]"
      >
        <el-radio-group v-model="form.LimitEdit">
          <el-radio
            v-for="item of $d.LimitEdit"
            :key="`LimitEdit${item.value}`"
            :label="item.value"
            >{{ item.label }}</el-radio
          >
        </el-radio-group>
      </el-form-item>
      <el-form-item 
        label="全局阅片是否显示"
        prop="GlobalReadingShowType"
        :rules="[
          { required: true, message: this.$t('common:ruleMessage:select'), trigger: 'blur' }
        ]"
      >
        <el-radio-group v-model="form.GlobalReadingShowType">
          <el-radio
            v-for="item of $d.GlobalReadingShowType"
            :key="item.id"
            :label="item.value"
            >{{ item.label }}</el-radio
          >
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="问题标识"
        v-if="form.Type !== 'group'"
        prop="QuestionType"
      >
        <el-select v-model="form.QuestionType" clearable>
          <el-option
            v-for="item of CriterionDictionaryList.QuestionType"
            :key="item.Id"
            :value="parseInt(item.Code)"
            :label="item.ValueCN"
          />
        </el-select>
      </el-form-item>
      <el-form-item 
        label="是否在阅片页面显示"
        prop="IsShowInDicom"
        :rules="[
          { required: true, message: this.$t('common:ruleMessage:select'), trigger: 'blur' }
        ]"
      >
        <el-radio-group v-model="form.IsShowInDicom">
          <el-radio
            v-for="item of $d.YesOrNo"
            :key="`YesOrNo${item.value}`"
            :label="item.value"
            >{{ item.label }}</el-radio
          >
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="注释"
        prop="Remark"
      >
        <el-input v-model="form.Remark" />
      </el-form-item>
      <el-form-item 
        label="序号" 
        prop="ShowOrder"
        :rules="[
          { required: true, message: this.$t('common:ruleMessage:select'), trigger: 'blur' }
        ]"
      >
        <el-input-number
          v-model="form.ShowOrder"
          controls-position="right"
          :min="0"
        />
      </el-form-item>
      <!-- 适用于Lugano 2014标准 -->
      <el-form-item label="问题分类" v-if="form.Type !== 'group' && criterionType === 2">
        <el-select v-model="form.QuestionClassify" clearable>
          <el-option
            v-for="item of $d.QuestionClassify"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
       <!-- 适用于iRECST标准 -->
      <el-form-item label="转化显示类型" prop="ConvertShowType" v-if="criterionType === 3">
        <el-radio-group v-model="form.ConvertShowType">
          <el-radio
            v-for="item of $d.ConvertShowType"
            :key="item.id"
            :label="item.value"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-divider content-position="left">私有属性</el-divider>
      <el-form-item
        v-if="
          form.Type === 'select' ||
          form.Type === 'radio' ||
          form.Type === 'calculation'
        "
        label="选项类型"
        prop="QuestionGenre"
        :rules="[{ required: form.Type !== 'calculation', message: '请选择' }]"
      >
        <el-radio-group
          v-model="form.QuestionGenre"
          @change="
            (val) => {
              questionGenreChange(val, form)
            }
          "
        >
          <el-radio :label="-1"> 无 </el-radio>
          <el-radio
            v-for="item of $d.TableQuestionType"
            v-show="item.value === 0 || item.value === 3"
            :key="item.id"
            :label="item.value"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item
        v-if="form.QuestionGenre === 0 || form.Type === 'class'"
        label="选项"
        prop="TypeValue"
      >
        <el-input
          v-model="form.TypeValue"
          placeholder="选项请用‘|’分割多个选项"
          @change="typeValueChange"
        />
      </el-form-item>
      
      
      <el-form-item
        v-if="form.QuestionGenre === 3"
        label="关联字典"
        prop="DictionaryCode"
      >
        <el-select
          v-model="form.DictionaryCode"
          clearable
          @change="
            () => {
              form.DefaultValue = null
            }
          "
        >
          <el-option
            v-for="item of dicList"
            :key="item.Id"
            :label="item.Code"
            :value="item.Code"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="form.QuestionGenre === 3" label="默认值">
        <el-select v-model="form.DefaultValue" clearable>
          <el-option
            v-for="item of form.DictionaryCode ? $d[form.DictionaryCode] : []"
            :key="item.id"
            :label="item.label"
            :value="item.value.toString()"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="form.QuestionGenre === 0" label="默认值">
        <el-select v-model="form.DefaultValue" clearable>
          <el-option
            v-for="item of form.TypeValue ? form.TypeValue.split('|') : []"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="form.Type === 'select' || form.Type === 'radio'"
        label="高亮标记值"
        prop="HighlightAnswerList"
      >
        <el-select v-model="form.HighlightAnswerList" clearable multiple>
          <template v-if="form.TypeValue">
            <el-option
              v-for="item of form.TypeValue.split('|')"
              :key="item"
              :label="item"
              :value="item"
            />
          </template>
          <template v-else-if="form.DictionaryCode">
            <el-option
              v-for="item of highlightAnswers"
              :key="item.Id"
              :label="item.ValueCN"
              :value="item.Code"
            />
          </template>
        </el-select>
      </el-form-item>
      <el-form-item
        label="分组标识"
        v-if="form.Type === 'group'"
        prop="GroupClassify"
      >
        <el-select v-model="form.GroupClassify" clearable>
          <el-option
            v-for="item of groupClassifyList"
            :key="item.Id"
            :value="parseInt(item.Code)"
            :label="item.ValueCN"
          />
        </el-select>
      </el-form-item>
      <el-form-item 
        v-if="form.Type === 'input' || form.Type === 'textarea'"
        label="最大长度">
        <el-input-number v-model="form.MaxAnswerLength" :min="0"></el-input-number>
      </el-form-item>
      <el-form-item v-if="form.Type === 'table' || form.Type === 'basicTable'" label="最大行数">
        <el-input-number
          v-model="form.MaxQuestionCount"
          controls-position="right"
          :min="0"
          :max="10"
        />
      </el-form-item>
      <el-form-item v-if="form.Type === 'table' || form.Type === 'basicTable'" label="自增序号前缀">
        <el-input v-model="form.OrderMark" />
      </el-form-item>
      
      <!-- 数值类型 -->
      <el-form-item
        v-if="form.Type === 'number' || form.Type === 'calculation'"
        label="数值类型"
        prop="ValueType"
        :rules="[{ required: true, message: '请选择' }]"
      >
        <el-radio-group v-model="form.ValueType">
          <el-radio
            v-for="item of $d.ValueType"
            :key="item.id"
            :label="item.value"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 数值单位 -->
      <el-form-item
        v-if="form.Type === 'number' || form.Type === 'calculation'"
        label="单位"
      >
        <el-radio-group v-model="form.Unit">
          <el-radio
            v-for="item of $d.ValueUnit"
            :key="item.id"
            :label="item.value"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        v-if="form.Type === 'table' || form.Type === 'basicTable'"
        label="表格类型标识"
        prop="LesionType"
      >
        <el-select v-model="form.LesionType" clearable>
          <el-option
            v-for="item of lesionTypes"
            :key="item.Code"
            :value="parseInt(item.Code)"
            :label="$fd('LesionType', parseInt(item.Code))"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="form.Type === 'basicTable'"
        label="表格类型标识"
        prop="LesionType"
      >
        <el-select v-model="form.LesionType" clearable>
          <el-option
            v-for="item of lesionTypeList"
            :key="item.Id"
            :value="parseInt(item.Code)"
            :label="item.ValueCN"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="form.Type === 'upload'" label="最大上传个数">
        <el-input-number
          v-model="form.ImageCount"
          controls-position="right"
          :min="0"
          :max="10"
        />
      </el-form-item>
      <!-- 文件类型 -->
      <el-form-item 
        v-if="form.Type === 'upload'" 
        label="文件类型"
        prop="FileType"
        :rules="[{ type: 'array', required: true, message: this.$t('common:ruleMessage:specify'), trigger: [ 'change'] }]"
      >
        <el-checkbox-group
          v-model="form.FileType"
          @change="(v) => {
            if (v && v.includes('-1')) {
              form.FileType = ['-1']
            }
          }"
        >
          <el-checkbox
            v-for="item of $d.fileType"
            :key="`fileType${item.value}`"
            :value="item.value + ''"
            :label="item.value"
            :disabled="form.FileType && form.FileType.includes('-1') && item.value !== '-1'"
          >
            {{ item.label }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <!-- 分类 -->
      <el-form-item
        v-if="form.Type === 'class'"
        label="分类数据来源"
        prop="ClassifyQuestionId"
      >
        <el-select v-model="form.ClassifyQuestionId" clearable>
          <el-option v-for="item of Questions" :key="item.QuestionId" :label="item.QuestionName"
                     :value="item.QuestionId"/>
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="form.Type === 'class'"
        label="分类算法"
        prop="ClassifyAlgorithms"
      >
        <div>
          <el-table
            ref="CalculateTable"
            :data="ClassifyAlgorithmsList"
            style="margin: 10px;width: 100%"
            size="small"
          >
            <!-- 运算类型 -->
            <el-table-column
              :label="$t('trials:readingUnit:label:label')"
              show-overflow-tooltip
              min-width="70"
            >
              <template slot-scope="scope">
                {{ scope.row.label }}
              </template>
            </el-table-column>
            <!-- 运算类型 -->
            <el-table-column
              :label="$t('trials:readingUnit:label:gt')"
              show-overflow-tooltip
              min-width="128"
            >
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.gt"></el-input-number>
              </template>
            </el-table-column>
            <!-- 运算类型 -->
            <el-table-column
              :label="$t('trials:readingUnit:label:lt')"
              show-overflow-tooltip
              min-width="128"
            >
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.lt"></el-input-number>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </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 {
  getBasicConfigSelect,
  addOrUpdateReadingQuestionSystem,
  getSystemCriterionOtherQuestion,
  getSystemGroupNameList,
  getCriterionDictionary,
  getCriterionDictionaryList,
  getSystemCalculateQuestions
} from '@/api/dictionary'
import { getCriterionLesionType } from '@/api/trials'
export default {
  name: 'CriterionQuestionForm',
  props: {
    data: {
      type: Object,
      default() {
        return {}
      },
    },
    type: {
      type: String,
      default() {
        return ''
      },
    },
    criterionType: {
      type: Number,
      required: true
    },
    criterionId: {
      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('选项不允许存在相同值'))
        } else {
          callback()
        }
      }
    }
    return {
      ClassifyAlgorithmsList: [],
      validateTypeVal: validateTypeVal,
      form: {
        Id: '',
        ReadingQuestionCriterionSystemId: '',
        QuestionName: '',
        QuestionEnName: '',
        Type: 'input',
        ValueType: '',
        Unit: '',
        QuestionGenre: '',
        TypeValue: '',
        DictionaryCode: '',
        ParentId: '',
        ParentTriggerValue: '',
        ParentTriggerValueList: [],
        ShowOrder: 0,
        ShowQuestion: 0,
        IsRequired: 2,
        IsJudgeQuestion: false,
        GroupName: '',
        GroupEnName: '',
        GroupClassify: null,
        Remark: '',
        ImageCount: 0,
        RelevanceId: '',
        RelevanceValue: '',
        RelevanceValueList: [],
        LesionType: '',
        QuestionType: null,
        IsShowInDicom: false,
        OrderMark: '',
        MaxQuestionCount: 0,
        GlobalReadingShowType: 3,
        DefaultValue: null,
        LimitEdit: 0,
        GroupId: null,
        ConvertShowType: 0,
        QuestionClassify: null,
        HighlightAnswerList: [],
        ExportIdentification: 0,
        ExportResult: [],
        MaxAnswerLength: 500,
        FileType: [],
        ClassifyQuestionId: null,
        ClassifyAlgorithms: null,
      },
      rules: {
        Type: [{ required: true, message: '请选择', trigger: 'blur' }],
        LesionType: [{ required: true, message: '请选择', trigger: 'blur' }],
        // QuestionName: [
        //   { required: true, message: '请注明', trigger: 'blur' },
        //   { max: 300, message: '最大长度为 300' },
        // ],
        QuestionGenre: [{ required: true, message: '请选择', trigger: 'blur' }],
        TypeValue: [
          { required: true, message: '请注明', trigger: 'blur' },
          { validator: validateTypeVal, trigger: 'blur' },
          { max: 500, message: '最大长度为 500' },
        ],
        DictionaryCode: [
          { required: true, message: '请选择', trigger: 'blur' },
        ],
        ShowQuestion: [{ required: true, message: '请选择', trigger: 'blur' }],
        IsRequired: [{ required: true, message: '请选择', trigger: 'blur' }],
        ParentId: [{ required: true, message: '请选择', trigger: 'blur' }],
        ParentTriggerValueList: [
          { required: true, message: '请选择', trigger: 'blur' },
        ],
        RelevanceId: [{ required: true, message: '请选择', trigger: 'blur' }],
        RelevanceValueList: [
          { required: true, message: '请选择', trigger: 'blur' },
        ],
        GroupName: [
          { required: true, message: '请注明', trigger: 'blur' },
          { max: 50, message: '最大长度为 50' },
        ],
        ExportIdentification: [
          { required: true, message: '请选择', trigger: 'blur' },
        ],
        ExportResult: [
          { required: true, message: '请选择', trigger: 'blur' },
        ]
      },
      loading: false,
      btnLoading: false,
      parentOptions: [],
      parentTriggerValOptions: [],
      groupOptions: [],
      isParentExistGroup: false,
      lesionTypes: [],
      dicList: [],
      CriterionDictionaryList: [],
      groupClassifyList: [],
      highlightAnswers: [],
      lesionTypeList: [],
      Questions: []
    }
  },
  watch: {
    'form.DictionaryCode': {
      deep: true,
      immediate: true,
      async handler(v, oldv) {
        try {
          if (!v) {
            this.highlightAnswers = []
            return
          }
          let res = await getCriterionDictionary({
            ReadingCriterionId: this.data.ReadingQuestionCriterionSystemId,
            DictionaryCode: this.form.DictionaryCode,
          })
          this.highlightAnswers = res.Result[this.form.DictionaryCode]
        } catch (e) {
          console.log(e)
        }
      },
    },
  },
  mounted() {
    this.initForm()
    this.getCalculateQuestions('number')
  },
  methods: {
    typeValueChange(v) {
      this.form.DefaultValue = null
      var list = v.split('|')
      this.form.ClassifyAlgorithms = null
      var arr = Object.assign([], this.ClassifyAlgorithmsList)
      this.ClassifyAlgorithmsList = list.map((res, i) => {
        return {
          label: res,
          lt: arr[i] ? arr[i].lt : 0,
          gt: arr[i] ? arr[i].gt : 0
        }
      })
    },
    getCalculateQuestions(type) {
      getSystemCalculateQuestions({
        systemCriterionId: this.criterionId,
        type: type
      }).then(res => {
        if (type === 'number') {
          this.Questions = res.Result
        }
      })
    },
    getCriterionDictionary() {
      getCriterionDictionary({
        ReadingCriterionId: this.data.ReadingQuestionCriterionSystemId,
        DictionaryCode: 'QuestionType',
      }).then((res) => {
        this.CriterionDictionaryList = res.Result
      })
    },
    getGroupClassifyDictionary() {
      getCriterionDictionary({
        ReadingCriterionId: this.data.ReadingQuestionCriterionSystemId,
        DictionaryCode: 'GroupClassify',
      }).then((res) => {
        this.groupClassifyList = res.Result.GroupClassify
      })
    },
    getLesionTypeDictionary() {
      getCriterionDictionary({
        ReadingCriterionId: this.data.ReadingQuestionCriterionSystemId,
        DictionaryCode: 'LesionType',
      }).then((res) => {
        this.lesionTypeList = res.Result.LesionType
      })
    },
    async initForm() {
      await this.getGroupOptions()
      await this.getParentQuestions()
      await this.getLesionTypeDictionary()
      await this.getLesionType()
      if (Object.keys(this.data).length > 0) {
        for (const k in this.form) {
          if (this.data.hasOwnProperty(k)) {
            if (k === 'ClassifyAlgorithms' && this.data[k] !== undefined && this.data[k] !== '') {
              this.ClassifyAlgorithmsList = JSON.parse(this.data[k])
            } else if(k === 'FileType'){
              this.form[k] = this.data[k].split(',')
            } else {
              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.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 index = this.parentOptions.findIndex((item) => {
            return item.QuestionId === this.form.RelevanceId
          })
          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
            }
          }
        }
      }
      this.getCriterionDictionary()
      this.getGroupClassifyDictionary()
    },
    save() {
      this.$refs.clinicalDataForm.validate((valid) => {
        if (!valid) return
        this.btnLoading = true
        this.form.ClassifyAlgorithms = JSON.stringify(this.ClassifyAlgorithmsList)
        if (this.form.Type !== 'upload') {
          this.form.ImageCount = 0
        }
        var params = Object.assign({}, this.form)
        params.FileType = this.form.FileType.join(',')
        addOrUpdateReadingQuestionSystem(params)
          .then((res) => {
            this.btnLoading = false
            this.$emit('getList')
            this.$emit('close')
            this.$message.success(this.$t('common:message:savedSuccessfully'))
          })
          .catch(() => {
            this.btnLoading = false
          })
      })
    },
    getGroupOptions() {
      return new Promise((resolve, reject) => {
        this.loading = true
        var param = {
          criterionId: this.data.ReadingQuestionCriterionSystemId,
        }
        getSystemGroupNameList(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 = {
          readingQuestionCriterionSystemId:
            this.data.ReadingQuestionCriterionSystemId,
          id: this.data.Id,
        }
        getSystemCriterionOtherQuestion(param)
          .then((res) => {
            this.parentOptions = res.Result
            this.loading = false
            resolve()
          })
          .catch(() => {
            this.loading = false
            reject()
          })
      })
    },
    questionGenreChange(val, form) {
      form.DictionaryCode = ''
      form.TypeValue = ''
    },
    // parentQuestionChange(val, form) {
    //   this.isParentExistGroup = false
    //   if (val) {
    //     var index = this.parentOptions.findIndex(item => {
    //       return item.QuestionId === val
    //     })
    //     if (index !== -1) {
    //       this.parentTriggerValOptions = this.parentOptions[index].TypeValue.split('|')
    //       if (this.parentOptions[index].GroupName) {
    //         this.isParentExistGroup = true
    //         form.GroupName = this.parentOptions[index].GroupName
    //       }
    //     }
    //   } else {
    //     form.ParentTriggerValue = ''
    //     form.GroupName = ''
    //   }
    // },
    typeChange(val, data) {
      if (val !== 'select' && val !== 'radio') {
        data.IsJudgeQuestion = false
      }
      if (val === 'table' || val === 'basicTable') {
        data.IsRequired = 2
      } else {
        data.LesionType = null
      }
      data.DictionaryCode = ''
      data.TypeValue = ''
      data.ValueType = ''
      data.Unit = ''
    },
    isShowQuestionChange(val, form) {
      if (this.form.Type === 'table' || this.form.Type === 'basicTable') return
      if (this.form.Type === 'group') {
        form.QuestionName = ''
        return
      }
      if (val === 2) {
        form.IsRequired = 2
        form.ParentId = ''
        form.ParentTriggerValueList = []
        this.isParentExistGroup = false
      } else if (val === 1) {
        form.ParentId = ''
        form.ParentTriggerValueList = []
        form.GroupName = ''
        form.GroupEnName = ''
        this.isParentExistGroup = true
      } else if (val === 0) {
        form.ParentId = ''
        form.ParentTriggerValueList = []
        this.isParentExistGroup = false
      }
    },
    isRequiredChange(val, form) {
      if (val !== 1) {
        form.RelevanceId = ''
        form.RelevanceValue = ''
      }
    },
    parentQuestionChange(val, form) {
      this.isParentExistGroup = false
      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 {
            var options = []
            this.parentOptions[index].TypeValue.split('|').forEach(
              (item, index) => {
                options.push({ id: index, label: item, value: item })
              }
            )
            this.parentTriggerValOptions = options
          }
          if (this.parentOptions[index].GroupName) {
            this.isParentExistGroup = true
            form.GroupName = this.parentOptions[index].GroupName
          }
        }
      } else {
        form.GroupName = ''
        form.GroupEnName = ''
      }
      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 {
            var options = []
            this.parentOptions[index].TypeValue.split('|').forEach(
              (item, index) => {
                options.push({ id: index, label: item, value: item })
              }
            )
            this.reParentTriggerValOptions = options
          }
        }
      }
      form.RelevanceValue = ''
    },
    isJudgeQuestionChange(val, form) {
      if (val) {
        form.IsRequired = 0
      }
    },
    getLesionType() {
      return new Promise((resolve, reject) => {
        this.loading = true
        var param = {
          SystemCriterionId: this.data.ReadingQuestionCriterionSystemId,
        }
        getCriterionLesionType(param)
          .then((res) => {
            this.lesionTypes = res.Result
            this.loading = false
            resolve()
          })
          .catch(() => {
            this.loading = false
            reject()
          })
      })
    },
    close() {
      this.$emit('close')
    },
  },
}
</script>
<style lang="scss" scoped>
</style>
