<template>
  <div ref="home" class="home">
    <div class="dialogue-list">
      <el-scrollbar height="calc(50vh)">
        <div
          v-for="(item, surveyIndex) in showList"
          :key="surveyIndex"
          class="dialogue-item m-1 bg-gray-100 rounded p-4 mb-3"
        >
          <QuestionItem
            :info="item"
            :hide-list="hideList"
            :repeat-answer="item.isAnswered && lastIndex === surveyIndex"
            class="dialogue-content"
            @skip="skip"
            @back="back"
            @reply="reply"
            @check="check"
          />
        </div>
      </el-scrollbar>
      <div class="text-right">
        <div class="dialogue-content">
          <span>{{ state.detail.endingText }}</span>
          <el-button
            block
            type="primary"
            @click="save"
            :loading="state.loading"
          >
            提交
          </el-button>
        </div>
      </div>
      <!-- <template v-if="state.inputLoading">
        <div
          class="dialogue-item animate__animated animate__faster animate__slideInLeft"
        >
          <van-image class="avatar" :src="state.detail.systemAvatar" />

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

<script setup>
// import { resolvingDslDecision, surveyByCode } from '../utils/axios'
import { request, parseJSON, deepClone, debounceWithImmediate } from "@/utils";
// import { showNotify, Toast, showConfirmDialog } from "vant";

import QuestionItem from "./questionItem.vue";
import dayjs from "dayjs";
import {
  onMounted,
  nextTick,
  computed,
  watch,
  ref,
  reactive,
  defineProps,
  defineEmits
} from "vue";
import { unique } from "@/utils/index";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
const QUESTION_TYPE_TEMP_CHECK = "temp_check";
const QUESTION_TYPE_ANSWER = "answer";
const QUESTION_TYPE_INPUT = "input";
const QUESTION_TYPE_TEXT = "text";
const QUESTION_TYPE_CHECKBOX = "checkbox";
const QUESTION_TYPE_RADIO = "radio";
const QUESTION_TYPE_SELECT = "select";
const QUESTION_TYPE_RATING_SCALE = "rating_scale";
const QUESTION_TYPE_RATING = "rating";
const QUESTION_TYPE_DATE = "date";
const QUESTION_TYPE_UPLOAD = "upload";
const QUESTION_TYPE_MATRIX = "matrix_checkbox";
const QUESTION_TYPE_COMBINATION = "combination";
const QUESTION_TYPE_GROUP = "group"; // 组合题
const route = useRoute();
const router = useRouter();
const emits = defineEmits(["onSave"]);
const props = defineProps({
  content: {
    type: Object,
    default: () => {
      return {
        content: {},
        logicCode: {}
      };
    }
  }
});
const state = reactive({
  loading: false,
  detail: {
    id: "",
    title: "",
    sn: "",
    questions: [],
    survey_rules: {
      status: ""
    },
    greetingText: "",
    endingText: "",
    memberAvatar: "",
    systemAvatar: "",
    peg: "",
    updated_at: ""
  },
  questionResult: {
    id: "",
    surveyMechanismId: ""
  },
  index: 0,
  isFinished: false,
  loading: null,
  inputLoading: false,
  survey_id: "",
  replyLock: false,
  logicRulesList: []
});
const currentValue = ref("");
const rawList = ref([]);
const showList = ref([]);
const _showList = ref([]);
const noAnswer = computed(() =>
  showList.value.filter(
    v =>
      ![
        QUESTION_TYPE_TEXT,
        QUESTION_TYPE_ANSWER,
        QUESTION_TYPE_TEMP_CHECK
      ].includes(v.type)
  )
);
const hideList = ref([]);

const lastIndex = computed(() => {
  for (let i = showList.value.length - 1; i >= 0; i--) {
    if (showList.value[i]?.isAnswered) {
      return i;
    }
  }
  return 0;
});

const rules = ref([]);
const checkDisabled = ref(false);

const home = ref();

const pushText = (text, time, isHtml = false) => {
  return new Promise((resolve, reject) => {
    showList.value.push({
      title: text,
      config: {
        desc: "",
        required: true
      },
      isHtml,
      type: QUESTION_TYPE_TEXT
    });
    setTimeout(() => {
      resolve(1);
    }, time || 8e2);
  });
};

