<template>
  <div class="criterion-form-item">
    <div
      v-if="!!question.QuestionName && question.ClinicalQuestionType==='group'"
      style="font-weight: bold;font-size: 16px;margin: 5px 0px;margin-bottom: 10px"
    >
      {{ language==='en'?question.QuestionEnName:question.QuestionName }}
    </div>
    <div
      v-else-if="question.ClinicalQuestionType==='summary'"
      style="background:#f3f3f3;border-radius:4px;font-size: 12px;margin: 5px 0px;margin-bottom: 10px;font-size: 12px;padding: 10px"
    >
      {{ language==='en'?question.QuestionEnName:question.QuestionName }}
    </div>
    <div
      v-else-if="question.ClinicalQuestionType==='table' && ((question.ClinicalQuestionShowEnum===1 && question.ParentTriggerValue === questionForm[question.ParentId].toString()) || question.ClinicalQuestionShowEnum===0)"
      style="font-weight: bold;font-size: 14px;margin: 5px 0px;"
    >
      <div style="display: flex;justify-content: space-between;">
        <span>
          {{ question.QuestionName }}
        </span>
        <!-- 添加 -->
        <el-button type="primary" size="mini" @click="openAddTableCol(question)">
          {{ $t('trials:readingUnit:qsList:title:add') }}
        </el-button>
      </div>
      <el-table
        :data="questionForm[question.Id]"
      >
        <el-table-column
          v-for="item of question.TableQuestions"
          :key="item.Id"
          :prop="item.Id"
          :label="item.QuestionName"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          :label="$t('common:action:action')"
          min-width="100"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="openAddTableCol(question, scope.$index)">
              {{ $t('common:button:edit') }}
            </el-button>
            <el-button type="text" size="mini" v-if="scope.row.IsCurrentTaskAdd === 'True' || !question.IsCopyLesions || IsBaseline" @click="deleteTableCol(question, scope.$index)">
              {{ $t('common:button:delete') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-col v-else :span="12">
      <el-form-item
        v-if="(question.ClinicalQuestionShowEnum===1 && question.ParentTriggerValue === questionForm[question.ParentId].toString()) || question.ClinicalQuestionShowEnum===0"
        :label="`${question.QuestionName}`"
        :prop="question.Id"
        :rules="[
          { required: (question.IsRequired === 0 || (question.IsRequired ===1 && question.RelevanceId && (question.RelevanceValue === questionForm[question.RelevanceId].toString()))) && question.ClinicalQuestionType !== 'summary' && question.ClinicalQuestionType!=='group' && question.ClinicalQuestionType!=='table',
            message: this.$t('common:ruleMessage:specify'), trigger: ['blur', 'change']}
        ]"
        :class="[question.Type==='group'?'mb':question.Type==='upload'?'uploadWrapper':'']"
      >
        <!-- 输入框 -->
        <el-input
          v-if="question.ClinicalQuestionType==='input'"
          v-model="questionForm[question.Id]"
          :disabled="question.TableQuestionType === 2"
          :max-length="question.MaxAnswerLength ? question.MaxAnswerLength : 200"
        />
        <!-- 多行文本输入框 -->
        <el-input
          v-if="question.ClinicalQuestionType==='textarea'"
          v-model="questionForm[question.Id]"
          type="textarea"
          :max-length="question.MaxAnswerLength ? question.MaxAnswerLength : 200"
          :autosize="{ minRows: 2, maxRows: 4}"
        />
        <!-- 下拉框 -->
        <el-select
          v-if="question.ClinicalQuestionType==='select'"
          v-model="questionForm[question.Id]"
          clearable
          :disabled="(question.TableQuestionType === 2 || question.QuestionGenre === 2) && !!question.DictionaryCode"
          @change="((val)=>{formItemChange(val, question)})"
        >
          <template v-if="question.TableQuestionType === 1">
            <el-option
              v-for="item in organList"
              :key="item.Id"
              :label="item[question.DataTableColumn]"
              :value="item[question.DataTableColumn]"
            />
          </template>
          <template v-else-if="question.TableQuestionType === 3 || question.QuestionGenre === 3">
            <el-option
              v-for="item of $d[question.DictionaryCode]"
              :key="item.id"
              :value="item.value"
              :label="item.label"
            />
          </template>
          <template v-else-if="(question.TableQuestionType === 2 || question.QuestionGenre === 2) && question.DictionaryCode">
            <el-option
              v-for="item of $d[question.DictionaryCode]"
              :key="item.id"
              :value="item.value"
              :label="item.label"
            />
          </template>
          <template v-else>
            <el-option
              v-for="val in question.TypeValue.split('|')"
              :key="val"
              :label="val"
              :value="val.trim()"
            />
          </template>
        </el-select>
        <!-- 单选 -->
        <el-date-picker
          v-if="question.ClinicalQuestionType === 'time'"
          v-model="questionForm[question.Id]"
          style="width: 200px"
          align="right"
          type="date"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
        />
        <!-- 单选 -->
        <el-radio-group
          v-if="question.ClinicalQuestionType==='radio'"
          v-model="questionForm[question.Id]"
          @change="((val)=>{formItemChange(val, question)})"
        >
          <template v-if="question.DictionaryCode">
            <el-radio
              v-for="item of $d[question.DictionaryCode]"
              :key="item.id"
              :label="item.value"
            >
              {{ item.label }}
            </el-radio>
          </template>
          <template v-if="question.TypeValue">
            <el-radio
              v-for="val in question.TypeValue.split('|')"
              :key="val"
              :label="val"
            >
              {{ val }}
            </el-radio>
          </template>
        </el-radio-group>
        <!-- 复选框 -->
        <el-checkbox-group
          v-if="question.ClinicalQuestionType==='checkbox' && questionForm[question.Id] !== ''"
          v-model="questionForm[question.Id]"
        >
          <el-checkbox
            v-for="val of question.TypeValue.split('|')"
            :key="val"
            :label="val"
            :value="val"
          >
            {{ val }}
          </el-checkbox>
        </el-checkbox-group>
        <el-input
          v-if="question.ClinicalQuestionType === 'number'"
          :ref="question.Id"
          v-model="questionForm[question.Id]"
          type="number"
          style="width: 200px"
          :disabled="question.CustomCalculateMark > 0"
          @input="limitInput($event, questionForm, question)"
        >
          <template v-if="question.Unit" slot="append">{{ question.Unit }}</template>
        </el-input>
        <span v-if="question.CustomCalculateMark === 11 && question.ClinicalQuestionType === 'number'" v-show="questionForm[JSON.parse(question.CalculateQuestions)[0].TableQuestionId] <= questionForm[JSON.parse(question.CalculateQuestions)[0].QuestionId]" style="margin-left: 10px">
          {{ questionForm[JSON.parse(question.CalculateQuestions)[0].TableQuestionId] }}-{{ questionForm[JSON.parse(question.CalculateQuestions)[0].QuestionId] }}
        </span>
        <span v-if="question.CustomCalculateMark === 10 && question.ClinicalQuestionType === 'number' && questionForm[JSON.parse(question.CalculateQuestions)[0].TableQuestionId]" style="margin-left: 10px">
          {{ questionForm[JSON.parse(question.CalculateQuestions)[0].TableQuestionId] }}-{{ questionForm.CreateTime ? questionForm.CreateTime : parseTime(new Date(), '{y}-{m}-{d}') }}
        </span>
        <!-- 生日不能大于截止日期 -->
        <span v-if="question.CustomCalculateMark === 11 && question.ClinicalQuestionType === 'number'" v-show="questionForm[JSON.parse(question.CalculateQuestions)[0].TableQuestionId] > questionForm[JSON.parse(question.CalculateQuestions)[0].QuestionId]" style="margin-left: 10px;font-size: 12px;color:#f66">
          {{ $t('trials:components:clinicalDataQS:msg:birthDay') }}
        </span>
      </el-form-item>
    </el-col>
    <!-- eslint-disable vue/no-use-v-if-with-v-for -->
    <!-- eslint-disable vue/valid-v-for -->
    <el-col v-for="(item) in question.Childrens" v-if="question.Childrens && question.Childrens.length>0 && question.ClinicalQuestionType !== 'table'" :span="['group', 'summary', 'table'].includes(item.ClinicalQuestionType) || item.Childrens.length > 0 ? 24 : 12">
      <QuestionFormItem
        :key="item.Id"
        :question="item"
        :question-form="questionForm"
        :trial-clinical-id="trialClinicalId"
        @formItemNumberChange="formItemNumberChange"
        @setFormItemData="setFormItemData"
        @resetFormItemData="resetFormItemData"
      />
    </el-col>
    <el-dialog
      v-if="addOrEdit.visible"
      class="my_dialog"
      :visible.sync="addOrEdit.visible"
      :close-on-click-modal="false"
      :title="addOrEdit.title"
      width="400px"
      append-to-body
    >
      <el-form
        ref="tableQsForm"
        v-loading="loading"
        size="small"
        :model="QuestionsForm"
      >
        <QuestionTableFormItem
          v-for="(item) in QuestionsList"
          :key="item.Id"
          :question="item"
          :question-form="QuestionsForm"
          @setFormItemData="setFormItemData"
          @resetFormItemData="resetFormItemData"
        />
        <div class="base-dialog-footer" style="text-align:right;margin-top:10px;">
          <el-form-item>
            <!-- 取消 -->
            <el-button
              size="small"
              type="primary"
              @click="addOrEdit.visible = false"
            >
              {{ $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>
    </el-dialog>
  </div>
</template>
<script>
import { getTrialClinicalQuestionCalculateRelation } from '@/api/dictionary'
import QuestionTableFormItem from './QuestionTableFormItem'
import { mapGetters } from 'vuex'
import DicomEvent from "../../../views/trials/trials-panel/reading/dicoms/components/DicomEvent";

export default {
  name: 'QuestionFormItem',
  components: { QuestionTableFormItem },
  props: {
    openType: {
      type: String,
      default() {
        return ''
      }
    },
    questionForm: {
      type: Object,
      default() {
        return {}
      }
    },
    question: {
      type: Object,
      default() {
        return []
      }
    },
    trialClinicalId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      addOrEdit: { visible: false, title: '', id: null, index: 0},
      fileList: [],
      accept: '.png,.jpg,.jpeg',
      imgVisible: false,
      imageUrl: '',
      urls: [],
      calculationList: [],
      organList: [],
      QuestionsList: [],
      QuestionsForm: {},
      AnswersList: [],
      loading: false
    }
  },
  computed: {
    ...mapGetters(['language'])
  },
  watch: {
    questionForm: {
      deep: true,
      immediate: true,
      handler(v, oldv) {
        try {
          if (!v || !v[this.question.Id] || !oldv || !oldv[this.question.Id]) return
        } catch (e) {
          console.log(e, v)
        }
        if (this.openType === 'look') return
        this.formItemNumberChange(this.question.Id, false)
      }
    }
  },
  mounted() {
    this.getTrialClinicalQuestionCalculateRelation()
    if (this.questionForm[this.question.Id]) {
      this.QuestionsForm = {}
      this.question.TableQuestions.forEach(v => {
        if (v.ClinicalQuestionType === 'number') {
          this.$set(this.QuestionsForm, v.Id, 0)
        } else if (this.question.ClinicalTableQuestionType === 'time') {
          this.$set(this.QuestionsForm, v.Id, null)
        } else if (this.question.ClinicalTableQuestionType === 'checkbox') {
          this.$set(this.QuestionsForm, v.Id, [])
        } else {
          this.$set(this.QuestionsForm, v.Id, '')
        }
      })
    }
  },
  methods: {
    limitInput(value, form, row) {
      if (value.indexOf('.') > -1) {
        if (value.split('.')[1].length >= row.DigitPlaces) {
          this.$set(form, row.Id, parseFloat(value).toFixed(row.DigitPlaces))
        }
      }
      this.$forceUpdate()
    },
    getTrialClinicalQuestionCalculateRelation() {
      getTrialClinicalQuestionCalculateRelation({
        TrialClinicalId: this.trialClinicalId
      }).then(res => {
        this.calculationList = res.Result
      })
    },
    getCurrentAgeByBirthDate2(val, val2) {
      const currentYear = new Date(val2).getFullYear() // 当前的年份
      const calculationYear = new Date(val).getFullYear() // 计算的年份
      const wholeTime = currentYear + val.substring(4) // 周岁时间
      const calculationAge = currentYear - calculationYear // 按照年份计算的年龄
      // 判断是否过了生日
      if (new Date(val2).getTime() > new Date(wholeTime).getTime()) {
        return calculationAge
      } else {
        return calculationAge - 1
      }
    },
    getCurrentAgeByBirthDate(val) {
      const currentYear = new Date().getFullYear() // 当前的年份
      const calculationYear = new Date(val).getFullYear() // 计算的年份
      const wholeTime = currentYear + val.substring(4) // 周岁时间
      const calculationAge = currentYear - calculationYear // 按照年份计算的年龄
      // 判断是否过了生日
      if (new Date().getTime() > new Date(wholeTime).getTime()) {
        return calculationAge
      } else {
        return calculationAge - 1
      }
    },
    save() {
      this.$refs.tableQsForm.validate(valid => {
        console.log(this.$refs.tableQsForm)
        console.log(this.QuestionsForm)
        console.log(valid)
        if (!valid) return
        if (this.addOrEdit.type === 'add') {
          this.AnswersList.push(this.QuestionsForm)
        } else {
          this.AnswersList[this.addOrEdit.index] = this.QuestionsForm
        }
        this.$emit('setFormItemData', { key: this.question.Id, val: this.AnswersList })
        this.formItemNumberChange(this.question.Id, true)
        this.addOrEdit.visible = false
      })
    },
    logic(rules, num = 0) {
      try {
        if (rules.CalculateQuestionList.length === 0) {
          return false
        }
        rules.CalculateQuestionList.forEach((o, i) => {
          if (i === 0) {
            if (rules.CustomCalculateMark > 4) {
              switch (rules.CustomCalculateMark) {
                case 5:
                  this.questionForm[o.QuestionId].forEach((q, qi) => {
                    if (qi === 0) {
                      num = parseFloat(q[o.TableQuestionId])
                    } else {
                      num *= parseFloat(q[o.TableQuestionId])
                    }
                  })
                  break
                case 6:
                  console.log(this.questionForm[o.QuestionId])
                  console.log(this.questionForm)
                  this.questionForm[o.QuestionId].forEach((q, qi) => {
                    if (qi === 0) {
                      num = parseFloat(q[o.TableQuestionId])
                    } else {
                      num += parseFloat(q[o.TableQuestionId])
                    }
                  })
                  break
                case 7:
                  this.questionForm[o.QuestionId].forEach((q, qi) => {
                    if (qi === 0) {
                      num = parseFloat(q[o.TableQuestionId])
                    } else {
                      num += parseFloat(q[o.TableQuestionId])
                    }
                  })
                  num = this.questionForm[o.QuestionId].length === 0 ? 0 : num / this.questionForm[o.QuestionId].length
                  break
                case 8:
                  var arr = []
                  this.questionForm[o.QuestionId].forEach(q => {
                    arr.push(q[o.TableQuestionId])
                  })
                  num = arr.length === 0 ? 0 : Math.max(...arr)
                  break
                case 9:
                  // eslint-disable-next-line no-redeclare
                  var arr = []
                  this.questionForm[o.QuestionId].forEach(q => {
                    arr.push(q[o.TableQuestionId])
                  })
                  num = arr.length === 0 ? 0 : Math.min(...arr)
                  console.log('min', this.questionForm[o.QuestionId], arr, num)
                  break
                case 10:
                  if (parseFloat(this.getCurrentAgeByBirthDate(this.questionForm[o.TableQuestionId])) > 0) {
                    num = parseFloat(this.getCurrentAgeByBirthDate(this.questionForm[o.TableQuestionId]))
                  } else {
                    num = 0
                  }
                  break
                case 11:
                  if (parseFloat(this.getCurrentAgeByBirthDate2(this.questionForm[o.TableQuestionId], this.questionForm[o.QuestionId])) > 0) {
                    num = parseFloat(this.getCurrentAgeByBirthDate2(this.questionForm[o.TableQuestionId], this.questionForm[o.QuestionId]))
                  } else {
                    num = 0
                  }
                  break
              }
            } else {
              num = parseFloat(this.questionForm[o.TableQuestionId])
            }
          } else {
            switch (rules.CustomCalculateMark) {
              case 1:
                num += parseFloat(this.questionForm[o.TableQuestionId])
                break
              case 2:
                num -= parseFloat(this.questionForm[o.TableQuestionId])
                break
              case 3:
                num *= parseFloat(this.questionForm[o.TableQuestionId])
                break
              case 4:
                num /= parseFloat(this.questionForm[o.TableQuestionId])
                break
              case 10:
                if (parseFloat(this.getCurrentAgeByBirthDate(this.questionForm[o.TableQuestionId])) > 0) {
                  num = parseFloat(this.getCurrentAgeByBirthDate(this.questionForm[o.TableQuestionId]))
                } else {
                  num = 0
                }
                break
              case 11:
                if (parseFloat(this.getCurrentAgeByBirthDate2(this.questionForm[o.TableQuestionId], this.questionForm[o.QuestionId])) > 0) {
                  num = parseFloat(this.getCurrentAgeByBirthDate2(this.questionForm[o.TableQuestionId], this.questionForm[o.QuestionId]))
                } else {
                  num = 0
                }
                break
            }
          }
        })
      } catch (e) {
        console.log(e)
      }
      console.log(num)
      return num
    },
    formItemNumberChange(questionId, isTable) {
      try {
        if (isTable) {
          this.calculationList.forEach((v, i) => {
            console.log(v, i)
            var find = v.CalculateQuestionList.filter(o => {
              return o.QuestionId === questionId
            })
            // find的自动计算值number
            console.log('find', find)
            if (find) {
              var num = this.logic(v)
              if (num !== false) {
                this.$emit('setFormItemData', { key: v.QuestionId, val: num })
              }
            }
          })
        } else {
          this.calculationList.forEach(v => {
            var find = v.CalculateQuestionList.filter(o => {
              return o.TableQuestionId === questionId
            })
            // find的自动计算值number
            console.log('find', find)
            // find的自动计算值number
            if (find) {
              var num = this.logic(v)
              if (num !== false) {
                this.$emit('setFormItemData', { key: v.QuestionId, val: num })
              }
            }
          })
        }
      } catch (e) {
        console.log(e)
      }
      // this.$emit('formItemNumberChange')
    },
    deleteTableCol(row, index) {
      this.$confirm(this.$t('trials:uploadNonDicoms:message:msg1')).then(() => {
        this.questionForm[row.Id].splice(index, 1)
        console.log(this.questionForm)
      })
    },
    openAddTableCol(row, index) {
      this.addOrEdit.visible = true
      this.addOrEdit.title = row.QuestionName + this.$t('trials:readingUnit:qsList:title:tableQs')// '表格问题'
      this.QuestionsList = row.TableQuestions
      this.AnswersList = Object.assign([], this.questionForm[row.Id])
      if (!index && index !== 0) {
        this.addOrEdit.type = 'add'
        this.QuestionsForm = {}
      } else {
        this.addOrEdit.type = 'edit'
        this.addOrEdit.index = index
        this.addOrEdit.id = row.Id
        this.QuestionsForm = Object.assign({}, this.questionForm[row.Id][index])
      }
    },
    formItemChange(v, question) {
      if (question.Childrens.length > 0) {
        this.resetChild(question.Childrens)
      }
      // if (question.TableQuestionType === 1 && question.RelationQuestions.length > 0) {
      //   var index = this.organList.findIndex(item => item[question.DataTableColumn] === v)
      //   if (index < 0) return
      //   var selected = this.organList[index]
      //   this.question.RelationQuestions.map(qs => {
      //     var val = selected[qs.DataTableColumn]
      //     // if (typeof val === 'boolean') {
      //     //   // val = String(val)
      //     // }
      //     this.$emit('setFormItemData', { key: qs.Id, val: val })
      //   })
      // }
    },
    resetChild(obj) {
      obj.forEach(i => {
        this.$emit('resetFormItemData', i.Id, i)
        if (i.Childrens && i.Childrens.length > 0) {
          this.resetChild(i.Childrens)
        }
      })
    },
    resetFormItemData(v, i) {
      this.$emit('resetFormItemData', v, i)
    },
    setFormItemData(obj) {
      this.$emit('setFormItemData', obj)
    }
  }
}
</script>
<style lang="scss" scoped>
.my_dialog{
  .criterion-form-item{
    >>>.el-form-item__content{
      width: auto;
    }
  }
}
.el-col-12 .el-col-12{
  width: 100%;
}
.criterion-form-item{
  .el-form-item{
    display: flex;
    flex-direction: row;
    align-items: flex-start;
  }
  .el-input{
    width:100%;
  }
  .mb{
    margin-bottom: 0px;
  }
  .disabled{
    >>>.el-upload--picture-card {
      display: none;
    }
  }
  .uploadWrapper{
    display: flex;
    flex-direction: column;
    align-items: flex-start;
  }
}
.clearfix:after{
  content: '';
  display: table;
  clear: both;
}
</style>
