<template>
  <div class="component-dialog-survey">
    <el-dialog
      v-model="visible"
      v-cloak
      width="70%"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <template #title>
        <span>问卷名称: {{ answerDetail?.surveyMechanism?.name || "" }}</span>
        <!-- <span class="margin-left-10" style="color: #666; font-size: 14px"
          >(注意：标<span style="color: #f56c6c">*</span>的为必答题)</span
        > -->
      </template>
      <!-- style="height: 50vh; overflow: scroll" -->
      <div>
        <Questions
          ref="questions"
          :details="details"
          :answerResult="answerResult"
        ></Questions>
      </div>
      <template #footer>
        <el-button @click="visible = false">取 消</el-button>
        <el-button @click="handleSave">保存</el-button>

        <el-button type="primary" @click="handleSubmit('submit')"
          >提 交</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>
<script>
import Questions from "../surveyCmps/Questions.vue";
import { request, uploadToOSS } from "@/utils";
import { ElMessage } from "element-plus";

export default {
  components: {
    Questions
  },
  data() {
    return {
      details: {},
      survey: {},
      answerResult: {},
      answerDetail: {},
      QUESTION_TYPE_TEMP_CHECK: "temp_check",
      QUESTION_TYPE_ANSWER: "answer",
      QUESTION_TYPE_INPUT: "input",
      QUESTION_TYPE_TEXT: "text",
      QUESTION_TYPE_CHECKBOX: "checkbox",
      QUESTION_TYPE_RADIO: "radio",
      QUESTION_TYPE_RATING_SCALE: "rating_scale",
      QUESTION_TYPE_RATING: "rating",
      QUESTION_TYPE_DATE: "date",
      QUESTION_TYPE_MATRIX: "matrix_checkbox",
      QUESTION_TYPE_COMBINATION: "group"
    };
  },
  computed: {
    visible: {
      get() {
        return this.show;
      },
      set(n) {
        this.$emit("update:show", n);
      }
    }
  },
  props: {
    show: Boolean,
    id: [Number, String],
    resultId: [Number, String]
  },
  watch: {
    show(n) {
      if (n) {
        // Elmessage.success(resp.message);
        this.getResultDetails();
        this.getDetails();
      }
    }
  },
  methods: {
    getResultDetails() {
      request
        .get("/surveyService/mechanism/surveyResult/detail", {
          params: {
            id: this.resultId
          }
        })
        .then(resp => {
          console.log("获取的问卷结果详情", resp);
          this.answerResult = resp.data.detail.answerResult;
          this.answerDetail = resp.data.detail;
        });
    },
    getDetails() {
      if (!this.id) return;
      return new Promise(resolve => {
        request
          .get("/surveyService/mechanism/survey/detail/config", {
            params: {
              id: this.id
            }
          })
          .then(resp => {
            let details = resp.data.detail;
            details.questions = details.subjects.map(v => {
              try {
                return JSON.parse(v.questionnaireSubject.validator);
              } catch (error) {
                return { ...v, ...v.questionnaireSubject };
              }
            });
            this.details = details;
            console.log(this.details);
            this.survey = resp.data.subjects;
            setTimeout(() => {
              this.$refs["questions"].init();
            }, 500);
          });
      });
    },
    handleSave() {
      this.handleSubmit("cache");
    },
    handleSubmit(key = "submit") {
      let { surveyInfo, questions, isAllAnswer } =
        this.$refs["questions"].handleSubmit();
      //   if (!isAllAnswer) {
      //     return this.$message.error('请回答完所属问卷')
      //   }
      this.visible = false;
      let requestAnswer = this.formatAnswer(questions);
      console.log(requestAnswer);
      let api = {
        cache: "/surveyService/mechanism/surveyResult/save",
        submit: "/surveyService/mechanism/surveyResult/submit"
      };
      console.log(api[key]);
      request
        .post(api[key], {
          id: this.resultId,
          answer: requestAnswer
        })
        .then(resp => {
          this.$message.success("操作成功");
          this.$emit("success");
        });
    },
    formatAnswer(questions) {
      let answerList = questions.filter(v => v.code);
      let answerObj = {};
      answerList.map(v => {
        let obj = {};
        switch (v.type) {
          case this.QUESTION_TYPE_MATRIX:
            obj["matrixAnswers"] = v.matrixValue;
            break;

          case this.QUESTION_TYPE_INPUT:
            obj["inputAnswers"] = {
              key: v.qKey,
              value: [v.answer]
            };
            break;

          case this.QUESTION_TYPE_DATE:
            obj["answer"] = {
              key: v.qKey,
              value: v.rawAnswer
            };
            break;

          case this.QUESTION_TYPE_CHECKBOX:
            obj["checkboxAnswers"] = v.rawAnswer;
            break;
          case this.QUESTION_TYPE_RADIO:
            obj["answer"] = v.rawAnswer;
            break;
          case this.QUESTION_TYPE_COMBINATION:
            obj["groupAnswers"] = v.rawAnswer;
        }
        answerObj[v.code] = {
          type: v.type,
          questionNo: v.code,
          multipleAnswers: v.multipleAnswers,
          ...obj
        };
      });
      return answerObj;
    }
  }
};
</script>
<style lang="scss" scoped>
[v-cloak] {
  display: none;
}
.component-dialog-survey {
  ::v-deep .el-dialog__body {
    height: 70vh;
    overflow: scroll;
  }
}
</style>
