<template>
  <el-form
    ref="tableQsForm"
    v-loading="loading"
    :model="form"
    size="small"
    :rules="rules"
    :disabled="type === 'look'"
    label-width="120px"
  >
    <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-if="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'"
        :label="$t('trials:readingUnit:qsList:title:groupName')"
        prop="GroupName"
      >
        <el-input
          v-model="form.GroupName"
        />
      </el-form-item>
      <el-form-item
        v-if="form.Type !== 'group'"
        :label="$t('trials:readingUnit:qsList:title:qsName')"
        prop="QuestionName"
      >
        <el-input
          v-model="form.QuestionName"
        />
      </el-form-item>
      <el-form-item
        v-if="form.Type !== 'group'"
        :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 === 'number'" label="问题数据来源" 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 :label="$t('trials:readingUnit:qsList:title:PrecopyValue')">
        <el-switch
          v-model="form.IsCopy"
        />
      </el-form-item>
      <el-form-item
        v-if="form.Type === 'number'"
        :label="$t('trials:readingUnit:qsList:title:valueType')"
        prop="ValueType"
        :rules="[
          { required: true, message: $t('trials:researchForm:formRule:select')}
        ]"
      >
        <el-radio-group
          v-model="form.ValueType"
        >
          <el-radio
            v-for="item of $d.ValueType"
            v-if="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:  $t('trials:researchForm:formRule:select')}
        ]"
      >
        <el-input :value="$fd('DigitPlaces', digitPlaces).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: $t('trials:researchForm:formRule:select')}
        ]"
      >
        <el-radio-group
          v-model="form.Unit"
        >
          <el-radio v-for="item of $d.ValueUnit" :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: $t('trials:researchForm:formRule: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)"
          >
            <el-radio
              v-for="item of $d.CustomCalculateMark"
              v-if="item.value <= 4"
              :key="`CustomCalculateMark${item.value}`"
              :label="item.value"
            >
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-table
          :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
            :label="$t('trials:readingUnit:qsList:title:qsNameEn')"
            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('common:button:add')"
                @click="addCustomCalculateMark(scope.$index)"
              />
              <el-button
                icon="el-icon-minus"
                size="mini"
                circle
                :disabled="form.CalculateQuestions.length <= 2"
                :title="$t('common:button: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) ? '请选择同级问题！' : '请选择表格问题下的子问题！' }}
        </div>
      </div>
      <el-form-item
        v-if="(form.Type === 'select' || form.Type === 'radio' || form.Type === 'input') && isFromSystem"
        :label="$t('trials:readingUnit:label:QuestionGenre')"
        prop="TableQuestionType"
        :rules="[
          { required: form.Type !== 'input', message: $t('common:ruleMessage:select')}
        ]"
      >
        <el-radio-group
          v-model="form.TableQuestionType"
          @change="((val)=>{tableQuestionTypeChange(val, form)})"
        >
          <el-radio
            v-for="item of $d.TableQuestionType"
            :key="item.id"
            :label="item.value"
            :disabled="form.Type === 'radio' && (item.value===1 || item.value===2)"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        v-if="(!isFromSystem || form.TableQuestionType === 3) && (form.Type === 'select' || form.Type === 'radio' || form.Type === 'calculation')"
        :label="$t('trials:readingUnit:qsList:title:typeValue')"
        prop="TypeValue"
      >
        <el-input
          v-model="form.TypeValue"
          :placeholder="$t('trials:readingUnit:qsList:message:msg3')"
        />
      </el-form-item>
      <!-- 关联表 -->
      <!-- <el-form-item
        v-if="form.TableQuestionType === 1"
        label="关联表"
        prop="DataTableName"
      >
        <el-select
          v-model="form.DataTableName"
          clearable
          @change="((val)=>{dataTableNameChange(val, form)})"
        >
          <el-option
            v-for="item of tblOptions"
            :key="`RelevanceId${item.QuestionId}`"
            :label="item.QuestionName"
            :value="item.QuestionId"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item
        v-if="form.TableQuestionType === 2 && isFromSystem"
        :label="$t('trials:readingUnit:qsList:title:DependParentId')"
        prop="DependParentId"
      >
        <el-select
          v-model="form.DependParentId"
        >
          <el-option
            v-for="item of parentOptions"
            :key="`DependParentId${item.QuestionId}`"
            :label="item.QuestionName"
            :value="item.QuestionId"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="form.TableQuestionType === 1 || !!form.DependParentId && isFromSystem"
        :label="$t('trials:readingUnit:qsList:title:DataTableColumn')"
        prop="DataTableColumn"
      >
        <el-select v-model="form.DataTableColumn">
          <el-option
            v-for="item of $d.OrganColumn"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item
        v-if="form.TableQuestionType === 3 || form.TableQuestionType === 2 && isFromSystem"
        :label="$t('trials:readingUnit:label:DictionaryCode')"
        prop="DictionaryCode"
        :rules="[{ required: form.TableQuestionType === 3, message: $t('common:ruleMessage:select'), trigger: 'blur' }]"
      >
        <el-select v-model="form.DictionaryCode">
          <el-option
            v-for="item of dicList"
            :key="item.Id"
            :label="item.Code"
            :value="item.Code"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('trials:readingUnit:baseDataCfg:title:isEnable')" 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'" :label="$t('trials:qcCfg:table: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:qcCfg:table:parentTriggerValue')" prop="ParentTriggerValueList">
        <el-select v-model="form.ParentTriggerValueList" clearable multiple>
          <el-option
            v-for="item of parentTriggerValOptions"
            :key="item"
            :label="item"
            :value="item"
          />
        </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"
            :label="item"
            :value="item"
          />
        </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"
        />
      </el-form-item>
      <el-form-item :label="$t('trials:readingUnit:qsList:title:MaxRowCount')">
        <el-input-number
          v-model="form.MaxRowCount"
          controls-position="right"
          :min="0"
          :max="10"
        />
      </el-form-item>
      <el-form-item :label="$t('trials:readingUnit:qsList:title:limitEdit')">
        <el-radio-group v-model="form.LimitEdit">
          <el-radio v-for="item of $d.LimitEdit" :label="item.value">{{ item.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
    </div>
    <div v-if="type !== 'look'" class="base-dialog-footer" style="text-align:right;margin-top:10px;">
      <!-- 取消 -->
      <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>
    </div>
  </el-form>
</template>
<script>
import { addOrUpdateReadingTableQuestionTrial, getReadingTableOtherQuestionTrial, getCalculateTableQuestions } from '@/api/trials'
import { getBasicConfigSelect, getCriterionDictionaryList } from '@/api/dictionary'
export default {
  name: 'AddOrUpdateTableQs',
  props: {
    isFromSystem: {
      type: Boolean,
      required: true
    },
    digitPlaces: {
      type: Number,
      default() { return 0 }
    },
    list: {
      type: Array,
      default() { return [] }
    },
    data: {
      type: Object,
      default() { return {} }
    },
    readingQuestionId: {
      type: String,
      required: true
    },
    criterionId: {
      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:medicalFeedbackCfg:message:msg2')))
        } else {
          callback()
        }
      }
    }
    return {
      form: {
        Id: '',
        ReadingQuestionId: '',
        QuestionName: '',
        QuestionEnName: '',
        Type: 'select',
        TypeValue: '',
        ParentId: '',
        ParentTriggerValueList: [],
        ShowOrder: 0,
        ShowQuestion: 0,
        IsRequired: 0,
        Remark: '',
        RelevanceId: '',
        RelevanceValueList: [],
        DataTableName: '',
        DataTableColumn: '',
        DictionaryCode: '',
        TableQuestionType: null,
        MaxRowCount: null,
        DependParentId: '',
        QuestionMark: null,
        CalculateQuestions: [],
        CustomCalculateMark: '',
        DataSource: 0,
        GlobalReadingShowType: 3,
        CustomUnit: null,
        ValueType: null,
        Unit: null,
        LimitEdit: 0,
        DefaultValue: null,
        IsCopy: false
        // 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: 200, message: `${this.$t('common:ruleMessage:maxLength')} 200` }],

        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' }],
        ParentTriggerValueList: [
          { required: true, message: this.$t('common:ruleMessage:select'), trigger: 'blur' }
        ],
        RelevanceId: [{ required: true, message: this.$t('common:ruleMessage:select'), trigger: 'blur' }],
        RelevanceValueList: [{ 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' }],
        DependParentId: [{ required: true, message: this.$t('common:ruleMessage:select'), trigger: 'blur' }]
      },
      loading: false,
      parentOptions: [],
      parentTriggerValOptions: [],
      reParentTriggerValOptions: [],
      tblOptions: [],
      colOptions: [],
      dicList: [],
      Questions: [],
      tableQuestions: [],
      LimitEdit: 0
    }
  },
  mounted() {
    this.initForm()
    this.getCalculateTableQuestions('number')
    this.getCalculateTableQuestions('table')
  },
  methods: {
    deleteCustomCalculateMark(index) {
      this.form.CalculateQuestions.splice(index, 1)
    },
    addCustomCalculateMark(index) {
      this.form.CalculateQuestions.splice(index + 1, 0, {
        IsTable: false,
        QuestionId: this.data.ReadingQuestionId,
        TableQuestionId: null
      })
    },
    CustomCalculateMarkChange() {
      if (this.form.CustomCalculateMark <= 4) {
        this.form.CalculateQuestions = [
          {
            IsTable: false,
            QuestionId: this.data.ReadingQuestionId,
            TableQuestionId: null
          }, {
            IsTable: false,
            QuestionId: this.data.ReadingQuestionId,
            TableQuestionId: null
          }
        ]
      } else {
        this.form.CalculateQuestions = [
          {
            IsTable: true,
            QuestionId: this.data.ReadingQuestionId,
            TableQuestionId: null
          }
        ]
      }
    },
    getCalculateTableQuestions(type) {
      getCalculateTableQuestions({
        QuestionId: this.readingQuestionId,
        type: type
      }).then(res => {
        if (type === 'table') {
          this.tableQuestions = res.Result
        } else {
          this.Questions = res.Result
        }
      })
    },
    async initForm() {
      await this.getParentQuestions()
      if (Object.keys(this.data).length > 0) {
        for (const k in this.form) {
          if (k === 'CalculateQuestions') {
            this.form[k] = JSON.parse(this.data[k])
            console.log('CalculateQuestions', this.form[k])
          } else {
            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) {
            this.parentTriggerValOptions = this.parentOptions[index].TypeValue.split('|')
          }
        }
        if (this.form.RelevanceId) {
          var i = this.parentOptions.findIndex(item => {
            return item.QuestionId === this.form.RelevanceId
          })
          if (i !== -1) {
            this.reParentTriggerValOptions = this.parentOptions[i].TypeValue.split('|')
          }
        }
      }
      if (!this.data.ShowOrder) {
        if (this.list.length > 0) {
          var ShowOrderList = this.list.map(v => v.ShowOrder)
          this.form.ShowOrder = Math.max(...ShowOrderList) + 1
        }
      }
    },
    getBasicConfigSelect() {
      getCriterionDictionaryList({
        CriterionId: this.criterionId,
        SystemCriterionId: this.criterionId
      }).then(res => {
        this.dicList = res.Result
      })
    },
    save() {
      this.$refs.tableQsForm.validate(valid => {
        if (!valid) return
        this.loading = true
        var params = Object.assign({}, this.form)
        params.ReadingQuestionId = this.readingQuestionId
        params.TrialCriterionId = this.criterionId
        params.CalculateQuestions = JSON.stringify(this.form.CalculateQuestions)
        addOrUpdateReadingTableQuestionTrial(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
          })
      })
    },
    getParentQuestions() {
      return new Promise((resolve, reject) => {
        this.loading = true
        var param = {
          readingQuestionId: this.readingQuestionId,
          id: this.data.Id
        }
        getReadingTableOtherQuestionTrial(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 (val === 2) {
        form.IsRequired = 2
        form.ParentId = ''
        form.ParentTriggerValueList = []
        this.isParentExistGroup = false
      } else if (val === 1) {
        form.ParentId = ''
        form.ParentTriggerValueList = []
        form.GroupName = ''
        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) {
      if (val) {
        var index = this.parentOptions.findIndex(item => {
          return item.QuestionId === val
        })
        if (index !== -1) {
          this.parentTriggerValOptions = this.parentOptions[index].TypeValue.split('|')
        }
      }
      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('|')
        }
      }
      form.RelevanceValueList = []
    },
    tableQuestionTypeChange(val, form) {
      this.form.DictionaryCode = ''
      this.form.DataTableColumn = ''
      this.form.DataTableName = ''
      this.form.DependParentId = ''
      this.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.TableQuestionType = null
      form.DependParentId = ''
      form.DataTableColumn = ''
      form.DataTableName = ''
      form.DictionaryCode = ''
    },
    close() {
      this.$emit('close')
    }

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