<template>
  <el-form
    ref="qsForm"
    v-loading="loading"
    :model="form"
    size="small"
    :rules="rules"
    label-width="280px"
    :disabled="isLook"
  >
    <div class="base-dialog-body">
      <!-- 题型 -->
      <el-form-item :label="$t('trials:readingUnit:qsList:title:type')" prop="Type">
        <el-select
          v-model="form.Type"
          clearable
          @change="((val)=>{qsTypeChange(val, form)})"
        >
          <el-option
            v-for="item of $d.Criterion_Question_Type"
            v-show="item.value !== 'calculation' && item.value !== 'increment'"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          />
        </el-select>
      </el-form-item>
      <!-- 分组名称 -->
      <el-form-item
        v-if="(form.Type === 'group' && !isLook) || (isLook && $i18n.locale !== 'en')"
        :label="$t('trials:readingUnit:qsList:title:groupName')"
        prop="GroupName"
      >
        <el-input
          v-model="form.GroupName"
        />
      </el-form-item>
      <!-- 分组名称(En) -->
      <el-form-item
        v-if="(form.Type === 'group' && !isLook) || (isLook && $i18n.locale !== 'zh')"
        :label="$t('trials:readingUnit:qsList:title:groupNameEn')"
        prop="GroupEnName"
      >
        <el-input
          v-model="form.GroupEnName"
        />
      </el-form-item>
      <!-- 问题名称 -->
      <el-form-item
        v-if="(form.Type !== 'group' && !isLook) || (isLook && $i18n.locale !== 'en')"
        :label="$t('trials:readingUnit:qsList:title:qsName')"
        prop="QuestionName"
      >
        <el-input
          v-model="form.QuestionName"
        />
      </el-form-item>
      <!-- 问题名称(En) -->
      <el-form-item
        v-if="(form.Type !== 'group' && !isLook) || (isLook && $i18n.locale !== 'zh')"
        :label="$t('trials:readingUnit:qsList:title:qsNameEn')"
        prop="QuestionEnName"
      >
        <el-input
          v-model="form.QuestionEnName"
        />
      </el-form-item>
      <!-- 最大上传个数 -->
      <el-form-item v-if="form.Type === 'upload'" :label="$t('trials:readingUnit:qsList:title:imageCount')">
        <el-input-number
          v-model="form.ImageCount"
          controls-position="right"
          :min="1"
          :max="10"
        />
      </el-form-item>
      <!-- 文件类型 -->
      <el-form-item v-if="form.Type === 'upload'" :label="$t('trials:readingUnit:qsList:title:FileType')"
                    prop="DataSource">
        <el-checkbox-group
          v-model="form.FileType"
          @change="(v) => {
            if (v.includes('-1')) {
              form.FileType = ['-1']
            } else {
            }
          }"
        >
          <el-checkbox
            v-for="item of $d.fileType"
            :key="`fileType${item.value}`"
            :value="item.value + ''"
            :label="item.value"
            :disabled="form.FileType.includes('-1') && item.value !== '-1'"
          >
            {{ item.label }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <!-- 最大字符数 -->
      <el-form-item v-if="form.Type === 'input' || form.Type === 'textarea'"
                    :label="$t('trials:readingUnit:qsList:title:MaxAnswerLength')">
        <el-input v-model="form.MaxAnswerLength"/>
      </el-form-item>
      <!-- 自增序号前缀 -->
      <el-form-item v-if="form.Type === 'table'" :label="$t('trials:readingUnit:qsList:title:orderMark')">
        <el-input v-model="form.OrderMark"/>
      </el-form-item>
      <!-- 最大行数 -->
      <el-form-item v-if="form.Type === 'table'" :label="$t('trials:readingUnit:qsList:title:maxQuestionCount')">
        <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'" :label="$t('trials:readingUnit:qsList:title:isCopyLesions')">
        <el-switch
          v-model="form.IsCopyLesions"
        />
      </el-form-item>
      <!-- 问题数据来源 -->
      <el-form-item v-if="form.Type === 'number'" :label="$t('trials:readingUnit:qsList:title:dataSource')"
                    prop="DataSource">
        <el-radio-group
          v-model="form.DataSource"
        >
          <el-radio
            v-for="item of $d.DataSource"
            :key="`DataSource${item.value}`"
            :label="item.value"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 数值类型 -->
      <el-form-item
        v-if="form.Type === 'number'"
        :label="$t('trials:readingUnit:qsList:title:valueType')"
        prop="ValueType"
        :rules="[
          { required: true, message: this.$t('common:ruleMessage:specify')}
        ]"
      >
        <el-radio-group
          v-model="form.ValueType"
        >
          <el-radio
            v-for="item of $d.ValueType"
            v-show="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.Type === 'number' && form.ValueType === 1"
        :label="$t('trials:readingUnit:qsList:title:digitPlaces')"
        prop="ValueType"
        :rules="[
          { required: true, message: this.$t('common:ruleMessage:select')}
        ]"
      >
        <el-input :value="$fd('DigitPlaces', ValueType).toString()" :disabled="true"/>
      </el-form-item>
      <!-- 单位 -->
      <el-form-item
        v-if="form.Type === 'number'"
        :label="$t('trials:readingUnit:qsList:title:unit')"
        prop="Unit"
        :rules="[
          { required: true, message: this.$t('common:ruleMessage:select')}
        ]"
      >
        <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 === 'number' && form.Unit === 4"
        :label="$t('trials:readingUnit:qsList:title:customUnit')"
        prop="CustomUnit"
        :rules="[
          { required: true, message: this.$t('common:ruleMessage:select')}
        ]"
      >
        <el-input v-model="form.CustomUnit"/>
      </el-form-item>
      <div v-if="form.Type === 'number' && form.DataSource === 1"
           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.CustomCalculateMark"
                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.CustomCalculateMark"
                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 slot-scope="scope">
              {{
                scope.$index === 0 && [1, 2, 3, 4].includes(form.CustomCalculateMark) ? null : $fd('CustomCalculateMark', form.CustomCalculateMark)
              }}
            </template>
          </el-table-column>
          <!-- 表格名称 -->
          <el-table-column
            v-if="form.CustomCalculateMark > 4"
            :label="$t('trials:readingUnit:qsList:title:tableName')"
            prop="QuestionId"
            show-overflow-tooltip
            min-width="180"
          >
            <template slot-scope="scope">
              <el-select v-model="scope.row.QuestionId" clearable :disabled="!scope.row.IsTable">
                <el-option v-for="item of tableQuestions" :key="item.QuestionId" :label="item.QuestionName"
                           :value="item.QuestionId"/>
              </el-select>
            </template>
          </el-table-column>
          <!-- 问题名称 -->
          <el-table-column
            :label="$t('trials:readingUnit:qsList:title:qsName')"
            prop="TableQuestionId"
            show-overflow-tooltip
            min-width="180"
          >
            <template slot-scope="scope">
              <el-select v-if="!scope.row.IsTable" v-model="scope.row.TableQuestionId" clearable>
                <el-option v-for="item of Questions" :key="item.QuestionId" :label="item.QuestionName"
                           :value="item.QuestionId"/>
              </el-select>
              <el-select v-if="scope.row.IsTable" v-model="scope.row.TableQuestionId" clearable>
                <el-option
                  v-for="item of !scope.row.QuestionId ? [] : tableQuestions.find(v => v.QuestionId === scope.row.QuestionId).TableQuestions"
                  :key="item.QuestionId" :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 style="font-size: 12px;color:#666;padding: 0 15px 0;text-align: right">
          <!-- '请选择同级问题！': '请选择表格问题下的子问题！' -->
          <i class="el-icon-info"/>{{
            [1, 2, 3, 4].includes(form.CustomCalculateMark) ? $t('trials:readingUnit:qsList:message:msg1') : $t('trials:readingUnit:qsList:message:msg2')
          }}
        </div>
      </div>
      <!-- 选项类型 -->
      <el-form-item
        v-if="(form.Type === 'select' || form.Type === 'radio' || form.Type === 'calculation') && isFromSystem"
        :label="$t('trials:readingUnit:label:QuestionGenre')"
        prop="QuestionGenre"
        :rules="[
          { required: form.Type !== 'calculation', message: '请选择'}
        ]"
      >
        <el-radio-group
          v-model="form.QuestionGenre"
          @change="((val)=>{questionGenreChange(val, form)})"
        >
          <el-radio
            :label="-1"
          >
            {{ $i18n.locale === 'zh' ? '无' : 'None' }}
          </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="(!isFromSystem || (isFromSystem && form.QuestionGenre !== 3)) && (form.Type === 'select' || form.Type === 'radio' || form.Type === 'calculation' || form.Type === 'class')"
        :label="$t('trials:qcCfg:table:typeValue')"
        prop="TypeValue"
      >
        <el-input
          v-model="form.TypeValue"
          @change="typeValueChange"
          :placeholder="$t('trials:qcCfg:message:typeValue')"
        />
      </el-form-item>
      <el-form-item
        v-if="form.Type === 'class'"
        :label="$t('trials:readingUnit:label:ClassifyQuestion')"
        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="$t('trials:readingUnit:label:ClassifyAlgorithms')"
        prop="ClassifyAlgorithms"
      >
        <div>
          <el-table
            ref="CalculateTable"
            :data="ClassifyAlgorithmsList"
            style="margin: 10px;width: calc(100% - 20px)"
            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>
      <el-form-item
        v-if="form.QuestionGenre === 3 && isFromSystem"
        :label="$t('trials:readingUnit:label:DictionaryCode')"
        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 && (form.Type === 'select' || form.Type === 'radio')  && isFromSystem"
        :label="$t('trials:qcCfg:table:typeValue')"
      >
        <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 || form.QuestionGenre === null) && (form.Type === 'select' || form.Type === 'radio') && isFromSystem"
        :label="$t('trials:qcCfg:table:typeValue')"
      >
        <el-select v-model="form.DefaultValue" clearable>
          <el-option
            v-for="item of form.TypeValue ? form.TypeValue.split('|') : []"
            :key="'TypeValue' + item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <!-- 分组 -->
      <el-form-item
        v-if="form.Type !== 'group'"
        :label="$t('trials:readingUnit:qsList:title:groupName')"
      >
        <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 :label="$t('trials:readingUnit:qsList:title:isShow')" 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.Type !== 'table' && form.Type !== 'summary' || form.Type === 'class'"
        :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.ShowQuestion===1"
        :label="$t('trials:readingUnit:qsList:title:parentId')"
        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="$t('trials:readingUnit:qsList:title:parentTriggerValueList')" 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.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.QuestionId"
          />
        </el-select>
      </el-form-item>
      <!-- 必填触发值 -->
      <el-form-item
        v-if="form.RelevanceId && form.IsRequired === 1"
        :label="$t('trials:readingUnit:qsList:title:relevanceValueList')"
        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 :label="$t('trials:readingUnit:qsList:title:order')" prop="ShowOrder">
        <el-input-number
          v-model="form.ShowOrder"
          controls-position="right"
          :min="0"
          :max="1000"
        />
      </el-form-item>
      <!-- 是否在影像页面显示 -->
      <el-form-item :label="$t('trials:readingUnit:qsList:title:isShowInDicom')" v-if="form.ShowQuestion !== 2">
        <el-radio-group v-model="form.IsShowInDicom">
          <el-radio
            v-for="item of $d.YesOrNo"
            :key="'IsShowInDicom'+item.value"
            :label="item.value"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 是否裁判问题 -->
      <el-form-item v-if="form.Type === 'select' || form.Type === 'radio' || form.Type === 'number'"
                    :label="$t('trials:readingUnit:qsList:title:isJudgeQuestion')">
        <el-radio-group
          v-model="form.IsJudgeQuestion"
          @change="((val)=>{isJudgeQuestionChange(val, form)})"
        >
          <el-radio
            v-for="item of $d.YesOrNo"
            :key="'IsJudgeQuestion'+item.value"
            :label="item.value"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 限制显示 -->
      <el-form-item :label="$t('trials:readingUnit:qsList:title:LimitShow')">
        <el-radio-group v-model="form.LimitShow" @change="(v) => {
          if (v !== 0) {
             form.LimitEdit = v
          }
        }">
          <el-radio v-for="item of $d.LimitShow" :key="item.id" :label="item.value">{{ item.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 限制编辑 -->
      <el-form-item :label="$t('trials:readingUnit:qsList:title:limitEdit')">
        <el-radio-group v-model="form.LimitEdit" :disabled="form.LimitShow !== 0">
          <el-radio v-for="item of $d.LimitEdit" :key="item.id" :label="item.value">{{ item.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 全局阅片是否显示 -->
      <el-form-item :label="$t('trials:readingUnit:qsList:title:globalReadingShowType')">
        <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="$t('trials:readingUnit:qsList:title:Remark')"
        prop="Remark"
      >
        <!-- 选项请用‘|’分割多个选项 -->
        <el-input
          v-model="form.Remark"
        />
      </el-form-item>
    </div>
    <div class="base-dialog-footer" style="text-align:right;margin-top:10px;">
      <el-form-item v-if="!isLook">
        <!-- 取消 -->
        <el-button
          size="small"
          type="primary"
          @click="close"
        >
          {{ $t('common:button:cancel') }}
        </el-button>
        <!-- 保存 -->
        <el-button size="small" type="primary" @click="save">
          {{ $t('common:button:save') }}
        </el-button>
      </el-form-item>
    </div>
  </el-form>
</template>
<script>
import {
  getCalculateQuestions,
  addOrUpdateReadingQuestionTrial,
  getTrialCriterionOtherQuestion,
  getTrialGroupNameList,
  getCriterionLesionType
} from '@/api/trials'
import {getBasicConfigSelect, getCriterionDictionaryList} from '@/api/dictionary'

export default {
  name: 'AddOrUpdateClinicalData',
  props: {
    digitPlaces: {
      type: Number,
      default() {
        return 0
      }
    },
    list: {
      type: Array,
      default() {
        return []
      }
    },
    trialCriterionId: {
      type: String,
      default() {
        return ''
      }
    },
    data: {
      type: Object,
      default() {
        return {}
      }
    },
    isFromSystem: {
      type: Boolean,
      default: true
    },
    isLook: {
      type: Boolean,
      default: 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:readingUnit:qsList:message:msg0')))
        } else {
          callback()
        }
      }
    }
    return {
      ClassifyAlgorithmsList: [],
      form: {
        Id: '',
        ReadingQuestionCriterionTrialId: '',
        QuestionName: '',
        QuestionEnName: '',
        Type: 'select',
        TypeValue: '',
        ParentId: '',
        ParentTriggerValueList: [],
        ShowOrder: 0,
        ShowQuestion: 0,
        IsRequired: 2,
        IsJudgeQuestion: false,
        GroupName: '',
        GroupEnName: '',
        Remark: '',
        ImageCount: 1,
        RelevanceId: '',
        RelevanceValueList: [],
        LesionType: '',
        QuestionType: null,
        QuestionGenre: null,
        IsShowInDicom: false,
        CalculateQuestions: [],
        CustomCalculateMark: '',
        DataSource: 0,
        GlobalReadingShowType: 3,
        CustomUnit: null,
        ValueType: null,
        Unit: null,
        LimitEdit: 0,
        DefaultValue: null,
        OrderMark: null,
        MaxQuestionCount: null,
        IsCopyLesions: false,
        MaxAnswerLength: null,
        FileType: [],
        DictionaryCode: null,
        GroupId: null,
        ClassifyQuestionId: null,
        ClassifyAlgorithms: null,
        LimitShow: 0
        // IsEnable: true
      },
      rules: {
        Type: [
          {required: true, message: this.$t('common:ruleMessage:select'), trigger: ['blur', 'change']}
        ],
        QuestionName: [{required: true, message: this.$t('common:ruleMessage:specify'), trigger: ['blur', 'change']},
          {max: 50, message: `${this.$t('common:ruleMessage:maxLength')} 50`}],
        TypeValue: [{required: true, message: this.$t('common:ruleMessage:specify'), trigger: ['blur', 'change']},
          {validator: validateTypeVal, trigger: ['blur', 'change']},
          {max: 200, message: `${this.$t('common:ruleMessage:maxLength')} 200`}],
        ShowQuestion: [{required: true, message: this.$t('common:ruleMessage:select'), trigger: ['blur', 'change']}],
        IsRequired: [{required: true, message: this.$t('common:ruleMessage:select'), trigger: ['blur', 'change']}],
        ParentId: [{required: true, message: this.$t('common:ruleMessage:select'), trigger: ['blur', 'change']}],
        ParentTriggerValueList: [
          {required: true, message: this.$t('common:ruleMessage:select'), trigger: ['blur', 'change']}
        ],
        RelevanceId: [{required: true, message: this.$t('common:ruleMessage:select'), trigger: ['blur', 'change']}],
        RelevanceValueList: [{
          required: true,
          message: this.$t('common:ruleMessage:select'),
          trigger: ['blur', 'change']
        }],
        GroupName: [{required: true, message: this.$t('common:ruleMessage:specify'), trigger: ['blur', 'change']},
          {max: 50, message: `${this.$t('common:ruleMessage:maxLength')} 50`}]
      },
      loading: false,
      dicList: [],
      parentOptions: [],
      parentTriggerValOptions: [],
      reParentTriggerValOptions: [],
      groupOptions: [],
      isParentExistGroup: false,
      lesionTypes: [],
      Questions: [],
      tableQuestions: [],
      isShow: true
    }
  },
  watch: {
    'form.CustomCalculateMark'() {
      // this.$refs.CalculateTable.doLayout()
    }
  },
  mounted() {
    this.initForm()
    this.getBasicConfigSelect()
    this.getCalculateQuestions('number')
    this.getCalculateQuestions('table')
  },
  methods: {
    typeValueChange(v) {
      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
        }
      })
    },
    getBasicConfigSelect() {
      // getBasicConfigSelect('Reading_eCRF_Criterion').then(res => {
      //   this.dicList = res.Result
      // })
      // getCriterionDictionaryList({
      //   CriterionId: this.data.ReadingQuestionCriterionSystemId,
      //   SystemCriterionId: this.data.ReadingQuestionCriterionSystemId
      // }).then(res => {
      //   this.dicList = res.Result
      // })
    },
    deleteCustomCalculateMark(index) {
      this.form.CalculateQuestions.splice(index, 1)
    },
    addCustomCalculateMark(index) {
      this.form.CalculateQuestions.splice(index + 1, 0, {
        IsTable: false,
        QuestionId: null,
        TableQuestionId: null
      })
    },
    CustomCalculateMarkChange() {
      this.isShow = false
      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
      })
    },
    getCalculateQuestions(type) {
      getCalculateQuestions({
        TrialCriterionId: this.trialCriterionId,
        type: type
      }).then(res => {
        if (type === 'table') {
          this.tableQuestions = res.Result
        } else {
          this.Questions = res.Result
        }
      })
    },
    async initForm() {
      await this.getGroupOptions()
      await this.getParentQuestions()
      await this.getLesionType()
      console.log('data', this.data)
      if (Object.keys(this.data).length > 0) {
        for (const k in this.form) {
          if (k === 'CalculateQuestions' && this.data[k] !== undefined) {
            console.log(this.data[k])
            this.form[k] = JSON.parse(this.data[k])
            console.log('CalculateQuestions', this.form[k])
          } else if (k === 'ClassifyAlgorithms' && this.data[k] !== undefined && this.data[k] !== '') {
            this.ClassifyAlgorithmsList = JSON.parse(this.data[k])
            console.log(11111, this.form)
          } else {
            if (this.data.hasOwnProperty(k)) {
              this.form[k] = this.data[k]
            }
          }
        }
        if (this.form.FileType && this.form.FileType.length > 0) {
          this.form.FileType = this.form.FileType.split(',')
        } else {
          this.form.FileType = []
        }
        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 i = this.parentOptions.findIndex(item => {
            return item.QuestionId === this.form.RelevanceId
          })
          if (i !== -1) {
            if (this.parentOptions[i].QuestionGenre === 3) {
              this.reParentTriggerValOptions = this.$d[this.parentOptions[i].DictionaryCode]
            } else {
              const options = []
              this.parentOptions[i].TypeValue.split('|').forEach((item, index) => {
                options.push({id: i, label: item, value: item})
              })
              this.reParentTriggerValOptions = options
            }
          }
        }
      }
      if (!this.data.ShowOrder && this.data.ShowOrder !== 0) {
        if (this.list.length > 0) {
          var ShowOrderList = this.list.map(v => v.ShowOrder)
          this.form.ShowOrder = Math.max(...ShowOrderList) + 1
        }
      }
    },
    save() {
      this.form.ClassifyAlgorithms = JSON.stringify(this.ClassifyAlgorithmsList)
      this.$refs.qsForm.validate(valid => {
        if (!valid) return
        this.loading = true
        var params = Object.assign({}, this.form)
        params.TrialId = this.$route.query.trialId
        params.ReadingCriterionPageId = this.data.ReadingCriterionPageId
        params.CalculateQuestions = JSON.stringify(this.form.CalculateQuestions)
        if (this.form.Type !== 'upload') {
          this.form.ImageCount = 0
        }
        params.FileType = this.form.FileType.toString()
        addOrUpdateReadingQuestionTrial(params).then(res => {
          this.$emit('getList')
          this.loading = false
          this.$emit('close')
          this.$emit('reloadArbitrationRules')

          this.$message.success(this.$t('common:message:savedSuccessfully'))
        })
          .catch(() => {
            this.loading = false
          })
      })
    },
    getGroupOptions() {
      return new Promise((resolve, reject) => {
        this.loading = true
        var param = {
          criterionId: this.data.ReadingQuestionCriterionTrialId,
          readingCriterionPageId: this.data.ReadingCriterionPageId
        }
        getTrialGroupNameList(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 = {
          readingQuestionCriterionTrialId: this.data.ReadingQuestionCriterionTrialId,
          id: this.data.Id,
          readingCriterionPageId: this.data.ReadingCriterionPageId
        }
        getTrialCriterionOtherQuestion(param).then(res => {
          this.parentOptions = res.Result
          this.loading = false
          resolve()
        }).catch(() => {
          this.loading = false
          reject()
        })
      })
    },
    isShowQuestionChange(val, form) {
      if (this.form.Type === 'table') 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.RelevanceValueList = []
      }
    },
    parentQuestionChange(val, form) {
      console.log(val)
      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('|')
          const 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
            form.GroupEnName = this.parentOptions[index].GroupEnName
          }
        }
      } else {
        form.GroupName = ''
        form.GroupEnName = ''
        this.isParentExistGroup = false
      }
      form.ParentTriggerValueList = []
    },
    relevanceQuestionChange(val, form) {
      if (val) {
        var index = this.parentOptions.findIndex(item => {
          return item.QuestionId === val
        })
        if (index !== -1) {
          // this.reParentTriggerValOptions = this.parentOptions[index].TypeValue.split('|')
          const options = []
          this.parentOptions[index].TypeValue.split('|').forEach((item, index) => {
            options.push({id: index, label: item, value: item})
          })
          this.reParentTriggerValOptions = options
        }
      }
      form.RelevanceValueList = []
    },
    isJudgeQuestionChange(val, form) {
      if (val) {
        form.ShowQuestion = 0
        form.IsRequired = 0
      }
    },
    qsTypeChange(val, form) {
      if (val === 'group') {
        form.QuestionName = ''
      }
      if (val !== 'select' && val !== 'radio') {
        form.IsJudgeQuestion = false
        form.TypeValue = ''
      }
      if (val === 'table') {
        form.IsRequired = 2
      } else {
        form.LesionType = null
      }
    },
    getLesionType() {
      return new Promise((resolve, reject) => {
        this.loading = true
        var param = {
          TrialCriterionId: this.data.ReadingQuestionCriterionTrialId
        }
        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>