const skip = item => {
  console.log(item);
  item.isAnswered = true;
  item.isSkip = true;
  next(item);
};
const back = item => {
  if (state.replyLock) return;
  const backList = rules.value[`QU${item.code}`]
    ?.filter(v => v.method === "hide" && v.expression.includes(item.code))
    .map(v => v.question)
    .flat();
  console.log(item);
  console.log(rules.value[`QU${item.code}`]);
  console.log(hideList.value);

  console.log(backList);
  if (backList?.length) {
    backList.forEach(k => {
      const delIdx = hideList.value.findIndex(v => v == k);
      delIdx >= 0 && hideList.value.splice(delIdx, 1);
    });
  }
  showList.value.splice(
    lastIndex.value + 1,
    showList.value.length - lastIndex.value
  );
  item.isAnswered = false;
  item.value = "";
  state.isFinished = false;
};

const scrollToLast = () => {
  const last = home.value?.querySelector(".dialogue-item:last-of-type");
  home.value?.scrollTo(
    0,
    last ? last.offsetTop - 40 : home.value?.scrollHeight
  );
};
const check = (item, flag) => {
  if (item.isRepeat) {
    repeat(item, flag);
  } else if (item.isEnd) {
    console.log(item);
    showList.value.splice(showList.value.length - 1, 1);
    if (flag) {
      state.isFinished = true;
    } else {
      next(noAnswer.value.at(-1), false);
    }
    scrollToLast();
  }
};

const repeat = (item, flag) => {
  console.log(item);
  if (flag) {
    showList.value.splice(showList.value.length - 1, 1);
    nextTick(() => {
      const item = JSON.parse(JSON.stringify(noAnswer.value.at(-1)));
      if (
        item.type === QUESTION_TYPE_COMBINATION ||
        item.type === QUESTION_TYPE_GROUP
      ) {
        item.children = item.children.map(v => {
          v.value = Array.isArray(v.value) ? [] : "";
          return v;
        });
      }
      // showList.value.push({
      //   ...item,
      //   isAnswered: false,
      //   value: ""
      // });
      // scrollToLast();
    });
  } else {
    showList.value.splice(showList.value.length - 1, 1);
    next(noAnswer.value.at(-1));
  }
};

const reply = (item, text) => {
  if (currentValue.value === item.value) return;
  currentValue.value = item.value;

  // showList.value.push({
  //   left: false,
  //   title: text,
  //   type: QUESTION_TYPE_ANSWER,
  //   isAnswered: true,
  //   isRequired: true,
  //   config: {
  //     required: true
  //   }
  // });
  if (item.isRepeat) {
    showList.value.push({
      title: "是否再增加一条记录？",
      config: {
        desc: "",
        required: true
      },
      isRepeat: true,
      type: QUESTION_TYPE_TEMP_CHECK
    });
    console.log(showList.value);
    scrollToLast();
    return;
  }
  initShowList();
};
const initShowList = () => {
  if (state.loading) return;
  state.loading = true;
  hideList.value = [];
  state.logicRulesList = [rawList.value[0]];
  _showList.value = unique([...rawList.value, ...showList.value], "sn");

  _showList.value?.map(item => {
    next(item);
  });
  setTimeout(() => {
    showList.value = removeDataBetweenDuplicates(state.logicRulesList, "sn");
    state.loading = false;
  }, 1000);
};
const getItem = code => {
  code = code.replace(/^QU/, "");
  return rawList.value.find(v => v.sn === code);
};
const getQ = code => {
  code = code.replace(/^QU/, "");
  const items = showList.value.filter(v => v.sn === code);
  const item = getItem(code);
  console.log(showList.value);
  console.log(items);
  if (items.length > 1) {
    return items.map(formatItemVal);
  }
  const val = item.value;

  if (item.type === QUESTION_TYPE_RADIO) {
    return [val];
  } else if (item.type === QUESTION_TYPE_CHECKBOX) {
    return val || [];
  }
  return item.value;
};

const getS = number => {
  const q = number.match(/Q\d+/)[0];
  const s = Number(number.match(/S\d+/)[0]?.slice(1)) - 1;
  const a = number.includes("A")
    ? Number(number.match(/A\d+/)[0].slice(1)) - 1
    : "";
  console.log(
    `当前获取${number} 获取到的q: ${q} ，获取到的s: ${s} ，获取到的a: ${a}`
  );
  return a ? getItem(q).matrix[s][a] : getItem(q).matrix[s];
};

