<template>
  <div class="measure">
    <div class="measure-dialogue" v-for="(item, index) in smartMeasure" :key="item.id">
      <div class="measure-dialogue-robot">
        <cr-image
          class="Md-robot-avatar"
          width=""
          height=""
          fit="cover"
          src="@/assets/images/user/avatar@2x.png"
        />
        <div class="Md-robot-container">
          <p class="Mdr-container-question">{{ item.question }}</p>
          <p class="Mdr-container-progress">{{ item.id + "/" + dataList.length }}</p>
          <component
            v-if="!item.answer || index === dataList.length - 1"
            :is="item.component"
            :type="item.type"
            :disabled="isLoading"
            @nextQuestion="nextQuestion"
            :currentAnswer.sync="currentAnswer"
          ></component>
        </div>
      </div>
      <div class="measure-dialogue-operation">
        <div
          class="Md-operation-back"
          v-show="index === smartMeasure.length - 1 && index !== 0"
          @click="goBack(item.id)"
        >
          上一题
        </div>
        <div
          class="Md-operation-submit"
          @click="nextQuestion"
          v-show="
            item.selectType === 'multi-select' && currentAnswer && index === smartMeasure.length - 1
          "
        >
          {{ item.type === "insurance" ? "确认提交" : "确定" }}
        </div>
      </div>
      <div class="measure-dialogue-user" v-show="index !== dataList.length - 1 && item.answer">
        <p class="Md-user-answer">{{ item.answer }}</p>
        <cr-image class="Md-user-avatar" width="" height="" fit="cover" :src="avatar" />
      </div>
    </div>
    <cr-loading v-if="isLoading" class="measure-loading" size="24px">测评报告生成中...</cr-loading>
  </div>
</template>
<script>
import Age from "./modules/Age";
import Gender from "./modules/Gender";
import Select from "./modules/Select";
import { questionList } from "./constants";
import { addRiskEvaluation } from "@/api/smartMeasure";
import autoSaveForm from "@/mixins/autoSaveForm.mixin";
import { answerMap, paramsMap } from "./constants";
import localStorage from "@/service/localStorage";
import { cloneDeep, debounce } from "lodash-es";
import man from "@/assets/images/user/male@2x.png";
import woman from "@/assets/images/user/female@2x.png";

export default {
  name: "SmartMeasure",
  mixins: [autoSaveForm],
  components: {
    Age,
    Gender,
    Select
  },
  data() {
    return {
      dataList: cloneDeep(questionList),
      isLoading: false,
      currentAnswer: ""
    };
  },
  created() {
    console.log("smartMeasureList", this.hasAutoSaveData("smartMeasureList"), this.dataList);
    if (this.hasAutoSaveData("smartMeasureList")) {
      this.getSaveInfoHandler("smartMeasureList", "dataList");
    }
  },
  computed: {
    smartMeasure() {
      let result = this.dataList.filter(data => data.answer);
      if (result.length < this.dataList.length) {
        result.push(this.dataList[result.length]);
      }
      this.autoSaveHandler("dataList", "smartMeasureList", 0);
      this.scrollToBottom();
      return JSON.parse(JSON.stringify(result));
    },
    avatar() {
      return this.dataList[0].answer === "男神" ? man : woman;
    }
  },
  methods: {
    nextQuestion: debounce(function() {
      const id = this.smartMeasure[this.smartMeasure.length - 1].id;
      const smartMeasureLength = this.smartMeasure.length;
      this.dataList = this.dataList.map(data => {
        if (data.id === id) data.answer = this.currentAnswer;
        return data;
      });

      console.log(smartMeasureLength, this.dataList.length);
      if (smartMeasureLength === this.dataList.length) {
        this.submit();
      } else {
        this.currentAnswer = "";
      }
    }, 500),
    goBack(id) {
      if (this.isLoading) return;
      this.dataList[id - 1].answer = "";
      this.dataList[id - 2].answer = "";
    },
    submit() {
      this.isLoading = true;
      this.scrollToBottom();
      setTimeout(async () => {
        const params = this.dataList
          .map(v => {
            let answerTransformed = v.answer;
            if (["gender", "marrige", "income"].includes(v.type)) {
              answerTransformed = answerMap[v.type][answerTransformed];
            } else if (v.type === "age") {
              answerTransformed = +answerTransformed.slice(0, answerTransformed.length - 1);
            } else if (answerTransformed === "没有，下一题") {
              answerTransformed = "";
            }

            return { ...v, answerTransformed, keyTransformed: paramsMap[v.type] };
          })
          .reduce((a, b) => {
            return Object.assign(a, { [b.keyTransformed]: b.answerTransformed });
          }, {});
        if (localStorage.get("mongoToken")) {
          await addRiskEvaluation(params);
        }
        this.clearSaveHandler("smartMeasureList");
        this.$router.push({
          path: "/home/smart-measure/report",
          query: { gender: params.gender, age: params.age }
        });
        console.log("submit", params);
      }, 1500);
    },
    scrollToBottom() {
      this.$nextTick(() => {
        const element = document.querySelector(".measure");
        document.documentElement.scrollTop = element.scrollHeight;
      });
    }
  }
};
</script>
<style lang="less" src="./index.less" scoped></style>
