import { AnswerApi } from '../js/api';
import { computed, getCurrentInstance, defineComponent, provide, ref, watch } from 'vue';
import answerMock from './mock';
import { useRoute } from 'vue-router';
import msg from './message';
import LangTranslate from '../components/LangTranslate.vue';
import { useQuestionStore } from '@/stores/Questions/useQuestionStore.ts';
import { storeToRefs } from 'pinia';

export default defineComponent({
  components: {
    LangTranslate
  },
  props: {
    // 是否答题模式
    isAnswer: {
      type: Boolean,
      default: false
    },
    // 是否模板预览
    isTemplate: {
      type: Boolean,
      default: false
    }
  },
  setup(props) {
    const questionStore = useQuestionStore();
    /**
     * styleInfo 主题样式
     */
    const { questionsData, styleInfo, page, pages } = storeToRefs(questionStore);
    const route = useRoute();
    // const questionsData = inject('questionsData'); // 问卷数据

    const translatedText = computed(() => questionsData.value.language || {});
    // 开始答题时间戳
    const startAnswerTime = new Date().getTime();
    const { proxy } = getCurrentInstance();
    const scrollbar = ref(null);
    let localPageInterval;

    watch(
      styleInfo,
      (style) => {
        // console.log(`style value: `, style);
        if (questionsData.value?.survey?.style && !style.is_home && !page.value) {
          page.value = 1;
        }
      },
      { immediate: true }
    );
    // 主题颜色
    const themeColor = computed(() => ({
      stemColor: styleInfo.value.stem_color,
      answerColor: styleInfo.value.answer_color,
      buttonColor: styleInfo.value.button_color,
      buttonTextColor: styleInfo.value.button_text_color
    }));
    provide('themeColor', themeColor);

    // 当前页问卷
    const questions = computed(() => {
      const currentPages = pages.value[page.value - 1] || [];
      return (questionsData.value?.questions || []).filter((quetion) =>
        currentPages.find((index) => quetion.question_index === index)
      );
    });
    // 是否显示分页器
    const showPage = computed(() => {
      return ![102, 104, 105, 201].includes(questions.value[0]?.question_type);
    });

    // 分页计时器
    watch(
      page,
      () => {
        localPageTimer.value = {};
        clearInterval(localPageInterval);
        const lastQuestionIndex = questions.value.slice(-1)[0]?.question_index;
        // console.log(questionsData.value);
        const localPage = questionsData.value?.survey?.local_pages.find(
          (localPage) =>
            localPage.question_index === lastQuestionIndex && localPage.timer_config.is_short_time
        );
        if (localPage) {
          localPageTimer.value = localPage.timer_config;
          localPageTimer.value.short_time = localPageTimer.value.short_time * 1;
          localPageInterval = setInterval(() => {
            if (localPageTimer.value.short_time === 0) {
              // 停止计时
              return clearInterval(localPageInterval);
            }
            localPageTimer.value.short_time -= 1;
          }, 1000);
        }
      },
      {
        deep: true,
        immediate: true
      }
    );

    // 要搜索的数组和要查找的连续数字的数量n
    function hasNConsecutiveNumbers(arr, n, onTrue, onFalse) {
      let count = 1;
      let warnStart = 0;
      let prevNum = arr[0];
      for (let i = 1; i < arr.length; i++) {
        if (prevNum && arr[i] === prevNum) {
          count += 1;
        } else {
          count = 1;
          warnStart = i;
        }
        if (count === n) {
          if (onTrue) onTrue(warnStart, warnStart + n);
          return true;
        }
        prevNum = arr[i];
      }
      if (onFalse) onFalse();
      return false;
    }

    // 答题
    async function answer(callback, callbackBeforePage) {
      if ((questions.value.length || !questionsData.value.questions.length) && !props.isTemplate) {
        // 表单验证(当前页)
        const errors = questions.value.filter((question) => {
          const { config, answer, question_type: questionType } = question;
          let isError = false;
          if (config.is_required && !answer) {
            isError = true;
            if (questionType === 10) {
              // 矩阵多选题
              if (question.config.is_change_row_cell) {
                question.error = translatedText.value.PleaseSelectAtLeastOneOptionsPerColumn(
                  config.min_select || 1
                );
              } else {
                question.error = translatedText.value.PleaseSelectAtLeastOneOptionsPerLine(
                  config.min_select || 1
                );
              }
            } else if (questionType === 12) {
              // 图片显示题，如果开启了仅显示并且开启了单图显示时长，需要确保用户每一个图片都点开看过了才能下一页
              if (!answer?.read && config.picture_type === 0 && config.countdown_type === 1) {
                isError = true;
                question.error = translatedText.value.PleaseClickToViewAllPictures;
              }
            } else if (questionType === 15) {
              // 分类题
              question.error = translatedText.value.PleaseCategorizeAllOptions;
            } else if (!question.error) {
              question.error = translatedText.value.ThisIsARequiredQuestion;
            }
          } else if (
            answer &&
            questionType === 1 &&
            Object.keys(answer).findIndex((value) => !answer[value]) !== -1
          ) {
            // 单选题
            isError = true;
            question.error = translatedText.value.PleaseInputAValue;
          } else if (answer && questionType === 2) {
            // 多选题
            if (Object.keys(answer).length < config.min_select) {
              // 选项数量
              let options = [];
              question.list.forEach((list) => {
                options = [...options, ...list.options];
              });
              const index = options.findIndex(
                (option) => option.option_key === Object.keys(answer)[0] && option.is_remove_other
              );
              if (index === -1) {
                isError = true;
                question.error = translatedText.value.PleaseSelectAtLeastOneOptions(
                  config.min_select
                );
              } else {
                question.error = '';
              }
            } else if (Object.keys(answer).findIndex((value) => !answer[value]) !== -1) {
              isError = true;
              question.error = translatedText.value.PleaseInputAValue;
            } else {
              question.error = '';
            }
            if (!question.error) {
              // 选项分组最少选项数量
              config.option_groups?.option_group.some((optionGroup) => {
                const { min, title } = optionGroup;
                const select = optionGroup.groups.filter((groups) =>
                  Object.keys(answer).includes(groups.option_key)
                );
                if (title && select.length < min) {
                  // 判断隐藏选项
                  question.hideOptionsSet = new Set(question.hideOptions);
                  const options = question.list.flatMap((list) =>
                    list.options
                      .filter(({ option_key: optionKey }) =>
                        optionGroup.groups.some(
                          ({ option_key: groupKey }) =>
                            groupKey === optionKey && !question.hideOptionsSet.has(groupKey)
                        )
                      )
                      .map(({ option_key: optionKey }) => optionKey)
                  );
                  if (options.length >= min) {
                    isError = true;
                    question.error = translatedText.value.PleaseSelectAtLeastOneOptionsInTitleGroup(
                      min,
                      title
                    );
                  }
                }
                return isError;
              });
            }
          } else if (answer && questionType === 10) {
            // 矩阵多选题，列分组时，校验选项数量
            const cellGroups = (config?.cell_option_groups?.option_group || []).filter(
              (i) => i.groups?.length
            );
            if (cellGroups.length) {
              const rows = question.list.reduce(
                (p, c) => [...p, ...(c.type === 1 ? c.options || [] : [])],
                []
              );
              const cols = question.list.reduce(
                (p, c) => [...p, ...(c.type === 2 ? c.options || [] : [])],
                []
              );
              const freeCols = cols.filter(
                (col) =>
                  !cellGroups.some((g) => g.groups.find((c) => c.option_key === col.option_key))
              );

              const arr = rows.map((row) => {
                return cellGroups.map((group) => {
                  return group.groups.map((col) => {
                    return `${row.option_key}_${col.option_key}`;
                  });
                });
              });
              arr.forEach((a, idx) =>
                a.push(freeCols.map((col) => `${rows[idx].option_key}_${col.option_key}`))
              );
              const answered = Object.keys(answer);

              cellGroups.forEach((group, idx) => {
                if (!group.groups?.length || (!group.max && !group.min) || isError) {
                  return;
                }

                for (let i = 0; i < arr.length; i += 1) {
                  const row = arr[i];
                  const selectedCount = row[idx].filter((key) => answered.includes(key)).length;
                  if (group.min && selectedCount < group.min) {
                    isError = true;
                    question.error = translatedText.value.PleaseSelectAtLeastOneOptionsInTitleGroup(
                      group.min,
                      group.title
                    );
                    break;
                  }
                  if (group.max && selectedCount > group.max) {
                    isError = true;
                    question.error = translatedText.value.PleaseSelectAtMostOneOptionsInTitleGroup(
                      group.max,
                      group.title
                    );
                    break;
                  }
                }
              });
            }
            // 最少选择数量校验
            const minSelect = +config.min_select || 0;
            const perLineSelectedCount = Object.keys(answer).reduce(
              (p, c) => {
                if (+answer[c]) {
                  p[+c.split('_')[0] - 1] += 1;
                }
                return p;
              },
              question.list.filter((i) => i.type === 1).flatMap((i) => i.options.map(() => 0))
            );
            if (minSelect && minSelect > Math.max(...perLineSelectedCount)) {
              if (question.config.is_change_row_cell) {
                question.error = translatedText.value.PleaseSelectAtLeastOneOptionsPerColumn(
                  config.min_select || 1
                );
              } else {
                question.error = translatedText.value.PleaseSelectAtLeastOneOptionsPerLine(
                  config.min_select || 1
                );
              }
              isError = true;
            }
            // console.log('===', minSelect, Object.keys(answer), answer, perLineSelectedCount);
          } else if (answer && questionType === 12) {
            question.error = '';
          } else if (
            answer &&
            questionType === 14 &&
            Object.keys(answer).length < config.min_select
          ) {
            // 图片多选题
            isError = true;
            question.error = translatedText.value.PleaseSelectAtLeastOnePictures(config.min_select);
          } else if (answer && questionType === 16) {
            // 排序题
            if (Object.keys(answer).length < (+config.min_select || 0)) {
              // 选项数量
              isError = true;
              question.error = translatedText.value.PleaseSelectAtLeastOneOptions(
                config.min_select
              );
            }
          } else if (answer && questionType === 17) {
            // 恒定总和题
            let sum = 0;
            Object.keys(answer).forEach((key) => {
              sum += answer[key] * 1;
            });
            if (sum === config.total) {
              question.error = '';
            } else {
              isError = true;
              question.error = translatedText.value.PleaseLetTheSumEqualToTotal(config.total);
            }
          } else if (answer && questionType === 18 && answer.length < config.min_number) {
            // 文件上传题
            isError = true;
            question.error = translatedText.value.PleaseUploadAtLeastOneFiles(config.min_number);
          } else if (answer && questionType === 4) {
            question.error = '';
            // 填空题
            const { value } = answer;
            const newValue = value.replace(/\n|\r|\r\n/g, '');
            switch (config.text_type) {
              // 字母
              case 3:
                isError =
                  config.include_mark === 1
                    ? !/^[a-zA-Z·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、`~!@#$%^&*()_\-+=<>?:"{}|,./;'\\[\]]+$/.test(
                        newValue
                      ) || !newValue.length
                    : !/^[a-zA-Z]+$/.test(newValue) || !newValue.length;
                question.error = isError ? translatedText.value.PleaseEnterEnglishLetters : '';
                break;
              // 中文
              case 4:
                isError =
                  config.include_mark === 1
                    ? !/^(?:[\u3400-\u4DB5\u4E00-\u9FEA\uFA0E\uFA0F\uFA11\uFA13\uFA14\uFA1F\uFA21\uFA23\uFA24\uFA27-\uFA29]|[\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|[·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、`~!@#$%^&*()_\-+=<>?:"{}|,./;'\\[\]])+$/.test(
                        newValue
                      ) || !newValue.length
                    : !/^(?:[\u3400-\u4DB5\u4E00-\u9FEA\uFA0E\uFA0F\uFA11\uFA13\uFA14\uFA1F\uFA21\uFA23\uFA24\uFA27-\uFA29]|[\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0])+$/.test(
                        newValue
                      ) || !newValue.length;
                question.error = isError ? translatedText.value.PleaseEnterChineseWords : '';
                break;
              // 邮箱
              case 5:
                isError =
                  !/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(
                    value
                  );
                question.error = isError ? translatedText.value.PleaseEnterACorrectEmail : '';
                break;
              // 手机号
              case 6:
                isError = !/^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(value);
                question.error = isError ? translatedText.value.PleaseEnterACorrectPhone : '';
                break;
              // 身份证号
              case 7:
                isError =
                  !/^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|10|11|12)(?:0[1-9]|[1-2]\d|30|31)\d{3}[\dXx]$/.test(
                    value
                  );
                question.error = isError ? translatedText.value.PleaseEnterACorrectID : '';
                break;
              default:
                break;
            }
            if (!isError && value.length < config.min && ![1, 2].includes(config.text_type)) {
              isError = true;
              question.error = translatedText.value.PleaseEnterMoreThanOneCharacters(config.min);
            }
          } else if (answer && questionType === 8) {
            // 矩阵填空题
            question.error = '';
            Object.keys(answer).forEach((key) => {
              const value = answer[key];
              switch (config.text_type) {
                // 字母
                case 3:
                  if (
                    !/^[a-zA-Z·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、`~!@#$%^&*()_\-+=<>?:"{}|,./;'\\[\]]+$/.test(
                      value
                    )
                  ) {
                    question.error = translatedText.value.PleaseEnterEnglishLetters;
                  }
                  break;
                // 中文
                case 4:
                  if (
                    !/^(?:[\u3400-\u4DB5\u4E00-\u9FEA\uFA0E\uFA0F\uFA11\uFA13\uFA14\uFA1F\uFA21\uFA23\uFA24\uFA27-\uFA29]|[\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|[·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、`~!@#$%^&*()_\-+=<>?:"{}|,./;'\\[\]])+$/.test(
                      value
                    )
                  ) {
                    question.error = translatedText.value.PleaseEnterChineseWords;
                  }
                  break;
                // 邮箱
                case 5:
                  if (
                    !/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(
                      value
                    )
                  ) {
                    question.error = translatedText.value.PleaseEnterACorrectEmail;
                  }
                  break;
                // 手机号
                case 6:
                  if (!/^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(value)) {
                    question.error = translatedText.value.PleaseEnterACorrectPhone;
                  }
                  break;
                // 身份证号
                case 7:
                  if (
                    !/^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|10|11|12)(?:0[1-9]|[1-2]\d|30|31)\d{3}[\dXx]$/.test(
                      value
                    )
                  ) {
                    question.error = translatedText.value.PleaseEnterACorrectID;
                  }
                  break;
                default:
                  break;
              }
              if (
                !question.error &&
                value.length < config.min &&
                ![1, 2].includes(config.text_type)
              ) {
                question.error = translatedText.value.PleaseEnterMoreThanOneCharacters(config.min);
              }
            });
            if (question.error) isError = true;
          } else if (questionType === 27 && question.error) {
            // 多项填空题
            isError = true;
          } else {
            question.error = '';
          }
          return isError;
        });
        if (!errors.length) {
          // 质量控制
          const question = questions.value.find((question) => {
            const { config, answer, question_type: questionType } = question;
            if (questionType === 9 && config.is_repeat) {
              // 矩阵单选
              const arr = Object.keys(answer).map((key) => key.split('_')[1]);
              return hasNConsecutiveNumbers(arr, config.allow_repeat_num + 1);
            } else if (questionType === 10 && config.is_repeat) {
              // 矩阵多选
              let arr = [];
              const obj = {};
              for (const key in answer) {
                const [index, value] = key.split('_');
                if (obj[index] === undefined) {
                  obj[index] = arr.length;
                  arr.push([value]);
                } else {
                  arr[obj[index]].push(value);
                }
              }
              arr = arr.map((subArr) => subArr.sort().join());
              return hasNConsecutiveNumbers(arr, config.allow_repeat_num + 1);
            }
            return false;
          });
          if (question) {
            await new Promise((resolve) => {
              Modal[question.config.repeat_type ? 'confirm' : 'info']({
                class: 'custom-modal custom-modal-title-notice',
                title: translatedText.value.PleaseAnswerCarefully,
                content: question.config.alert_text,
                cancelText: translatedText.value.ContinueAnswer,
                okText: translatedText.value.ReviseAnswer,
                onCancel: () => {
                  resolve();
                }
              });
            });
          }
          // 判断是作答还是预览
          if (!props.isAnswer) {
            loading.value = true;
            try {
              // 模拟接口
              const data = answerMock(questionsData.value, page.value);
              // console.log('模拟作答数据', data);
              // 更新答案
              updateAnswer(data.answer_info_autofill);
              // 更新分页数组
              questionsData.value.answer.pages = data.pages;
              // 选项隐藏
              hideOptions(data.hide_options);
              // 更新action
              questionsData.value.action = data.action;
              if ([20004, 20011, 20016].includes(data.action.code)) {
                return (page.value = pages.value.length + 1);
              }
              callback(data.jump_to);
            } catch (error) {
              // console.log(error);
            }
            return (loading.value = false);
          }
          // 表单验证通过，开始答题
          const cycle = [];
          const questionsAnswer = [];
          questions.value.forEach((question) => {
            questionsAnswer.push({
              question_index: question.question_index,
              answer: question.answer || {}
            });
            // 循环
            if (question.question_type === 1 || question.question_type === 2) {
              const optionKeys = [];
              question.list.forEach((list) => {
                list.options.forEach((option) => {
                  optionKeys.push(option.option_key);
                });
              });
              cycle.push({
                question_index: question.question_index,
                options: {
                  a: optionKeys.join()
                }
              });
            }
          });
          loading.value = true;
          try {
            if (callbackBeforePage) await callbackBeforePage();
            const { data } = await AnswerApi.answer({
              id: proxy.$route.query.sn,
              data: {
                cycle,
                answer: JSON.stringify(questionsAnswer),
                is_test: proxy.$route.query.is_test
              }
            });
            // 更新答案
            updateAnswer(data.answer_info_autofill);
            // 更新分页数组
            questionsData.value.answer.pages = data.pages;
            // 京东跳转
            if (data.action.code === 302) {
              location.href = data.action.msg;
            }
            // 更新问卷状态
            if (data.action.code === 20014) {
              const timer = setTimeout(() => {
                const url = data.action.msg;
                toUrl(url);
                clearTimeout(timer);
              });
            }
            // 判断抽奖
            if (data.action.lottery) {
              const endAnswerTime = new Date().getTime();
              const answerTime = endAnswerTime - startAnswerTime;
              proxy.$router.push({
                path: '/luck',
                query: {
                  user_id: proxy.$route.query.sn,
                  id: questionsData.value.answer.sn,
                  time_num: parseInt(answerTime / 1000),
                  is_test: proxy.$route.query.is_test || 0
                }
              });
            }
            // 选项隐藏
            hideOptions(data.hide_options);
            // 更新action
            questionsData.value.action = data.action;
            callback(data.jump_to);
            // 写入关联选项缓存
            if (props.isAnswer && questionsData.value.survey.is_breakpoint) {
              if (data.action.code === 20010) {
                const questionsCache = JSON.parse(localStorage.getItem('questionsCache')) || {};
                questionsCache[proxy.$route.query.sn] = questionsData.value.questions;
                localStorage.setItem('questionsCache', JSON.stringify(questionsCache));
              } else {
                const questionsCache = JSON.parse(localStorage.getItem('questionsCache'));
                if (questionsCache?.[proxy.$route.query.sn]) {
                  delete questionsCache[proxy.$route.query.sn];
                  localStorage.setItem('questionsCache', JSON.stringify(questionsCache));
                }
              }
            }
          } catch (error) {
            // console.log(error);
          }
          loading.value = false;
        } else {
          // console.log(errors);
          const { error, title, question_index: questionIndex } = errors[0];
          const lines = (error || '')
            .split('\n')
            .filter((i) => !!i)
            .map((i) => `${title}：${i}`);
          msg.error(lines.join('\n'));

          // 锚点
          const anchor = document.querySelector(`#questionIndex${questionIndex}`);
          // console.log(anchor, scrollbar.value);
          scrollbar.value.scrollTo(0, anchor.offsetTop - (props.isMobile ? 20 : 40));
        }
      } else {
        callback();
      }
    }

    // function jumpImmediately() {
    //   const code = questionsData.value.action?.code;
    //   if (page.value !== pages.value.length + 1 && ![20004, 20011, 20016].includes(code)) {
    //     return;
    //   }
    //   const survey = questionsData.value.survey;
    //   let countTime = 0;
    //   let url = '';
    //
    //   if (code === 20004 && survey.screening_end_url_select && survey.screening_end_url) {
    //     countTime = survey.screening_standing_time;
    //     url = survey.screening_end_url;
    //   }
    //   if (code === 20011 && survey.success_end_url_select && survey.success_end_url) {
    //     countTime = survey.success_standing_time;
    //     url = survey.success_end_url;
    //   }
    //   if (code === 20016 && survey.quota_end_url_select && survey.quota_end_url) {
    //     countTime = survey.quota_standing_time;
    //     url = survey.quota_end_url;
    //   }
    //
    //   // 跳转链接
    //   if (countTime <= 0 && url) {
    //     questionsData.value.action.code = -1 * code; // 防止 AnswerMob AnswerPc 组件里显示最后一页
    //
    //     url = url.replaceAll('#sn#', questionsData.value.answer.sn);
    //     url = url.replaceAll('#user#', questionsData.value.answer.respondent);
    //     url = url.replaceAll('#survey_sn#', questionsData.value.answer.survey_sn);
    //     if (proxy.$route.query.source === 'YILI_APP_WANGYI') {
    //       Object.keys(proxy.$route.query).forEach((key) => {
    //         if (!['sn', 'source', 'is_template', 'channelUCode'].includes(key)) {
    //           url += `${url.indexOf('?') === -1 ? '?' : '&'}${key}=${proxy.$route.query[key]}`;
    //         }
    //       });
    //     }
    //     // 判断是否小程序路径
    //     if (url[0] === '/') {
    //       // 判断是否在小程序环境
    //       wx.miniProgram.getEnv(() => {
    //         wx.miniProgram.redirectTo({ url });
    //       });
    //     } else {
    //       if (url.indexOf('http://') === -1 && url.indexOf('https://') === -1) {
    //         url = `http://${url}`;
    //       }
    //       open(url, '_self');
    //     }
    //   }
    // }

    // 选项隐藏
    function hideOptions(hide) {
      const questionIndex = hide?.question_index;
      if (questionIndex) {
        const qustion = questionsData.value.questions.find(
          (qustion) => qustion.question_index === questionIndex
        );
        qustion.hideOptions = hide.option_key || [];
      }
    }

    // 关联引用
    function onRelation(
      { options, value, list },
      { question_type: questionType, question_index: questionIndex, related, answer }
    ) {
      // 关联
      related.forEach((relationItem) => {
        let relationOptions = [];
        if (questionType === 9 || questionType === 10) {
          // 矩阵选择
          list.forEach((item) => {
            if (item.type === relationItem.cite_type) {
              relationOptions = [...relationOptions, ...item.options];
            }
            if (relationItem.relation_type === 1) {
              relationOptions = relationOptions.filter((option) =>
                questionType === 9 ? option.value : option.value?.length
              );
            } else if (relationItem.relation_type === 2) {
              relationOptions = relationOptions.filter((option) =>
                questionType === 9 ? !option.value : !option.value?.length
              );
            }
          });
        } else if (questionType === 11) {
          // 矩阵打分
          list.forEach((item) => {
            if (item.type === relationItem.cite_type) {
              relationOptions = [...relationOptions, ...item.options];
            }
          });
        } else if (questionType === 25 || questionType === 26) {
          // 热区题
          relationOptions = options.filter((option) => {
            if (relationItem.relation_type === 1) {
              return option.status === 1;
            } else if (relationItem.relation_type === 2) {
              return option.status === 2;
            } else if (relationItem.relation_type === 3) {
              return !option.status;
            }
            return true;
          });
        } else if (questionType === 105) {
          // MXD
          options.forEach((currentOptions) => {
            currentOptions.forEach((option) => {
              const index = relationOptions.findIndex(
                (relationOption) => relationOption.option_key === option.option_key
              );
              if (index === -1) {
                // 全部项
                if (relationItem.relation_type === 0) {
                  return relationOptions.push(option);
                }
                // 高相关
                if (relationItem.relation_type === 3) {
                  return option.value === 'b' && relationOptions.push(option);
                }
                // 不相关
                if (relationItem.relation_type === 4) {
                  return option.value === 'w' && relationOptions.push(option);
                }
              }
            });
          });
        } else if (relationItem.relation_type === 0) {
          // 全部选项
          relationOptions = options;
        } else {
          // 过滤选中/未选中选项
          relationOptions = options.filter((option) => {
            if (questionType === 1) {
              // 单选
              if (relationItem.relation_type === 1) return value === option.option_key;
              return value !== option.option_key;
            } else if (questionType === 2) {
              // 多选
              if (relationItem.relation_type === 1) return value.includes(option.option_key);
              return !value.includes(option.option_key);
            }
            return true;
          });
        }
        // 找到关联题
        const question = questionsData.value.questions.find(
          (question) => question.question_index === relationItem.relation_question_index
        );
        // 深拷贝关联选项
        const copyRelationOptions = JSON.parse(JSON.stringify(relationOptions));
        // 更新关联选项key
        copyRelationOptions.forEach((option) => {
          if (option.option_key[0] !== 'Q') {
            let letter = 'A';
            // 矩阵题行、列
            if (questionType >= 9 && questionType <= 11) {
              letter = relationItem.cite_type === 1 ? 'R' : 'C';
            }
            option.option_key = `Q${questionIndex}${letter}${option.option_key}`;
          }
          // 其他项特殊处理
          if (option.is_other && option.value) {
            option.is_other = 0;
            option.option = option.value;
          }
          delete option.value;
          delete option.status;
        });
        // 更新关联题列表
        const relatedList = question.list.find(
          (relatedListItem) => relatedListItem.relation_question_index === questionIndex
        );
        relatedList.options = answer ? copyRelationOptions : [];
      });
    }

    // 更新答案
    function updateAnswer(auto) {
      if (auto) {
        auto.forEach((autoItem) => {
          const question = questionsData.value.questions.find(
            (question) => question.question_index === autoItem.question_index
          );
          question.answer = JSON.parse(autoItem.answer);

          // 隐藏的题目，自动填写时，并被后续题目关联选项，会出现关联选项未正确展示的情况，此暂时解决方法
          const evt1 = {};

          if ([1].includes(question.question_type)) {
            evt1.value =
              Object.keys(question.answer)
                .map((key) => (question.answer[key] ? key : undefined))
                .filter((i) => !!i)?.[0] || undefined;
            evt1.options = question.list.flatMap((i) => i.options);
            onRelation(evt1, question);
          }
        });
      }
    }

    // 跳转链接
    function toUrl(url) {
      // 判断是否小程序路径
      if (url[0] === '/') {
        // 判断是否在小程序环境
        wx.miniProgram.getEnv(() => {
          wx.miniProgram.redirectTo({ url });
        });
      } else {
        let _url;
        if (url.indexOf('http://') === -1 && url.indexOf('https://') === -1) {
          _url = `http://${url}`;
        }
        open(_url);
      }
    }

    watch(
      () => route.query,
      () => {
        // console.log('route.query.sn', route.query);
        location.reload();
      },
      {
        deep: true
      }
    );

    return {
      page,
      pages,
      loading,
      prevLoading,
      showPage,
      styleInfo,
      questions,
      scrollbar,
      questionsData,
      localPageTimer,
      answer,
      previous,
      next,
      onRelation
    };
  }
});