const getA = number => {
  const q = number.match(/Q\d+/)[0];
  const a = Number(number.match(/A\d+/)[0].slice(1)) - 1;
  console.log(`当前获取${number} 获取到的q: ${q} ，获取到的a: ${a}`);
  console.log(`获取到的q:`);
  console.log(Array.isArray(getQ(q)), getQ(q), typeof a, a);
  const qVal = Array.isArray(getQ(q)) ? getQ(q).map(String) : getQ(q) || "";
  return qVal.includes(String(a));
};

const getVal = code => {
  // return number.includes('S') ? getS(number) .includes('A') ? getA(number) : getQ(number)
  return getQ(code);
};

const getRuleKey = type => {
  switch (type) {
    case "showHide":
    case "to":
      return "expression";
    case "say":
    case "replace":
      return "keyword";
    default:
      return "";
  }
};
const 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));
};
const chooseAnd = (itemVal, ...choices) => {
  for (const idx of choices) {
    if (!itemVal.includes(idx)) return false;
  }
  return true;
};
const chooseOr = (itemVal, ...choices) => {
  for (const idx of choices) {
    if (itemVal.includes(idx)) return true;
  }
  return false;
};
const chooseMatrix = (itemVal, ...values) => {
  for (const v of values) {
    if (!itemVal.includes(v)) return false;
  }
  return true;
};
const chooseMatrixOr = (itemVal, ...values) => {
  for (const v of values) {
    if (!itemVal.includes(v)) return true;
  }
  return false;
};
const isEmpty = val => {
  if (Array.isArray(val)) {
    return !val.length;
  }
  if (val === 0) return false;
  return !val;
};
const count = arg => (typeof arg == "number" ? arg : arg.length);

