<template>
  <div ref="home" class="home">
    <div class="dialogue-list">
      <!-- <div v-if="state.detail.greeting_text" class="dialogue-item">
        <Image
          v-if="state.detail.style"
          :src="state.detail.style[0]"
          class="avatar"
        />

        <div class="dialogue-content">{{ state.detail.greeting_text }}</div>
      </div> -->
      <div
        v-for="(item, surveyIndex) in showList"
        :key="surveyIndex"
        class="dialogue-item"
      >
        <Image
          v-if="state.detail.style && item.type != 'answer'"
          class="avatar"
          :src="state.detail.style[0]"
        />
        <!-- :repeat-answer="item.isAnswered && lastIndex === surveyIndex" -->
        <QuestionItem
          :info="item"
          :hide-list="hideList"
          class="dialogue-content"
          ref="questionItem"
          @skip="skip"
          @back="back"
          @reply="reply"
          @check="check"
          :disable="details.status == 3"
          :answerResult="answerResult"
        ></QuestionItem>
        <Image
          v-if="state.detail.style && item.type === 'answer'"
          class="avatar"
          :src="state.detail.style[1]"
        />
        <el-divider></el-divider>
      </div>

      <template v-if="state.inputLoading">
        <div
          class="dialogue-item animate__animated animate__faster animate__slideInLeft"
        >
          <Image
            v-if="state.detail.style"
            class="avatar"
            :src="state.detail.style[0]"
          />

          <div class="dialogue-content">
            <span>...</span>
          </div>
        </div>
      </template>

      <!-- <template v-if="state.isFinished">

        <div
          v-if="state.detail.finished_text"
          class="dialogue-item animate__animated animate__fast animate__slideInLeft"
        >

          <Image v-if="state.detail.style" class="avatar" :src="state.detail.style[0]" />

          <div class="dialogue-content">

            <span>{{ state.detail.finished_text }}</span>

            <Button
              block
              type="primary"
              class="full-btn"
              @click="save"
              :disabled="checkDisabled"
              :loading="checkDisabled"
            >
              查看
            </Button>

          </div>

        </div>

      </template> -->
    </div>
  </div>
</template>

