<template>
  <div class="criterion-form-item">
    <!-- <div
      v-if="!!question.GroupName && (questionForm[question.ParentId] === question.ParentTriggerValue) || question.ParentId===''||question.ParentId===null"
      style="font-weight: bold;font-size: 16px;margin: 5px 0px;"
    >
      {{ question.GroupName }}
    </div> -->
    <div v-if="!!question.GroupName && question.Type === 'group'"
      style="font-weight: bold; font-size: 16px; margin: 5px 0px">
      {{ language === "en" ? question.GroupEnName : question.GroupName }}
    </div>
    <div v-if="question.Type === 'table' || question.Type === 'basicTable'"
      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" @click="openAddTableCol(question)">
          {{ $t("trials:readingUnit:qsList:title:add") }}
        </el-button>
      </div>
      <el-table :data="question.TableQuestions.Answers">
        <el-table-column v-for="item of question.TableQuestions.Questions" :key="item.Id" :prop="item.Id"
          :label="item.QuestionName" min-width="100" show-overflow-tooltip>
          <template slot-scope="scope">
            <span v-if="item.Unit">{{ scope.row[item.Id] }}{{ item.Unit !== 4 ? $fd('ValueUnit', item.Unit)
              : item.ValueType === 2 ? '%' :
                item.CustomUnit }}</span>
            <span v-else>{{ scope.row[item.Id] }}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <template v-else>
      <el-form-item v-if="
        (question.ShowQuestion === 1 &&
          !!~question.ParentTriggerValueList.indexOf(
            questionForm[question.ParentId]
          )) ||
        question.ShowQuestion === 0
      " :label="`${question.QuestionName}`" :prop="question.Id" :rules="[
        {
          required:
            (question.IsRequired === 0 ||
              (question.IsRequired === 1 &&
                question.RelevanceId &&
                !!~question.RelevanceValueList.indexOf(
                  isNaN(parseFloat(questionForm[question.RelevanceId])) ? questionForm[question.RelevanceId] :
                    questionForm[question.RelevanceId].toString()))) &&
            question.Type !== 'group' &&
            question.Type !== 'summary',
          message: this.$t('common:ruleMessage:specify'),
          trigger: ['blur', 'change'],
        },
      ]" :class="[
        question.Type === 'group'
          ? 'mb'
          : question.Type === 'upload'
            ? 'uploadWrapper'
            : '',
      ]">
        <!-- 输入框 -->
        <el-input v-if="question.Type === 'input'" v-model="questionForm[question.Id]"
          :disabled="question.TableQuestionType === 2" @change="(val) => { formItemChange(val, question) }" />
        <!-- 多行文本输入框 -->
        <el-input v-if="question.Type === 'textarea'" v-model="questionForm[question.Id]" type="textarea"
          :autosize="{ minRows: 2, maxRows: 4 }" @change="(val) => { formItemChange(val, question) }" />
        <!-- 下拉框 -->
        <el-select v-if="question.Type === '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.trim()"
              :value="val.trim()" />
          </template>
        </el-select>
        <!-- 单选 -->
        <el-radio-group v-if="question.Type === '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.trim()" :label="val.trim()">
              {{ val.trim() }}
            </el-radio>
          </template>
        </el-radio-group>
        <!-- 复选框 -->
        <el-checkbox-group v-if="question.Type === 'checkbox'" v-model="questionForm[question.Id]"
          @change="(val) => { formItemChange(val, question) }">
          <template v-if="question.DictionaryCode">
            <el-checkbox v-for="item of $d[question.DictionaryCode]" :key="item.id" :label="item.value">
              {{ item.label }}
            </el-checkbox>
          </template>
          <template v-if="question.TypeValue">
            <el-checkbox v-for="val in question.TypeValue.split('|')" :key="val.trim()" :label="val.trim()">
              {{ val.trim() }}
            </el-checkbox>
          </template>
        </el-checkbox-group>

        <!-- 自动计算 -->
        <!-- :precision="2" :step="0.1" :max="10" -->
        <el-input v-if="question.Type === 'calculation'" v-model="questionForm[question.Id]" disabled />
        <!-- 自动分类 -->
        <el-input v-if="question.Type === 'class' && question.ClassifyShowType === 1"
          v-model="questionForm[question.Id]" :disabled="!question.ClassifyEditType" />
        <el-select v-if="question.Type === 'class' && question.ClassifyShowType === 2"
          v-model="questionForm[question.Id]" :disabled="!question.ClassifyEditType"
          @change="(val) => { formItemChange(val, question) }">
          <el-option v-for="val in question.TypeValue.split('|')" :key="val" :label="val.trim()" :value="val.trim()" />
        </el-select>
        <el-radio-group v-if="question.Type === 'class' && question.ClassifyShowType === 3"
          v-model="questionForm[question.Id]" :disabled="!question.ClassifyEditType"
          @change="(val) => { formItemChange(val, question) }">
          <el-radio v-for="item of question.TypeValue.split('|')" :key="item.trim()" :label="item.trim()">
            {{ item.trim() }}
          </el-radio>
        </el-radio-group>
        <el-input v-if="question.Type === 'class' && question.ClassifyShowType === 4" type="number"
          :disabled="!question.ClassifyEditType" v-model="questionForm[question.Id]" />
        <!-- 自增 -->
        <el-input v-if="question.Type === 'increment'" v-model="questionForm[question.Id]" disabled />
        <!-- 数值 -->
        <!-- :precision="2" :step="0.1" :max="10" -->
        <el-select v-if="question.Type === 'number' && question.TypeValue" v-model="questionForm[question.Id]" clearable
          @change="(val) => { formItemNumberChange(val, question) }">
          <el-option v-for="val in question.TypeValue.split('|')" :key="val" :label="val.trim()" :value="val.trim()" />
          <template v-if="question.Unit !== 0" slot="prefix">{{ question.Unit !== 4 ? $fd('ValueUnit', question.Unit) :
            question.CustomUnit }}</template>
          <template v-else-if="question.ValueType === 2" slot="prefix">%</template>
        </el-select>
        <el-input v-else-if="question.Type === 'number' && question.DataSource !== 1"
          v-model="questionForm[question.Id]" type="number" @change="(val) => { formItemNumberChange(val, question) }">
          <template v-if="question.Unit !== 0" slot="append">{{ question.Unit !== 4 ? $fd('ValueUnit', question.Unit) :
            question.CustomUnit }}</template>
          <template v-else-if="question.ValueType === 2" slot="append">%</template>
        </el-input>
        <el-input v-else-if="question.Type === 'number' && question.DataSource === 1"
          v-model="questionForm[question.Id]" :disabled="question.DataSource === 1">
          <template v-if="question.Unit !== 0" slot="append">{{ question.Unit !== 4 ? $fd('ValueUnit', question.Unit) :
            question.CustomUnit }}</template>
          <template v-else-if="question.ValueType === 2" slot="append">%</template>
        </el-input>
        <!-- 上传图像 -->
        <el-upload v-if="question.Type === 'upload'" action :accept="question.FileType"
          :limit="question.ImageCount > 0 ? parseInt(question.ImageCount) : 100" :on-preview="handlePictureCardPreview"
          :before-upload="handleBeforeUpload" :http-request="uploadScreenshot" list-type="picture-card"
          :on-remove="handleRemove" :file-list="fileList" :class="{ disabled: fileList.length >= question.ImageCount }">
          <i slot="default" class="el-icon-plus" />
          <div slot="file" slot-scope="{ file }">
            <img class="el-upload-list__item-thumbnail" :src="OSSclientConfig.basePath + file.url"
              crossOrigin="Anonymous" alt="" />
            <span class="el-upload-list__item-actions">
              <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                <i class="el-icon-zoom-in" />
              </span>

              <span v-if="readingTaskState < 2" class="el-upload-list__item-delete" @click="handleRemove(file)">
                <i class="el-icon-delete" />
              </span>
            </span>
          </div>
        </el-upload>
        <el-dialog v-if="question.Type === 'upload'" append-to-body :visible.sync="imgVisible" width="600px">
          <el-image :src="imageUrl" crossOrigin="Anonymous" width="100%">
            <!-- 加载中 -->
            <div slot="placeholder" class="image-slot">
              {{ $t("trials:readingUnit:qsList:message:loading")
              }}<span class="dot">...</span>
            </div>
          </el-image>
        </el-dialog>
      </el-form-item>
    </template>
    <template v-if="
      question.Childrens &&
      question.Childrens.length > 0 &&
      (question.Type !== 'table' && question.Type !== 'basicTable') && Object.keys(questionForm).length > 0
    ">
      <QuestionFormItem v-for="item in question.Childrens" :key="item.Id" :questionForm="questionForm" :question="item"
        :reading-task-state="readingTaskState" :is-system-criterion="isSystemCriterion" :visit-task-id="visitTaskId"
        :criterion-id="criterionId" :calculation-list="calculationList" @formItemNumberChange="formItemNumberChange"
        @setFormItemData="setFormItemData" @resetFormItemData="resetFormItemData" />
    </template>
    <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">
        <QuestionTableFormItem v-for="item in QuestionsList" :key="item.Id" :question="item"
          :reading-task-state="readingTaskState" :is-system-criterion="isSystemCriterion" :question-form="QuestionsForm"
          :visit-task-id="visitTaskId" :criterion-id="criterionId"
          @formItemTableNumberChange="formItemTableNumberChange" @setFormItemData="setTblFormItemData"
          @resetFormItemData="resetTblFormItemData" />
        <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 {
  uploadReadingAnswerImage,
  getTrialOrganList,
  getCustomTableQuestionPreview,
  getQuestionCalculateRelation,
} from "@/api/trials";
import QuestionTableFormItem from "./QuestionTableFormItem";
import { mapGetters } from "vuex";
export default {
  name: "QuestionFormItem",
  components: { QuestionTableFormItem },
  props: {
    questionForm: {
      type: Object,
      required: true,
    },
    isSystemCriterion: {
      type: Boolean,
      default: false
    },
    question: {
      type: Object,
      required: true,
    },
    criterionId: {
      type: String,
      required: true,
    },
    readingTaskState: {
      type: Number,
      required: true,
    },
    visitTaskId: {
      type: String,
      default: "",
    },
    calculationList: {
      type: Array,
      default() {
        return [];
      },
    },
  },

  computed: {
    ...mapGetters(["language"]),
  },
  data() {
    return {
      addOrEdit: { visible: false, title: "" },
      fileList: [],
      accept: ".png,.jpg,.jpeg",
      imgVisible: false,
      imageUrl: "",
      urls: [],
      organList: [],
      QuestionsList: [],
      QuestionsForm: {},
      AnswersList: [],
      loading: false,
      classArr: []
    };
  },
  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.question.Type === 'class') {
          this.$emit("setFormItemData", { key: this.question.Id, val: v[this.question.Id], question: v })
        }

        this.formItemNumberChange(this.question.Id, false);

      },
    },
  },
  mounted() {
    if (this.question.Type === "class") {
      this.ClassifyAlgorithmsList = JSON.parse(
        this.question.ClassifyAlgorithms
      );
    }
    // setInterval(() => {
    //   if (this.question.Type === "class") {
    //     let o = this.ClassifyAlgorithmsList.find((v) => {
    //       return (
    //         this.questionForm[this.question.ClassifyQuestionId] >= v.gt &&
    //         this.questionForm[this.question.ClassifyQuestionId] < v.lt
    //       );
    //     });
    //     if (this.questionForm[this.question.ClassifyQuestionId]) {
    //       this.questionForm[this.question.Id] = o ? o.label : null;
    //     } else {
    //       this.questionForm[this.question.Id] = null;
    //     }
    //   }
    // }, 300);
    if (this.question.Type === "upload") {
      if (this.questionForm[this.question.Id]) {
        this.urls = this.questionForm[this.question.Id].split("|");
        this.fileList = [];
        this.urls.map((url) => {
          this.fileList.push({ name: "", url: `${url}` });
        });
      }
    }
    // if (this.question.Type === "table") {
    //   // this.getQuestionCalculateRelation()
    //   if (this.questionForm[this.question.Id]) {
    //     this.QuestionsForm = {};
    //     this.question.TableQuestions.Questions.forEach((v) => {
    //       if (v.Type === "number") {
    //         this.$set(this.QuestionsForm, v.Id, 0);
    //       } else {
    //         this.$set(this.QuestionsForm, v.Id, "");
    //       }
    //     });
    //   }
    // }
  },
  methods: {
    getQuestionCalculateRelation() {
      getQuestionCalculateRelation({
        TrialReadingCriterionId: this.criterionId,
        ReadingQuestionId: this.question.Id,
      }).then((res) => {
        this.calculationList = res.Result;
      });
    },
    save() {
      // this.AnswersList.push(this.QuestionsForm);
      this.$emit("setFormItemData", {
        key: this.question.Id,
        val: this.QuestionsForm,
        type: 'table',
        question: this.question
      });
      this.question.TableQuestions.Answers.push(this.QuestionsForm)
      this.formItemNumberChange(this.question.Id, true);
      this.addOrEdit.visible = false;
    },
    logic(rules, num = 0) {
      let isNE = false
      try {
        if (rules.CalculateQuestionList.length === 0) {
          return false;
        }
        let dataArr = []
        rules.CalculateQuestionList.forEach((o, i) => {
          if (this.questionForm[o.TableQuestionId] === 'NE') {
            isNE = true
          }
          if (i === 0) {
            if (rules.CustomCalculateMark > 4 && rules.CustomCalculateMark < 10) {
              switch (rules.CustomCalculateMark) {
                case 5:
                  this.questionForm[o.QuestionId].forEach((q, qi) => {
                    if (!isNaN(parseFloat(q[o.TableQuestionId]))) {
                      if (qi === 0) {
                        num = parseFloat(q[o.TableQuestionId]);
                      } else {
                        num *= parseFloat(q[o.TableQuestionId]);
                      }
                    }

                    if (q[o.TableQuestionId] === 'NE') {
                      isNE = true
                    }
                    if (q[o.TableQuestionId] === 'NE') {
                      isNE = true
                    }
                  });
                  break;
                case 6:
                  this.questionForm[o.QuestionId].forEach((q, qi) => {
                    if (!isNaN(parseFloat(q[o.TableQuestionId]))) {
                      if (qi === 0) {
                        num = parseFloat(q[o.TableQuestionId]);
                      } else {
                        num += parseFloat(q[o.TableQuestionId]);
                      }
                    }

                    if (q[o.TableQuestionId] === 'NE') {
                      isNE = true
                    }
                    if (q[o.TableQuestionId] === 'NE') {
                      isNE = true
                    }
                  });
                  break;
                case 7:
                  this.questionForm[o.QuestionId].forEach((q, qi) => {
                    if (!isNaN(parseFloat(q[o.TableQuestionId]))) {
                      if (qi === 0) {
                        num = parseFloat(q[o.TableQuestionId]);
                      } else {
                        num += parseFloat(q[o.TableQuestionId]);
                      }
                    }

                    if (q[o.TableQuestionId] === 'NE') {
                      isNE = true
                    }
                    if (q[o.TableQuestionId] === 'NE') {
                      isNE = true
                    }
                  });
                  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) => {
                    if (!isNaN(parseFloat(q[o.TableQuestionId]))) {
                      arr.push(q[o.TableQuestionId]);
                    }

                    arr.push(q[o.TableQuestionId]);
                    if (q[o.TableQuestionId] === 'NE') {
                      isNE = true
                    }
                  });
                  num = arr.length === 0 ? 0 : Math.max(...arr);
                  break;
                case 9:
                  var arr = [];
                  this.questionForm[o.QuestionId].forEach((q) => {
                    if (!isNaN(parseFloat(q[o.TableQuestionId]))) {
                      arr.push(q[o.TableQuestionId]);
                    }
                    if (q[o.TableQuestionId] === 'NE') {
                      isNE = true
                    }
                  });
                  num = arr.length === 0 ? 0 : Math.min(...arr);
                  break;
              }
            } else {
              if (!isNaN(parseFloat(this.questionForm[o.TableQuestionId]))) {
                num = parseFloat(this.questionForm[o.TableQuestionId]);
                if (!isNaN(num)) {
                  dataArr.push(num)
                }
              }

            }
          } else {
            if (this.questionForm[o.TableQuestionId] === 'NE') {
              isNE = true
            }
            switch (rules.CustomCalculateMark) {
              case 1:
                if (!isNaN(parseFloat(this.questionForm[o.TableQuestionId]))) {
                  num += parseFloat(this.questionForm[o.TableQuestionId]);
                }
                break;
              case 2:
                if (!isNaN(parseFloat(this.questionForm[o.TableQuestionId]))) {
                  num -= parseFloat(this.questionForm[o.TableQuestionId]);
                }
                break;
              case 3:
                if (!isNaN(parseFloat(this.questionForm[o.TableQuestionId]))) {
                  num *= parseFloat(this.questionForm[o.TableQuestionId]);
                }

                break;
              case 4:
                if (!isNaN(parseFloat(this.questionForm[o.TableQuestionId]))) {
                  num /= parseFloat(this.questionForm[o.TableQuestionId]);
                }

                break;
              case 10:
                if (!isNaN(parseFloat(this.questionForm[o.TableQuestionId]))) {
                  dataArr.push(parseFloat(this.questionForm[o.TableQuestionId]))
                }
                num = dataArr.length === 0 ? 0 : dataArr.reduce((acc, curr) => {
                  return acc + (typeof curr === "number" ? curr : 0);
                }, 0) / dataArr.length;
                break;
              case 11:
                if (!isNaN(parseFloat(this.questionForm[o.TableQuestionId]))) {
                  dataArr.push(parseFloat(this.questionForm[o.TableQuestionId]))
                }
                num = Math.max(...dataArr);
                break;
              case 12:
                if (!isNaN(parseFloat(this.questionForm[o.TableQuestionId]))) {
                  dataArr.push(parseFloat(this.questionForm[o.TableQuestionId]))
                }
                num = Math.min(...dataArr);
                break;
              case 13:
                if (!isNaN(parseFloat(this.questionForm[o.TableQuestionId]))) {
                  dataArr.push(parseFloat(this.questionForm[o.TableQuestionId]))
                }

                num = dataArr.length === 0 ? 0 : dataArr.reduce((acc, curr) => acc && curr) ? 1 : 0
                break;
              case 14:
                if (!isNaN(parseFloat(this.questionForm[o.TableQuestionId]))) {
                  dataArr.push(parseFloat(this.questionForm[o.TableQuestionId]))
                }
                num = dataArr.length === 0 ? 0 : dataArr.reduce((acc, curr) => acc || curr, 0) ? 1 : 0;
                break;
            }
          }
        });
      } catch (e) {
        console.log(e);
      }
      if (isNE) {
        return 'NE'
      }
      if (rules.ValueType === 2) {
        num = num * 100
      }
      return num.toFixed(this.digitPlaces)
    },
    formItemNumberChange(questionId, isTable) {
      if (typeof isTable === 'object') {
        this.$emit("setFormItemData", { key: isTable.Id, val: questionId, question: isTable });
      } else {
        if (isTable) {
          this.calculationList.forEach((v, i) => {
            var find = v.CalculateQuestionList.filter((o) => {
              return o.QuestionId === questionId;
            });
            if (find) {
              var num = this.logic(v);
              if (num !== false) {
                this.$emit("setFormItemData", { key: v.QuestionId, val: num, question: v });
              }
            }
          });
        } else {
          this.calculationList.forEach((v) => {
            var find = v.CalculateQuestionList.filter((o) => {
              return o.TableQuestionId === questionId;
            });

            // find的自动计算值number
            if (find) {
              var num = this.logic(v);
              if (num !== false) {
                this.$emit("setFormItemData", { key: v.QuestionId, val: num, question: v });
              }
            }
          });
        }
      }

      // this.$emit('formItemNumberChange')
    },
    formItemTableNumberChange() {
      this.question.TableQuestions.Questions.forEach((v) => {
        if (v.Type === "number" && v.DataSource === 1) {
          var CalculateQuestions = JSON.parse(v.CalculateQuestions);
          var num,
            arr = [];
          let isNE = false
          CalculateQuestions.forEach((o, i) => {
            if (this.QuestionsForm[o.TableQuestionId] === 'NE') {
              isNE = true
            }
            if (i === 0) {
              if (!isNaN(parseFloat(this.QuestionsForm[o.TableQuestionId]))) {
                num = parseFloat(this.QuestionsForm[o.TableQuestionId]);
                arr = [num];
              }

            } else {
              switch (v.CustomCalculateMark) {
                case 1:
                  if (!isNaN(parseFloat(this.QuestionsForm[o.TableQuestionId]))) {
                    num += parseFloat(this.QuestionsForm[o.TableQuestionId]);
                  }

                  break;
                case 2:
                  if (!isNaN(parseFloat(this.QuestionsForm[o.TableQuestionId]))) {
                    num -= parseFloat(this.QuestionsForm[o.TableQuestionId]);
                  }

                  break;
                case 3:
                  if (!isNaN(parseFloat(this.QuestionsForm[o.TableQuestionId]))) {
                    num *= parseFloat(this.QuestionsForm[o.TableQuestionId]);
                  }

                  break;
                case 4:
                  if (!isNaN(parseFloat(this.QuestionsForm[o.TableQuestionId]))) {
                    num /= parseFloat(this.QuestionsForm[o.TableQuestionId]);
                  }

                  break;
                case 7:
                  if (!isNaN(parseFloat(this.QuestionsForm[o.TableQuestionId]))) {
                    arr.push(parseFloat(this.QuestionsForm[o.TableQuestionId]));
                  }

                  num =
                    arr.length === 0
                      ? 0
                      : arr.reduce((acc, curr) => {
                        return acc + (typeof curr === "number" ? curr : 0);
                      }, 0) / arr.length;
                  break;
                case 8:
                  if (!isNaN(parseFloat(this.QuestionsForm[o.TableQuestionId]))) {
                    arr.push(parseFloat(this.QuestionsForm[o.TableQuestionId]));
                  }

                  num = arr.length === 0 ? 0 : Math.max(...arr);
                  break;
                case 9:
                  if (!isNaN(parseFloat(this.QuestionsForm[o.TableQuestionId]))) {
                    arr.push(parseFloat(this.QuestionsForm[o.TableQuestionId]));
                  }

                  num = arr.length === 0 ? 0 : Math.min(...arr);
                  // console.log('min', this.questionForm[o.QuestionId], arr, num)
                  break;
              }
            }
          });
          if (isNE) {
            num = 'NE'
          } else {
            num = num.toFixed(this.digitPlaces)
          }
          this.$set(this.QuestionsForm, v.Id, num.toString());
        }
      });
    },
    openAddTableCol(row) {
      this.QuestionsForm = {}
      this.classArr = []
      this.addOrEdit.title =
        row.QuestionName + this.$t("trials:readingUnit:qsList:title:tableQs"); // '表格问题'
      this.QuestionsList = row.TableQuestions.Questions;
      row.TableQuestions.Questions.map(v => {
        if (v.Type === 'class') {
          this.classArr.push({ triggerId: v.ClassifyTableQuestionId, classId: v.Id, classifyAlgorithms: v.ClassifyAlgorithms, classifyType: v.ClassifyType })
        }
      })
      // this.AnswersList = row.TableQuestions.Answers;
      row.TableQuestions.Questions.map(i => {
        this.$set(this.QuestionsForm, i.Id, null)
      })
      // this.QuestionsForm = {};
      this.addOrEdit.visible = true;
    },
    getOrganInfoList() {
      var param = {
        trialId: this.$route.query.trialId,
        lesionType: this.question.LesionType,
        // systemCriterionId: this.criterionId,
        isEnable: true,
      };
      getTrialOrganList(param).then((res) => {
        this.organList = res.Result;
      });
    },
    formNumberItemChange(v) {
      this.$emit("setFormItemData", { key: v.QuestionId, val: num, question: v });
    },
    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, question: qs });
        });
      } else {
        this.$emit("setFormItemData", { key: question.Id, val: v, question: question })
      }
    },
    resetChild(obj) {
      obj.forEach((i) => {
        this.$emit("resetFormItemData", i.Id);
        if (i.Childrens && i.Childrens.length > 0) {
          this.resetChild(i.Childrens);
        }
      });
    },
    resetFormItemData(v) {
      this.$emit("resetFormItemData", v);
    },
    setFormItemData(obj) {
      this.$emit("setFormItemData", obj);
    },
    setTblFormItemData(obj) {
      this.$set(this.QuestionsForm, obj.key, obj.val)
      this.classArr.map(i => {
        if (i.triggerId === obj.key) {
          let answer = null
          let list = JSON.parse(i.classifyAlgorithms)
          if (i.classifyType === 0) {
            let o = list.find(v => {
              return (
                parseFloat(obj.val) >= parseFloat(v.gt) &&
                parseFloat(obj.val) < parseFloat(v.lt)
              )
            })
            answer = o ? o.label : 'NE'
          } else if (i.classifyType === 1) {
            let o = list.find(v => {
              return v.val.includes(obj.val)
            })
            answer = o ? o.label : null
          }
          this.$set(this.QuestionsForm, i.classId, answer)
        }
      })
      // if (this.classArr.length > 0) {
      //   let qs = this.classArr.find(i=>i.triggerId === obj.key)
      //   if (!qs) return
      //   let answer = null
      //   let list = JSON.parse(qs.classifyAlgorithms)
      //   if (qs.classifyType === 0) {
      //     let o = list.find(v => {
      //       return (
      //         parseFloat(obj.val) >= parseFloat(v.gt) &&
      //         parseFloat(obj.val) < parseFloat(v.lt)
      //       )
      //     })
      //     answer = o ? o.label : null 
      //   } else if (qs.classifyType === 1) {
      //     let o = list.find(v => {
      //       return v.val.includes(obj.val)
      //     })
      //     answer = o ? o.label : null 
      //   }
      //   if (answer !== null) {
      //     this.$set(this.QuestionsForm, qs.classId, answer)
      //   }
      // }
    },
    resetTblFormItemData(obj) {
      this.$set(this.QuestionsForm, obj.key, null)
    },
    async uploadScreenshot(param) {
      if (!this.visitTaskId) {
        const loading = this.$loading({
          target: document.querySelector(".ecrf-wrapper"),
          fullscreen: false,
          lock: true,
          text: "Loading",
          spinner: "el-icon-loading",
        });
        var file = await this.fileToBlob(param.file);
        const res = await this.OSSclient.put(
          `/${this.trialId}/ReadAttachment/preview/${param.file.name}`,
          file
        );
        this.fileList.push({
          name: param.file.name,
          url: this.$getObjectName(res.url),
        });
        this.urls.push(this.$getObjectName(res.url));
        this.$emit("setFormItemData", {
          key: this.question.Id,
          val: this.urls.length > 0 ? this.urls.join("|") : "",
          question: this.question
        });
        loading.close();
      } else {
        const loading = this.$loading({
          target: document.querySelector(".ecrf-wrapper"),
          fullscreen: false,
          lock: true,
          text: "Loading",
          spinner: "el-icon-loading",
        });
        var file = await this.fileToBlob(param.file);
        const res = await this.OSSclient.put(
          `/${this.trialId}/ReadAttachment/${this.subjectId}/${this.visitTaskId}/${param.file.name}`,
          file
        );
        this.fileList.push({
          name: param.file.name,
          url: this.$getObjectName(res.url),
        });
        this.urls.push(this.$getObjectName(res.url));
        this.$emit("setFormItemData", {
          key: this.question.Id,
          val: this.urls.length > 0 ? this.urls.join("|") : "",
          question: this.question
        });
        loading.close();
      }
      // uploadReadingAnswerImage(this.$route.query.trialId, this.visitTaskId, formData).then(res => {
      //   if (res.IsSuccess) {
      //     this.fileList.push({ url: `${res.Result.Path}` })
      //     this.urls.push(res.Result.Path)
      //     this.$emit('setFormItemData', { key: this.question.Id, val: this.urls.length > 0 ? this.urls.join('|') : '' })
      //   }
      //   loading.close()
      // }).catch(() => {
      //   loading.close()
      // })
    },
    handleBeforeUpload(file) {
      // 检测文件类型是否符合要求
      if (this.checkFileSuffix(file.name)) {
        // this.fileList = []
        return true;
      } else {
        var msg = this.$t(
          "trials:readingUnit:qsList:message:imageFormat"
        ).replace("xxx", this.accept);
        this.$alert(msg);
        return false;
      }
    },
    checkFileSuffix(fileName) {
      var index = fileName.lastIndexOf(".");
      var suffix = fileName.substring(index + 1, fileName.length);
      if (
        this.accept.toLocaleLowerCase().search(suffix.toLocaleLowerCase()) ===
        -1
      ) {
        return false;
      } else {
        return true;
      }
    },
    autoCalculation() {
      // console.log('自动计算')
    },
    // 预览图片
    handlePictureCardPreview(file) {
      this.imageUrl = this.OSSclientConfig.basePath + file.url;
      this.imgVisible = true;
    },
    // 删除图片
    handleRemove(file, fileList) {
      this.imageUrl = "";
      this.fileList.splice(
        this.fileList.findIndex((f) => f.url === file.url),
        1
      );
      this.urls.splice(
        this.fileList.findIndex((f) => f === file.url),
        1
      );
      this.$emit("setFormItemData", {
        key: this.question.Id,
        val: this.urls.length > 0 ? this.urls.join("|") : "",
        question: this.question
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.my_dialog {
  .criterion-form-item {
    ::v-deep .el-form-item__content {
      width: auto;
    }
  }
}

::v-deep .el-select .el-input__prefix {
  left: calc(100% - 50px);
  cursor: pointer;
}

::v-deep .el-select .el-input__inner {
  padding-left: 15px;
  padding-right: 50px;
}

.criterion-form-item {
  .el-form-item {
    display: flex;
    flex-direction: row;
    align-items: flex-start;
  }

  ::v-deep .el-form-item__content {
    width: 500px;
  }

  .el-input {
    width: 100%;
  }

  .mb {
    margin-bottom: 0px;
  }

  .disabled {
    ::v-deep .el-upload--picture-card {
      display: none;
    }
  }

  .uploadWrapper {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>