window["formatAge"] = formatAge;
window["chooseAnd"] = chooseAnd;
window["chooseOr"] = chooseOr;
window["chooseMatrix"] = chooseMatrix;
window["chooseMatrixOr"] = chooseMatrixOr;
window["isEmpty"] = isEmpty;
const formatQuKey = key => (/^QU/.test(key) ? key.replace(/^QU/, "") : key);
const customFunc = [
  "formatAge",
  "chooseAnd",
  "chooseOr",
  "chooseMatrix",
  "count"
];
const formatRule = rule => {
  const getQAReg = new RegExp(/QU(\w+)?/gi);
  let rawCondition = rule[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);
    qa.map(n => {
      const code = formatQuKey(n);
      const curItem = getItem(code);
      const v = getVal(code);
      console.log("获取到的值：", n, "：", v);
      // 存在自定义方法
      for (const func of customFunc) {
        if (condition.includes(func)) {
          // 选择类方法
          if (/^choose/.test(func)) {
            if (func.includes("Matrix")) {
              curItem.rows.forEach(row => {
                curItem.columns.forEach(col => {
                  const matrixAttr = row.attr + col.attr;
                  if (condition.includes(matrixAttr)) {
                    condition = condition.replace(
                      new RegExp(matrixAttr),
                      `"${row.label + col.label}"`
                    );
                  }
                });
              });
            } else {
              let sortChoices = curItem.choices.map((v, k) => {
                return {
                  ...v,
                  index: k
                };
              });
              sortChoices = sortChoices.sort(
                (a, b) => b.attr.length - a.attr.length
              );
              sortChoices.forEach(v => {
                if (condition.includes(v.attr)) {
                  condition = condition.replace(new RegExp(v.attr), v.index);
                }
              });
            }
          }
        }
      }
      const 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 = false;
  try {
    flag = eval(condition);
  } catch (e) {
    console.log(e);

    flag = false;
  }
  console.log(`当前规则执行的flag: %c ${flag}`, "color: #f00;");

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

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

      {
        let t = undefined;
        const q = 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}`);

        getItem(rule.to).title = getItem(rule.to).title?.replace(
          replaceReg,
          Array.isArray(t) ? t.join(",") : t
        );
      }
      break;
    case "end":
      showList.value.push({
        title: "是否结束答题？",
        config: {
          desc: "",
          required: true
        },
        isEnd: true,
        type: QUESTION_TYPE_TEMP_CHECK
      });
      return {
        type: "end"
      };
  }
};
const removeDataBetweenDuplicates = (array, key = "id") => {
  const seenIds = new Set(); // 存储已经遍历到的id
  const result = []; // 新数组

  for (let i = 0; i < array.length; i++) {
    const currentId = array[i][key];

    if (!seenIds.has(currentId)) {
      // 如果 id 没有出现过，加入结果集
      result.push(array[i]);
      seenIds.add(currentId); // 标记为已见过
    } else {
      // 如果发现了重复的 id，删除当前结果集之后重复 id 之前的数据
      const duplicateIndex = result.findIndex(item => item[key] === currentId);
      result.splice(duplicateIndex + 1);
    }
  }

  return result;
};

const next = async (item, runRule = true, index) => {
  state.replyLock = true;
  console.log("规则判断");
  const rule = rules.value[`QU${item.sn}`];
  console.log(rules.value);
  console.log(rule);
  console.log("当前item");
  console.log(item);
  console.log(getItem(item.sn));
  console.log(getQ(item.sn));
  console.time("规则执行");
  console.log("==================start=====================");
  let to = undefined;
  try {
    if (runRule) {
      for (const i in rule || []) {
        console.log("执行规则", i + 1, "-----type:", rule[i].type);
        const res = formatRule(rule[i]) || {};
        switch (res.type) {
          case "to":
            to = res.to || undefined;
            break;
          case "say":
            res.say && (await pushText(res.say || "", 0, true));
            break;
          case "end":
            state.replyLock = false;
            return;
        }
      }
    }
  } catch (e) {
    console.log("报错了");
    console.log(e);
    // showNotify(e?.message);
    ElMessage.error(e?.message);
  }
  console.log("==================end=======================");
  console.log(to);
  console.timeEnd("规则执行");

  state.inputLoading = true;
  nextTick(() => {
    setTimeout(() => {
      state.inputLoading = false;
      if (to) {
        console.log("存在to跳转", to);
        if (to.toLocaleLowerCase() === "end") {
          state.isFinished = true;
        } else {
          console.log("to跳转", getItem(to));
          // showList.value.push(getItem(to));
          state.logicRulesList.push(getItem(to));
          // showList.value.splice(state.index, spliceIndex);
        }
      } else {
        console.log("不存在to跳转");
        console.log(hideList.value);
        // state.index = Number(item.number.match(/Q\d+/gi)[0].slice(1))
        state.index = findNoHideQuestion(
          rawList.value.findIndex(v => v.sn == item.sn) + 1
        );
        console.log(`当前index: ${state.index}`);
        console.log(rawList.value[state.index]);
        if (state.index >= rawList.value.length) {
          state.isFinished = true;
        } else {
          // showList.value.push(rawList.value[state.index]);
          state.logicRulesList.push(rawList.value[state.index]);
        }
      }
      state.replyLock = false;
      localStorage.setItem(
        `temp_q3_${route.query.id}`,
        JSON.stringify({
          state,
          rawList: rawList.value,
          showList: showList.value,
          hideList: hideList.value,
          rules: rules.value
        })
      );
      console.log("logicRulesList", state.logicRulesList);
      console.log("logicRulesList", showList.value);

      nextTick(() => {
        scrollToLast();
        if (state.isFinished) return;
      });
    }, 500);
  });
};
const findNoHideQuestion = index => {
  if (index >= rawList.value.length) return rawList.value.length;
  if (hideList.value.includes(`QU${rawList.value[index].sn}`)) {
    return findNoHideQuestion(index + 1);
  } else {
    return index;
  }
};
const recover = async () => {
  const tempQuestions = JSON.parse(
    localStorage.getItem(`temp_q3_${route.query.id}`)
  );
  if (tempQuestions) {
    if (tempQuestions?.state?.detail?.updated_at != state?.detail?.updated_at) {
      return localStorage.removeItem(`temp_q3_${route.query.id}`);
    }
    console.log("存在缓存题目");
    return;
    const dialog = await showConfirmDialog({
      title: "提示",
      message: "存在答题记录，是否使用之前的答题记录？",
      confirmButtonColor: "#4B72F6"
    }).catch(() => {});

    if (dialog === "confirm") {
      Object.keys(tempQuestions.state).forEach(key => {
        if (key != "questionResult") {
          state[key] = tempQuestions.state[key];
        }
      });

      rawList.value = tempQuestions.rawList;
      showList.value = tempQuestions.showList;
      hideList.value = tempQuestions.hideList;
      rules.value = tempQuestions.rules;
      setTimeout(() => {
        scrollToLast();
      }, 0);
    }
  }
};
const formatResultList = arr => {
  console.log("formatResultList执行成功", arr);

  const list = [];
  const repeatKey = [];

  arr.forEach(v => {
    if (v.isRepeat) {
      if (!repeatKey.includes(v.sn)) {
        const temp = {
          ...v,
          value: []
        };
        repeatKey.push(v.sn);
        const cur = arr.filter(v2 => v2.sn === v.sn);
        console.log("cur", cur);

        temp.value = cur.map(formatItemVal);

        temp.rawValue = cur.map(v2 => {
          if (v.type == QUESTION_TYPE_GROUP) {
            return v2.children.map(v3 => v3.value);
          } else {
            return v2.value;
          }
        });
        console.log(temp.value, temp.rawValue);
        list.push(temp);
      }
    } else {
      console.log(v.type == QUESTION_TYPE_GROUP && "出现组合题", v);
      if (v.type == QUESTION_TYPE_GROUP) {
        list.push({
          ...v,
          rawValue: v.children.map(child => child.value),
          value: formatItemVal(v)
        });
      } else {
        list.push({
          ...v,
          rawValue: v.value,
          value: formatItemVal(v)
        });
      }
    }
  });
  return list;
};
const formatItemVal = item => {
  if (item.type === QUESTION_TYPE_GROUP) {
    item.value = item.children.map(v => formatItemVal(v));
    return item.value;
  } else if (item.type === QUESTION_TYPE_MATRIX) {
    const res = [];
    item.matrix?.forEach((cols, k1) => {
      cols &&
        cols.forEach &&
        cols?.forEach((c, k2) => {
          c && res.push(item.rows[k1].label + "" + item.columns[k2].label);
        });
    });
    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]?.isInput
      ? item["choices"][item.value]?.extra
      : item["choices"][item.value]?.label;
  } else {
    return item.value;
  }
};
const formatResultDataItem = item => {
  const resultItem = {
    multipleAnswers: item.isRepeat,
    type: item.type,
    questionNo: item.sn,
    checkboxAnswers: null,
    inputAnswers: null,
    matrixAnswers: null,
    linkAnswers: null,
    groupAnswers: null,
    answer: undefined
  };
  switch (item.type) {
    case QUESTION_TYPE_CHECKBOX:
      {
        const tmp = [];
        if (Array.isArray(item.rawValue)) {
          item.rawValue?.forEach((childIdx, k) => {
            const findChoices = item.choices[childIdx];
            tmp.push({
              key: findChoices?.attr,
              value: item.value[k]
            });
          });
        }
        resultItem.checkboxAnswers = tmp;
      }
      break;
    case QUESTION_TYPE_RADIO:
      {
        resultItem.answer = {
          key: item.choices[item.rawValue]?.attr,
          value: item.value
        };
      }
      break;
    case QUESTION_TYPE_SELECT:
      {
        resultItem.checkboxAnswers = item.value || [];
      }
      break;
    case QUESTION_TYPE_INPUT:
      {
        const tmp = {
          key: item.attr,
          value: []
        };
        if (item.isRepeat) {
          item.value?.forEach(val => {
            tmp.value.push(val);
          });
        } else {
          tmp.value = Array.isArray(item.value) ? item.value : [item.value];
        }
        tmp.value = tmp.value.map(String);
        resultItem.inputAnswers = tmp;
      }
      break;
    case QUESTION_TYPE_UPLOAD:
      {
        const tmp = {
          key: item.attr,
          value: []
        };
        tmp.value = Array.isArray(item.value) ? item.value : [item.value];
        resultItem.linkAnswers = tmp;
      }
      break;
    case QUESTION_TYPE_DATE:
      {
        resultItem.answer = {
          key: item.attr,
          value: Array.isArray(item.value) ? item.value[0] : item.value
        };
      }
      break;
    case QUESTION_TYPE_MATRIX:
      resultItem.matrixAnswers = [];
      item.matrix.forEach((cols, k1) => {
        cols.forEach((check, k2) => {
          if (check) {
            resultItem.matrixAnswers.push({
              xKey: item.rows[k1].attr,
              xText: item.rows[k1].label,
              yKey: item.columns[k2].attr,
              yText: item.columns[k2].label
            });
          }
        });
      });
      break;
    case QUESTION_TYPE_GROUP:
      resultItem.groupAnswers = [];
      (item.isRepeat ? item.value : [item.value])?.forEach((val, k) => {
        const temp = [];
        item.children.forEach((child, childIdx) => {
          temp.push(
            formatResultDataItem({
              ...child,
              rawValue: item.isRepeat
                ? item.rawValue[k][childIdx]
                : item.rawValue[childIdx],
              value: val[childIdx]
            })
          );
        });
        resultItem.groupAnswers.push(temp);
      });
      break;
  }
  console.log(item, resultItem);
  return resultItem;
};
const formatData = list => {
  const result = {};
  list.forEach(v => {
    result[v.sn] = formatResultDataItem(v);
  });
  return result;
};
const startTime = ref();
const save = async () => {
  state.loading = true;
  const list = formatResultList(noAnswer.value);
  // const _ruleList = unique(state.logicRulesList, "sn");
  // console.log("_ruleList", _ruleList);
  setTimeout(() => {
    const isAllAnswer = list?.some(v => {
      return v.config.required && !isNonZero(v.value);
    });
    state.loading = false;
    if (isAllAnswer) {
      return ElMessage.error("请回答问卷必答题");
    }
    emits("onSave", {
      questions: _showList.value,
      viewQuestions: list
    });
  }, 700);

  return;
  const { data } = await request.post(
    "/surveyService/member/customSurvey/answer",
    {
      surveyId: route.query.id,
      startTime: startTime.value,
      answerRaw: JSON.stringify(list)
    }
  );
  router.push({
    name: route.query.redirectPath || "customResult",
    query: {
      id: data.id,
      surveyMechanismId: route.query.id,
      _r: Date.now(),
      back: route.query.token ? undefined : 1
    }
  });
};

const isNonZero = value => {
  // 检验值是否为空（null, undefined, "" 或者 false）
  if (value == null || value === "" || value === false) {
    return false;
  }
  // 对于对象，检验是否有属性
  if (typeof value === "object" && Object.keys(value).length === 0) {
    return false;
  }
  // 其他情况视为非空
  return true;
};
const init = async () => {
  startTime.value = dayjs(Date.now()).format("YYYY-MM-DD HH:mm:ss");
  // const { data: surveyData } = await request.get(
  //   "/surveyService/member/customSurvey/detail",
  //   {
  //     params: route.query
  //   }
  // );

  const surveyData = {
    detail: {
      content: {
        content: [],
        logicCode: []
      }
    }
  };

  if (props.content?.content) {
    surveyData.detail.content.content = deepClone(props.content?.content || []);
  }
  if (props?.content?.logicCode) {
    surveyData.detail.content.logicCode = deepClone(
      props?.content?.logicCode || []
    );
  }
  state.detail = surveyData.detail;
  state.detail.questions = surveyData.detail.content.content;
  console.log("state.detail.questions", state.detail.questions);
  // showList.value = [state.detail.questions[0]];
  rawList.value = state.detail.questions;
  // let peg = null;
  // try {
  //   peg = state.detail.peg ? JSON.parse(state.detail.peg) : {};
  // } catch (e) {
  //   console.log(e);
  //   peg = {};
  // }
  const r = {};
  surveyData.detail.content.logicCode?.length &&
    surveyData.detail.content.logicCode.forEach(v => {
      const code = `QU${v.condition}`;
      if (!r[code]) {
        r[code] = [];
      }
      r[code].push(v);
    });

  console.log("props?.content?.logicCode", props?.content?.logicCode);

  rules.value = r;
  console.log("state.detail");
  console.log(state.detail);
  console.log("rules.value");
  console.log(rules.value);

  showList.value = rawList.value;
  showList.value?.forEach(v => {
    if (isNonZero(v?.rawValue)) {
      v.value = v.rawValue;
    }
  });
  initShowList();
  console.log("showList", showList.value);
  console.log("hideList", hideList.value);
};
onMounted(() => {
  if ("scrollRestoration" in history) {
    history.scrollRestoration = "manual";
  }
  // route.query.token && setSurveyToken(route.query.token);
  // inputBlur();
  // init();
});
defineExpose({
  init
});
</script>

<style lang="scss">
body {
  // height: 100%;
  -moz-osx-font-smoothing: grayscale;
  -webkit-font-smoothing: antialiased;
  text-rendering: optimizeLegibility;
  font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB,
    Microsoft YaHei, Arial, sans-serif;
  background: #f6f9ff;
  overflow-x: hidden;
}
.home {
  overflow-x: hidden;
  overflow-y: auto;
  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%;
    width: 100%;
    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>