<script>
// import { resolvingDslLogic, surveyByCode } from '../utils/axios'
// import { inputBlur, wxPlusReady } from '@/utils'
// import { Notify, Toast, Button, Image, Dialog } from 'vant'
import { empty } from "@/utils/index";
import QuestionItem from "./QuestionItem.vue";
export default {
  data() {
    return {
      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",
      state: {
        detail: {
          id: "",
          title: "",
          code: "",
          questions: [],
          survey_rules: {
            status: ""
          },
          greeting_text: "",
          finished_text: "",
          style: [],
          peg: "",
          updated_at: ""
        },
        index: 0,
        isFinished: false,
        loading: null,
        inputLoading: false,
        survey_id: "",
        replyLock: false
      },
      rawList: [],
      showList: [],
      hideList: [],
      rules: [],
      checkDisabled: false,
      home: ""
    };
  },
  props: {
    details: {
      type: Object,
      default: () => {}
    },
    answerResult: {
      type: Object,
      default: () => {}
    }
  },
  components: {
    QuestionItem
  },
  computed: {
    noAnswer() {
      return this.showList.filter(
        v =>
          ![
            this.QUESTION_TYPE_TEXT,
            this.QUESTION_TYPE_ANSWER,
            this.QUESTION_TYPE_TEMP_CHECK
          ].includes(v.type)
      );
    },
    lastIndex() {
      for (let i = this.showList.length - 1; i >= 0; i--) {
        if (this.showList[i].isAnswered) {
          return i;
        }
      }
      return 0;
    }
  },
  methods: {
    reset() {
      (this.state = {
        detail: {
          id: "",
          title: "",
          code: "",
          questions: [],
          survey_rules: {
            status: ""
          },
          greeting_text: "",
          finished_text: "",
          style: [],
          peg: "",
          updated_at: ""
        },
        index: 0,
        isFinished: false,
        loading: null,
        inputLoading: false,
        survey_id: "",
        replyLock: false
      }),
        (this.rawList = []);
      this.showList = [];
      this.hideList = [];
      this.rules = [];
      this.checkDisabled = false;
      this.home = "";
    },
    async init() {
      this.reset();
      this.state.detail = this.details;
      // state.survey_id = data.id
      this.state.detail.questions = this.state.detail.questions.map(v => {
        if (v.type === this.QUESTION_TYPE_RATING_SCALE) {
          v.rating = [];
          for (let i = 0; i < v.max; i++) {
            v.rating.push(i + v.min);
          }
        }
        if (v.type === this.QUESTION_TYPE_COMBINATION) {
          if (v.children.find(v2 => v2.isRepeat)) {
            v.isRepeat = true;
          }
        }
        return v;
      });
      this.rawList = this.state.detail.questions;
      // this.showList = [this.state.detail.questions[0]]
      this.showList = this.state.detail.questions;
      console.log("this.showList", this.showList);
      let peg = null;
      try {
        peg = this.state.detail.peg ? JSON.parse(this.state.detail.peg) : {};
      } catch (e) {
        console.log(e);
        peg = {};
      }
      this.rules = peg.rules || {};
      console.log("state.detail", this.state.detail);
      console.log("rules.value", this.rules);
      this.$nextTick(() => {
        // this.inputBlur()
      });

      console.log(this.showList);
      this.$nextTick(async () => {
        this.$refs["questionItem"].forEach(v => {
          v.init();
        });
        this.recover();
        // 普通问卷不走规则校验；
        // if(this.details.survey.type == 1) return;
        // let list = [];
        // this.showList.forEach( v => {
        //   list.push(this.next(v, true, (number) => {
        //     list.push(number);
        //     list = list.filter(v =>  typeof v === 'number');
        //     this.showList = this.showList.splice(0, list[0]);
        //     console.log(this.showList);
        //   }));
        // })
        // setTimeout(() => {
        //   console.log("跑规则之后的list==>", list);
        // }, 3000)
      });
    },
    pushText(text, time, isHtml = false) {
      return new Promise((resolve, reject) => {
        this.showList.push({
          title: text,
          config: {
            desc: "",
            required: true
          },
          isHtml,
          type: this.QUESTION_TYPE_TEXT
        });
        setTimeout(() => {
          resolve(1);
        }, time || 8e2);
      });
    },

    skip(item) {
      item.isAnswered = true;
      this.next(item);
    },
    back(item) {
      if (this.state.replyLock) return;
      console.log(this.rules);
      let backList = this.rules[item.number]
        .filter(v => v.method === "hide" && v.expression.includes(item.number))
        .map(v => v.question)
        .flat();
      if (backList.length) {
        backList.forEach(k => {
          let delIdx = this.hideList.findIndex(v => v == k);
          delIdx >= 0 && this.hideList.splice(delIdx, 1);
        });
      }
      this.showList.splice(
        this.lastIndex + 1,
        this.showList.length - this.lastIndex
      );
      item.isAnswered = false;
      item.value = "";
      this.state.isFinished = false;
    },

    check(item, flag) {
      if (item.isRepeat) {
        this.repeat(item, flag);
      } else if (item.isEnd) {
        console.log(item);
        this.showList.splice(this.showList.length - 1, 1);
        if (flag) {
          this.state.isFinished = true;
        } else {
          this.next(this.noAnswer.at(-1), false);
        }
        // window.scrollTo(0, home.value.scrollHeight)
        this.home.scrollTo(0, this.home.scrollHeight);
      }
    },

    repeat(item, flag) {
      if (flag) {
        this.showList.splice(this.showList.length - 1, 1);
        this.$nextTick(() => {
          let item = JSON.parse(JSON.stringify(this.noAnswer.at(-1)));
          if (item.type === this.QUESTION_TYPE_COMBINATION) {
            item.children = item.children.map(v => {
              v.value = Array.isArray(v.value) ? [] : "";
              return v;
            });
          }
          this.showList.push({
            ...item,
            isAnswered: false,
            value: ""
          });
          // window.scrollTo(0, home.value.scrollHeight)
          this.home.scrollTo(0, this.home.scrollHeight);
        });
      } else {
        this.showList.splice(this.showList.length - 1, 1);
        this.next(this.noAnswer.at(-1));
      }
    },
    reply(item, text) {
      return;
      this.showList.push({
        left: false,
        title: text,
        type: this.QUESTION_TYPE_ANSWER,
        config: {
          required: true
        }
      });
      if (item.isRepeat) {
        this.showList.push({
          title: "是否再增加一条记录？",
          config: {
            desc: "",
            required: true
          },
          isRepeat: true,
          type: this.QUESTION_TYPE_TEMP_CHECK
        });
        console.log(showList.value);
        // window.scrollTo(0, home.value.scrollHeight)

        this.home.value.scrollTo(0, this.home.scrollHeight);
        return;
      }
      this.next(this.noAnswer.at(-1));
    },
    getItem(number) {
      return this.rawList.find(v => v.number === number);
    },
    getQ(number) {
      let items = this.showList.filter(v => v.number === number);
      let item = this.getItem(number);
      if (items.length > 1) {
        return items.map(this.formatItemVal);
      }
      let val = item.value;

      if (item.type === this.QUESTION_TYPE_RADIO) {
        return [val];
      } else if (item.type === this.QUESTION_TYPE_CHECKBOX) {
        return val || [];
      }
      return item.value;
    },
    getS(number) {
      var q = number.match(/Q\d+/)[0];
      var s = Number(number.match(/S\d+/)[0].slice(1)) - 1;
      var a = number.includes("A")
        ? Number(number.match(/A\d+/)[0].slice(1)) - 1
        : "";
      console.log(
        `当前获取${number} 获取到的q: ${q} ，获取到的s: ${s} ，获取到的a: ${a}`
      );
      return a ? this.getItem(q).matrix[s][a] : this.getItem(q).matrix[s];
    },
    getA(number) {
      let q = number.match(/Q\d+/)[0];
      let a = Number(number.match(/A\d+/)[0].slice(1)) - 1;
      console.log(`当前获取${number} 获取到的q: ${q} ，获取到的a: ${a}`);
      console.log(`获取到的q:`);
      let qVal = Array.isArray(this.getQ(q))
        ? this.getQ(q).map(String)
        : this.getQ(q) || "";
      return qVal.includes(String(a));
    },
    getVal(number) {
      return number.includes("S")
        ? this.getS(number)
        : number.includes("A")
        ? this.getA(number)
        : this.getQ(number);
    },
    getRuleKey(type) {
      switch (type) {
        case "showHide":
        case "to":
          return "expression";
        case "say":
        case "replace":
          return "keyword";
        default:
          return "";
      }
    },
    formatAge(birthday) {
      if (!birthday) return "";
      if (!isNaN(Number(birthday))) return birthday;
      const offset = +new Date() - +new Date(birthday.replace(/-/g, "/"));
      return parseInt(String(offset / 86400000 / 365));
    },
    formatRule(rule) {
      let getQAReg = new RegExp(/Q\d+(S\d+)?(A\d+)?/gi);
      let rawCondition = rule[this.getRuleKey(rule.type)] || "";
      rawCondition = rawCondition
        .replace(/ and /g, " && ")
        .replace(/ or /g, " || ");
      let condition = rawCondition;
      let replaceReg = undefined;
      let qa = [];
      if (condition) {
        console.log(
          `%c当前的规则： ${condition}`,
          "font-size: 16px; color: #4b72f6;"
        );
        qa = rawCondition.match(getQAReg) || [];
        console.log(qa);
        qa.map(n => {
          let v = this.getVal(n);
          console.log("获取到的值：", v, "获取的:", n);

          let reg = new RegExp(n);
          console.log(`要执行的正则`, reg, v);
          condition = condition.replace(
            reg,
            Array.isArray(v)
              ? `[${v
                  .map(v2 => (typeof v2 === "string" ? `'${v2}'` : v2))
                  .join(",")}]`
              : typeof v === "string"
              ? `'${v}'`
              : v
          );
          console.log(condition);
        });

        console.log(`获取到的qa`);
        console.log(qa);
        console.log(`最后的condition`);
        console.log(condition);
      }
      let flag = true;
      // try {
      //   flag = eval(condition)
      // } catch (e) {
      //   flag = false
      // }
      console.log(`当前规则执行的flag: %c ${flag}`, "color: #f00;");

      switch (rule.type) {
        case "showHide":
          console.log(
            `执行---------------show hide -----------规则: ${condition}`
          );
          if (flag) {
            if (rule.method == "hide") {
              this.hideList.push(...rule.question);
            }
          }
          break;
        case "to":
          console.log(`执行---------------to-----------规则: ${condition}`);
          return flag
            ? {
                type: "to",
                to: rule.to
              }
            : undefined;
        case "say":
          console.log(`执行---------------say-----------规则: ${condition}`);
          if (flag) {
            return {
              type: "say",
              say: rule.say
            };
          }
          break;

        case "replace":
          console.log(
            `执行---------------replace-----------规则: ${condition}`
          );
          replaceReg = new RegExp(rule.keyword);
          console.log(`执行正则: ${rule.keyword}`);

          {
            let t = undefined;
            let q = this.getItem(rule.from);
            console.log(`当前replace-q: `);
            console.log(q);
            if (rule.index >= 0) {
              console.log(q["choices"][rule.index - 1]);
              t = q["choices"][rule.index - 1].label;
            } else {
              if (q["choices"]) {
                t = q["choices"][Number(getQ(rule.from))].label;
              } else {
                t = q.value;
              }
            }
            console.log(`获取到的t: ${t}`);

            this.getItem(rule.to).title = this.getItem(rule.to).title.replace(
              replaceReg,
              Array.isArray(t) ? t.join(",") : t
            );
          }
          break;
        case "end":
          this.showList.push({
            title: "是否结束答题？",
            config: {
              desc: "",
              required: true
            },
            isEnd: true,
            type: this.QUESTION_TYPE_TEMP_CHECK
          });
          return {
            type: "end"
          };
      }
    },
    handleSubmit() {
      // localStorage.setItem(
      //       `temp_q2_${this.details.code}`,
      //       JSON.stringify({
      //         state: this.state,
      //         rawList: this.rawList,
      //         showList: this.showList,
      //         hideList: this.hideList,
      //         rules: this.rules
      //       })
      //     )
      console.log(this.details);
      let type = this.details.type;
      console.log(type);
      let { list, isAllAnswer } =
        type == 1 ? this.saveGeneralSurvey() : this.save();
      // this.save();

      return {
        surveyInfo: JSON.stringify({
          // surveyId: this.details.id,
          state: this.state,
          rawList: this.rawList,
          showList: this.showList,
          hideList: this.hideList,
          rules: this.rules
        }),
        questions: list,
        isAllAnswer
      };
    },
    recover() {
      const tempQuestions =
        this.details.answerCache && JSON.parse(this.details.answerCache);
      console.log("缓存", tempQuestions);
      if (tempQuestions) {
        // if (tempQuestions.state.detail.updated_at != state.detail.updated_at) {
        //   return localStorage.removeItem(`temp_q2_${this.details.code}`)
        // }
        console.log("存在缓存题目");

        Object.keys(tempQuestions.state).forEach(key => {
          this.state[key] = tempQuestions.state[key];
          // console.log(key, tempQuestions.state[key])
        });
        this.rawList = tempQuestions.rawList;
        this.showList = tempQuestions.showList;
        this.hideList = tempQuestions.hideList;
        this.rules = tempQuestions.rules;

        console.log("showList==>", this.showList);
      }
    },
    async next(item, runRule = true, callback) {
      this.state.replyLock = true;
      console.log("规则判断");
      let rule = this.rules[item.number];
      console.log("==================start=====================");
      let to = undefined;
      try {
        if (runRule) {
          for (let i in rule || []) {
            console.log("执行规则", i + 1, "-----type:", rule[i].type);
            let res = this.formatRule(rule[i]) || {};
            console.log(res);
            switch (res.type) {
              case "to":
                to = res.to || undefined;
                break;
              case "say":
                // res.say && (await this.pushText(res.say || '', 0, true))
                break;
              case "end":
                this.state.replyLock = false;
                return;
            }
          }
        }
      } catch (e) {
        console.log("报错了");
        console.log(e);
        // Notify(e.message)
      }
      console.log("==================end=======================");
      console.log(to);
      console.timeEnd("规则执行结束");

      this.state.inputLoading = true;
      this.$nextTick(async () => {
        setTimeout(async () => {
          this.state.inputLoading = false;
          if (to) {
            console.log("存在to跳转");
            if (to.toLocaleLowerCase() === "end") {
              this.state.isFinished = true;
              callback &&
                callback(Number(item.number.match(/Q\d+/gi)[0].slice(1)));
              // return Number(item.number.match(/Q\d+/gi)[0].slice(1))
            } else {
              // this.showList.push(this.getItem(to))
              // return this.getItem(to)
            }
          } else {
            console.log("不存在to跳转");
            this.state.index = Number(item.number.match(/Q\d+/gi)[0].slice(1));
            if (this.state.index >= this.rawList.length) {
              this.state.isFinished = true;
            } else {
              console.log("执行到这里", this.state.index);
              // this.showList.push(this.rawList[this.state.index])
              // return this.rawList[this.state.index]
            }
          }
          this.state.replyLock = false;
          // localStorage.setItem(
          //   `temp_q2_${this.$route.query.code}`,
          //   JSON.stringify({
          //     state: this.state,
          //     rawList: this.rawList,
          //     showList: this.showList,
          //     hideList: this.hideList,
          //     rules: this.rules
          //   })
          // )
          // this.$nextTick(() => {
          //   // window.scrollTo(0, home.value.scrollHeight)
          //   this.home.scrollTo(0, this.home.scrollHeight)
          //   if (this.state.isFinished) return
          // })
        }, 700);
      });
    },
    //
    saveGeneralSurvey() {
      let list = [];
      this.noAnswer.map(item => {
        let temp = {
          type: item.type,
          answer: "",
          q: item.title,
          rawAnswer: item.value,
          choices: [],
          config: item.config,
          code: item.sn,
          multipleAnswers: item.isMultiple || false,
          qKey: item.attr
        };
        console.log(item);
        switch (item.type) {
          case this.QUESTION_TYPE_INPUT:
            temp.answer = item.value;
            break;
          case this.QUESTION_TYPE_CHECKBOX:
            temp.choices = item.choices
              .map(v => {
                return {
                  label: v.label,
                  attr: v.attr
                };
              })
              .sort((a, b) => a - b);
            temp.answer = item.value
              ? item.value.map(v => {
                  return {
                    value: temp.choices[Number(v)].label,
                    key: temp.choices[Number(v)].attr
                  };
                })
              : [];
            temp.rawAnswer = temp.answer;
            break;
          case this.QUESTION_TYPE_RADIO:
            temp.choices = item.choices.map(v => {
              return {
                label: v.label,
                attr: v.attr
              };
            });
            temp.answer =
              item.value || item.value === 0
                ? {
                    key: temp.choices[Number(item.value)].attr,
                    value: temp.choices[Number(item.value)].label
                  }
                : null;
            temp.rawAnswer = temp.answer;
            break;
          case this.QUESTION_TYPE_RATING_SCALE:
            // let arr = []
            // for (let i = item.min; i < item.max; i++) {
            //   arr.push(i)
            // }

            temp.choices = Array(item.max - item.min)
              .fill(null)
              .map((_, index) => index + item.min);
            temp.answer = item.value;
            break;
          case this.QUESTION_TYPE_RATING:
            // let sum = 0
            if (item.isMultiple) {
              temp.answer = item.value
                ? item.value.map(v => String(Number(v) + 1))
                : [];
            } else {
              temp.answer =
                item.value || item.value === 0
                  ? [String(Number(item.value) + 1)]
                  : null;
            }
            temp.rawAnswer = temp.answer.map(v => item.choices[v - 1].label);
            temp.choices = item.choices.map(v => String(v.score));
            break;
          // 矩阵题
          case this.QUESTION_TYPE_MATRIX:
            let matrixValue = [];
            item.matrix.map((v, i) => {
              v.map((vv, ii) => {
                let obj = {};
                if (vv) {
                  console.log(ii);
                  obj["xKey"] = item.rows[i].attr;
                  obj["xText"] = item.rows[i].label;
                  obj["yKey"] = item.columns[ii].attr;
                  obj["yText"] = item.columns[ii].label;
                  matrixValue.push(obj);
                }
              });
            });
            temp.matrixValue = matrixValue;
            break;
          // 组合题目
          case this.QUESTION_TYPE_COMBINATION:
            let list = [];
            item.children.map(v => {
              list.push(Object.values(this.formatItemValOfGroup(v)));
            });
            console.log("组合题", list);
            temp.rawAnswer = list;
            break;
        }
        list.push(temp);
      });
      // initParser(list)
      console.log(list);
      let isAllAnswer = false;
      let index = list.findIndex(v => {
        if (v.config && v.config.required) {
          if (Array.isArray(v.answer)) {
            return !v.answer.length;
          } else {
            return !v.answer;
          }
        }
      });
      if (index < 0) {
        isAllAnswer = true;
      }
      console.log(index);
      return { list, isAllAnswer: isAllAnswer };
    },
    save() {
      console.log(this.noAnswer);
      let list = this.formatResultList(this.noAnswer);

      console.log("list==>", list);
      let result = this.formatData(list);
      console.log("result");
      console.log(result);
      let isAllAnswer = false;
      let unansweredInfo = list.find(v => {
        // if(v.config.required) {
        //      if( Array.isArray(v.value))return !v.length;
        //     return !v;
        // }
        return (
          v.config.required &&
          (Array.isArray(v.value) ? !v.value.length : empty(v.value))
        );
      });
      console.log("unansweredInfo==>,", unansweredInfo);
      if (unansweredInfo && unansweredInfo.number) {
        if (!unansweredInfo.value) {
          isAllAnswer = false;
        } else if (
          Array.isArray(result.q[unansweredInfo.number]) &&
          result.q[unansweredInfo.number].length == 0
        ) {
          isAllAnswer = false;
        } else {
          isAllAnswer = true;
        }
      } else {
        isAllAnswer = true;
      }

      for (let k in result.q) {
        if (!result.q[k]) {
          delete result.q[k];
        }
      }
      console.log(isAllAnswer);

      return { list: result.q, isAllAnswer };
      // return false
      // const { data } = await resolvingDslLogic({
      //   ...route.query,
      //   questions: result.q,
      //   targets: result.t,
      //   lang: 'php',
      //   survey_id: state.survey_id
      // })
      console.log(data);
      console.log(data.assess);
    },
    formatData(list) {
      let res = {};
      let tar = {};
      list.forEach(v => {
        if (v.belongIndicator) {
          let k = v.belongIndicator.var.replace(/target/, "T");
          if (!tar[k]) {
            tar[k] = {};
          }
          if (v.children && v.children.length) {
            let temp = [];
            v.value.forEach(v2 => {
              let tempItem = {};
              v.children.forEach((child, idx2) => {
                if (!tar[k][child.attr]) {
                  tar[k][child.attr] = [];
                }
                tar[k][child.attr].push(v2[idx2]);
                tempItem[child.attr] = v2[idx2];
              });
              temp.push(tempItem);
            });
            res[v.number] = temp;
          } else {
            tar[k][v.attr] = v.isRepeat ? v.value : this.formatItemVal(v);
            res[v.number] = Array.isArray(v.value) ? [...v.value] : v.value;
          }
        } else {
          res[v.number] = v.isRepeat ? v.value : this.formatItemVal(v);
        }
      });
      return {
        t: tar,
        q: res
      };
    },

    formatResultList(arr) {
      let list = [];
      let repeatKey = [];
      arr.forEach(v => {
        if (v.isRepeat) {
          if (!repeatKey.includes(v.number)) {
            let temp = {
              ...v,
              value: []
            };
            repeatKey.push(v.number);
            temp.value = arr
              .filter(v2 => v2.number === v.number)
              .map(this.formatItemVal);
            list.push(temp);
          }
        } else {
          list.push(v);
        }
      });
      return list;
    },
    formatItemVal(item) {
      try {
        if (item.type === this.QUESTION_TYPE_COMBINATION) {
          item.value = item.children.map(this.formatItemVal);
          return item.value;
        } else if (item.type === this.QUESTION_TYPE_MATRIX) {
          let res = [];
          item.matrix.forEach((cols, k1) => {
            cols.forEach((c, k2) => {
              c && res.push(item.rows[k1].label + "" + item.columns[k2].label);
            });
          });
          item.value = res;
          return res;
        } else if (item["choices"].length) {
          return Array.isArray(item.value)
            ? item.value.map(c =>
                item["choices"][c].isInput
                  ? item["choices"][c].extra
                  : item["choices"][c].label
              )
            : item["choices"][item.value].label;
        } else {
          return item.value;
        }
      } catch (error) {}
    },

    formatItemValOfGroup(item) {
      let temp = {
        type: item.type,
        answer: "",
        rawAnswer: item.value,
        choices: [],
        code: item.sn,
        multipleAnswers: item.isMultiple || false,
        qKey: item.attr
      };
      let obj = {};
      obj[item.sn] = {
        type: item.type,
        questionNo: item.sn,
        multipleAnswers: item.isMultiple || false
      };
      try {
        if (item.type === this.QUESTION_TYPE_COMBINATION) {
          temp = item.children.map(this.formatItemVal);
        } else if (item.type === this.QUESTION_TYPE_MATRIX) {
          // let res = [];
          // item.matrix.forEach((cols, k1) => {
          //   cols.forEach((c, k2) => {
          //     c && res.push(item.rows[k1].label + "" + item.columns[k2].label);
          //   });
          // });
          // item.value = res;
          // return res;
          let matrixValue = [];
          item.matrix.map((v, i) => {
            v.map((vv, ii) => {
              let obj = {};
              if (vv) {
                console.log(ii);
                obj["xKey"] = item.rows[i].attr;
                obj["xText"] = item.rows[i].label;
                obj["yKey"] = item.columns[ii].attr;
                obj["yText"] = item.columns[ii].label;
                matrixValue.push(obj);
              }
            });
          });
          obj["matrixAnswers"] = matrixValue;
        } else if (item.type == this.QUESTION_TYPE_CHECKBOX) {
          const choices = item.choices
            .map(v => {
              return {
                label: v.label,
                attr: v.attr
              };
            })
            .sort((a, b) => a - b);
          let answer = item.value
            ? item.value.map(v => {
                return {
                  value: choices[Number(v)].label,
                  key: choices[Number(v)].attr
                };
              })
            : [];
          obj[item.sn]["checkboxAnswers"] = answer;
          return obj;
        } else if ((item.type = this.QUESTION_TYPE_RADIO)) {
          const choices = item.choices.map(v => {
            return {
              label: v.label,
              attr: v.attr
            };
          });
          const answer =
            item.value || item.value === 0
              ? {
                  key: choices[Number(item.value)].attr,
                  value: choices[Number(item.value)].label
                }
              : null;
          obj[item.sn]["answer"] = answer;
        } else {
          return obj;
        }
      } catch (error) {}
      return obj;
    }
  }
};

// const len = (arg: any[] | string) => (typeof arg == 'number' ? arg : arg.length)

// onMounted(() => {
//   if ('scrollRestoration' in history) {
//     history.scrollRestoration = 'manual'
//   }
//   inputBlur()
//   init()
// })
</script>

<style lang="scss">
body {
  overflow-x: hidden;
}
.home {
  height: 100%;
  overflow-x: hidden;
  overflow-y: auto;
  padding-bottom: 140px;
  box-sizing: border-box;
  .dialogue-list {
    box-sizing: border-box;
    padding-top: 20px;
  }
  .dialogue-item {
    // display: flex;
    // justify-content: flex-start;
    // align-items: flex-start;
    margin-bottom: 15px;
    transition: all 0.3s linear;
    transform: translateZ(0);
  }
  .survey-title {
    font-size: 15px;
  }
  .survey-desc {
    font-size: 12px;
    color: #666;
    margin-top: 5px;
  }
  .survey-tag {
    position: absolute;
    right: 0;
    top: 0;
    color: #fff;
    padding: 4px 10px;
    font-size: 12px;
    border-radius: 0 10px 0 10px;
    background: linear-gradient(to right, #fea36c 0%, #fb7654 100%);
  }
  .avatar {
    border-radius: 4px;
    width: 45px;
    height: 45px;
    margin: 0 10px;
    overflow: hidden;
    border-radius: 50%;
  }
  .dialogue-content {
    max-width: 70%;
    border-radius: 10px;
    border-top-left-radius: 0;
    background: #fff;
    // box-shadow: 1px 1px 2px #ccc;
    padding: 10px;
    box-sizing: border-box;
    position: relative;
    img {
      max-width: 100%;
    }
    .gender-select {
      width: 180px;
      padding: 20px 0 10px;
      display: flex;
      align-items: center;
      justify-content: space-around;
      .gender-item {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        font-size: 14px;
        color: #999;
        cursor: pointer;
        img {
          border-radius: 50%;
        }
        span {
          margin-top: 4px;
        }
        &.active {
          img {
            border: 1px solid #4b72f6;
          }
          span {
            color: #4b72f6;
          }
        }
      }
    }
    .link {
      margin-top: 10px;
    }
    .confirm-btn {
      min-width: 60%;
      margin: 15px auto 0;
      background: #4b72f6;
    }
    .confirm-input {
      border-color: #dbe0ef;
    }
    .confirm-input-btn {
      border-radius: 4px;
    }
    .answer-btn {
      background: #f5f5f5;
      border-radius: 4px;
      border: 0;
      display: block;
      width: 100%;
      padding: 8px 15px;
      box-sizing: border-box;
      position: relative;
      cursor: pointer;
      &:before {
        content: "";
        background: #4b72f6;
        width: 4px;
        height: 4px;
        display: inline-block;
        vertical-align: middle;
        border-radius: 50%;
        position: absolute;
        left: 5px;
        top: 50%;
        margin-top: -2px;
      }
      &.active {
        color: #4b72f6;
        background: #edf2fe;
      }
    }
  }
  .cur-answer {
    .dialogue-content {
      border-top-left-radius: 10px;
      border-top-right-radius: 0;
      background: #4b72f6;
      color: #fff;
    }
  }
  .full-btn {
    display: block;
    background: #4b72f6;
    border: 0;
    color: #fff;
    text-shadow: 1px 1px 1px #643d066c;
    font-size: 16px;
    letter-spacing: 2px;
    cursor: pointer;
    border-radius: 4px;
    height: 40px;
    line-height: 40px;
    margin-top: 20px;
  }
}
</style>
