let answerQues = [];
/**
 * 关联选项处理
 * @returns
 */
function optionHandle(questionIndex) {
  const optAndrelateList = [];
  const rowOptAndrelateList = [];
  const colOptAndrelateList = [];
  const classOptAndrelateList = [];
  const curQuesInfo = answerQues.find((ques) => ques.question_index === questionIndex);
  curQuesInfo.list.forEach((l) => {
    if (l.type === 0) {
      optAndrelateList.push(...l.options);
    } else if (l.type === 1) {
      rowOptAndrelateList.push(...l.options);
    } else if (l.type === 2) {
      colOptAndrelateList.push(...l.options);
    } else if (l.type === 3) {
      classOptAndrelateList.push(...l.options);
    }
  });
  // 选项列表
  const optList = optAndrelateList.map((opt, oIndex) => {
    opt.option_index = oIndex + 1;
    return opt;
  });
  const rowOptList = rowOptAndrelateList.map((opt, oIndex) => {
    opt.option_index = oIndex + 1;
    return opt;
  });
  const coloptList = colOptAndrelateList.map((opt, oIndex) => {
    opt.option_index = oIndex + 1;
    return opt;
  });
  const classoptList = classOptAndrelateList.map((opt, oIndex) => {
    opt.option_index = oIndex + 1;
    return opt;
  });
  return {
    optAndrelateList: optList,
    rowOptAndrelateList: rowOptList,
    colOptAndrelateList: coloptList,
    classOptAndrelateList: classoptList
  };
}
/**
 * 运算符转换处理
 * @param {*} operator
 * @returns
 */
function operatorHandle(operator) {
  let operatorStr = '';
  if (operator === '=' || operator === '是') {
    operatorStr = '===';
  } else if (operator === '≠' || operator === '不是') {
    operatorStr = '!==';
  } else if (operator === '≥') {
    operatorStr = '>=';
  } else if (operator === '≤') {
    operatorStr = '<=';
  } else if (operator === '包含') {
    operatorStr = 'includes';
  } else if (operator === '不包含') {
    operatorStr = '!includes';
  } else {
    operatorStr = operator;
  }
  return operatorStr;
}
/**
 * 处理每种题型的不同逻辑
 * @param {*} answer 每个题里面的答题信息answer字段
 * @param {*} logChild 逻辑信息
 * @returns
 */
function quesHandle(answer, logChild) {
  // 单选
  const choiceHandle = (config) => {
    // 如果配置的逻辑中option_index为0,则代表没有配置选中项，此时不做校验
    if (logChild.option_index === 0) {
      return true;
    }
    let status = false;
    Object.keys(answer).forEach((key) => {
      // 选项分组
      if (logChild.is_option_group) {
        const optionGroup = config.option_groups.option_group.find((optionGroup) =>
          optionGroup.groups.find((group) => group.option_key === key)
        );
        // eslint-disable-next-line no-eval
        status = eval(
          `${optionGroup?.group_index}${operatorHandle(logChild.operator)}${logChild.option_index}`
        );
      } else {
        const { optAndrelateList } = optionHandle(logChild.question_index);
        // 旧的错误代码，处理 answer 有问题. pc 端夹带私货
        // const postion = optAndrelateList.find((opt) => opt.option_key === key).option_index;
        // 拿到答题时选中的选项位置
        const postion = optAndrelateList.find((opt) => {
          /**
           * todo: 旧的答案配置
           * key : value。 value: 答案的索引 + 1.
           * 答案格式 {
           *   answer: {
           *     value: 1,
           *   }
           * }
           */
          // return opt.option_key === answer[key];
          /**
           * todo: 新的答案配置
           * key : 答案的索引 + 1.  value: 1
           * 答案格式 {
           *   answer: {
           *     '1': 1
           *   }
           * }
           */
          //   遍历答案的key值
          for (const _key in answer[key]) {
            // _key 选中的答案
            if (Number(_key) === Number(opt.option_key)) {
              return true;
            }
          }
        }).option_index;
        // 拿到配置的逻辑里选项的位置
        const logPostion = optAndrelateList.find(
          (opt) => opt.option_key === logChild.option_index
        ).option_index;
        // eslint-disable-next-line no-eval
        status = eval(`'${postion}'${operatorHandle(logChild.operator)}'${logPostion}'`);
      }
    });
    return status;
  };
  // 多选
  const choiceCheckBoxHandle = (config) => {
    // 如果配置的逻辑中option_index为0,则代表没有配置选中项，此时不做校验
    if (logChild.option_index === 0 || logChild.is_select === '') {
      return true;
    }
    let status = false;
    // 选项分组
    if (logChild.is_option_group) {
      const optionGroup = config.option_groups.option_group.find(
        (optionGroup) => optionGroup.group_index === logChild.option_index * 1
      );
      const group = optionGroup.groups.find((group) =>
        Object.keys(answer).includes(group.option_key)
      );
      status = group ? logChild.is_select : !logChild.is_select;
    } else {
      if (logChild.is_select) {
        // 如果配置的是选中, 则判断answer答案里面是否包含配置的选项
        status = Object.keys(answer).includes(logChild.option_index);
      } else {
        // 如果配置的是未选中, 则判断answer答案里面是否不包含配置的选项
        status = !Object.keys(answer).includes(logChild.option_index);
      }
    }
    return status;
  };
  // 填空题
  const inputHandle = () => {
    // 如果配置的逻辑中value为空,则代表没有配置输入值，此时不做校验
    if (!logChild.value || !logChild.operator) {
      return true;
    }
    let status = false;
    if (['包含', '不包含'].includes(logChild.operator)) {
      // eval执行转换成字符串的语句(value.includes('222'))
      // eslint-disable-next-line no-eval
      status = eval(`'${answer.value}'.${operatorHandle(logChild.operator)}('${logChild.value}')`);
    } else {
      // eval执行转换成字符串的语句(value === '222')， 返回值是个 {Boolean}
      // eslint-disable-next-line no-eval
      status = eval(`'${answer.value}'${operatorHandle(logChild.operator)}'${logChild.value}'`);
    }
    return status;
  };
  // 知情同意书题
  const agreementHandle = () => {
    // 如果配置的逻辑中value为空,则代表没有配置输入值，此时不做校验
    if (!logChild.value || !logChild.operator) {
      return true;
    }
    let status = false;
    if (['=', '等于', '是'].includes(logChild.operator)) {
      // eslint-disable-next-line no-eval
      status = eval(`'${answer.value}'${operatorHandle(logChild.operator)}('${logChild.value}')`);
    } else {
      // eslint-disable-next-line no-eval
      status = eval(`${answer.value}${operatorHandle(logChild.operator)}${logChild.value}`);
    }
    // console.log('===', status);
    return status;
  };
  // 打分题
  const rateHandle = () => {
    // 如果配置的逻辑中参数为空,则代表没有配置逻辑匹配值，此时不做校验
    if (logChild.option_index === 0 || !logChild.operator || !logChild.value) {
      return true;
    }
    // eslint-disable-next-line no-eval
    return eval(
      `${answer[logChild.option_index]}${operatorHandle(logChild.operator)}${logChild.value}`
    );
  };
  // 矩阵单选题
  const matrixRadioHandle = (config) => {
    // 如果配置的逻辑中参数为空,则代表没有配置逻辑匹配值，此时不做校验
    if (logChild.cell_index === 0 || logChild.row_index === 0 || !logChild.operator) {
      return true;
    }
    let status = false;
    // 选项分组
    if (logChild.is_option_group) {
      const selectAnswer = Object.keys(answer).find(
        (key) => key.split('_')[0] === logChild.row_index
      );
      const optionGroup = config.cell_option_groups.option_group.find((optionGroup) =>
        optionGroup.groups.find((group) => group.option_key === selectAnswer.split('_')[1])
      );
      // eslint-disable-next-line no-eval
      status = eval(
        `${optionGroup?.group_index}${operatorHandle(logChild.operator)}${logChild.cell_index}`
      );
    } else {
      const { colOptAndrelateList } = optionHandle(logChild.question_index);
      // 先找到配置的逻辑中，列选项的位置
      const cellLogPostion = colOptAndrelateList.find(
        (opt) => opt.option_key === logChild.cell_index
      ).option_index;
      // 然后在找到答案里面行和配置的逻辑行一样的key
      const selectAnswer = Object.keys(answer).find(
        (key) => key.split('_')[0] === logChild.row_index
      );
      // 再找到逻辑里面配置的行在答案里面选中的位置
      const cellPostion = colOptAndrelateList.find(
        (opt) => opt.option_key === selectAnswer.split('_')[1]
      ).option_index;
      // 两者进行对比
      // eslint-disable-next-line no-eval
      status = eval(`${cellPostion}${operatorHandle(logChild.operator)}${cellLogPostion}`);
    }
    return status;
  };
  // 矩阵多选题
  const matrixCheckboxHandle = (config) => {
    // 如果配置的逻辑中参数为空,则代表没有配置逻辑匹配值，此时不做校验
    if (logChild.cell_index === 0 || logChild.row_index === 0 || logChild.is_select === '') {
      return true;
    }
    let status = false;
    // 选项分组
    if (logChild.is_option_group) {
      const selectAnswer = Object.keys(answer)
        .filter((key) => key.split('_')[0] === logChild.row_index)
        .map((key) => key.split('_')[1]);
      const optionGroup = config.cell_option_groups.option_group.find((optionGroup) =>
        optionGroup.groups.find((group) => selectAnswer.includes(group.option_key))
      );
      status = logChild.is_select
        ? optionGroup.group_index === logChild.cell_index * 1
        : optionGroup.group_index !== logChild.cell_index * 1;
    } else {
      const optionKey = `${logChild.row_index}_${logChild.cell_index}`;
      if (logChild.is_select) {
        // 如果配置的是选中, 则判断answer答案里面是否包含配置的选项
        status = Object.keys(answer).includes(optionKey);
      } else {
        // 如果配置的是未选中, 则判断answer答案里面是否不包含配置的选项
        status = !Object.keys(answer).includes(optionKey);
      }
    }
    return status;
  };
  // 矩阵打分题
  const matrixRateHandle = () => {
    // 如果配置的逻辑中参数为空,则代表没有配置逻辑匹配值，此时不做校验
    if (
      logChild.cell_index === 0 ||
      logChild.row_index === 0 ||
      !logChild.operator ||
      !logChild.value
    ) {
      return true;
    }
    const optionKey = `${logChild.row_index}_${logChild.cell_index}`;
    // eslint-disable-next-line no-eval
    return eval(`${answer[optionKey]}${operatorHandle(logChild.operator)}${logChild.value}`);
  };
  // 矩阵填空题
  const matrixInputHandle = () => {
    // 如果配置的逻辑中参数为空,则代表没有配置逻辑匹配值，此时不做校验
    if (
      logChild.cell_index === 0 ||
      logChild.row_index === 0 ||
      !logChild.operator ||
      !logChild.value
    ) {
      return true;
    }
    let status = false;
    const optionKey = `${logChild.row_index}_${logChild.cell_index}`;
    if (['包含', '不包含'].includes(logChild.operator)) {
      // eval执行转换成字符串的语句(value.includes('222'))
      // eslint-disable-next-line no-eval
      status = eval(
        `'${answer[optionKey]}'.${operatorHandle(logChild.operator)}('${logChild.value}')`
      );
    } else {
      // eslint-disable-next-line no-eval
      status = eval(`${answer[optionKey]}${operatorHandle(logChild.operator)}${logChild.value}`);
    }
    return status;
  };
  // 图片单选
  const imgRadioHandle = () => {
    // 如果配置的逻辑中参数为空,则代表没有配置逻辑匹配值，此时不做校验
    if (logChild.option_index === 0 || !logChild.operator) {
      return true;
    }
    let status = false;
    Object.keys(answer).forEach((key) => {
      // eslint-disable-next-line no-eval
      status = eval(`${key}${operatorHandle(logChild.operator)}${logChild.option_index}`);
    });
    return status;
  };
  // 图片多选
  const imgCheckBoxHandle = () => {
    // 如果配置的逻辑中参数为空,则代表没有配置逻辑匹配值，此时不做校验
    if (logChild.option_index === 0 || logChild.is_select === '') {
      return true;
    }
    let status = false;
    if (logChild.is_select) {
      // 如果配置的是选中, 则判断answer答案里面是否包含配置的选项
      status = Object.keys(answer).includes(logChild.option_index);
    } else {
      // 如果配置的是未选中, 则判断answer答案里面是否不包含配置的选项
      status = !Object.keys(answer).includes(logChild.option_index);
    }
    return status;
  };
  // 分类题
  const classifyHandle = () => {
    // 如果配置的逻辑中参数为空,则代表没有配置逻辑匹配值，此时不做校验
    if (logChild.row_index === 0 || logChild.cell_index === 0 || !logChild.operator) {
      return true;
    }
    // eslint-disable-next-line no-eval
    return eval(
      `${answer[logChild.row_index]}${operatorHandle(logChild.operator)}${logChild.cell_index}`
    );
  };
  // 排序题
  const sortHandle = () => {
    // 如果配置的逻辑中参数为空,则代表没有配置逻辑匹配值，此时不做校验
    if (logChild.option_index === 0 || !logChild.operator || logChild.location === '') {
      return true;
    }
    // eslint-disable-next-line no-eval
    const status = eval(
      `${answer[logChild.option_index]}${operatorHandle(logChild.operator)}${logChild.location}`
    );
    return status;
  };
  // 恒定总和题
  const constantSumHandle = () => {
    // 如果配置的逻辑中参数为空,则代表没有配置逻辑匹配值，此时不做校验
    if (logChild.option_index === 0 || !logChild.operator || !logChild.value) {
      return true;
    }
    // eslint-disable-next-line no-eval
    return eval(
      `${answer[logChild.option_index]}${operatorHandle(logChild.operator)}${logChild.value}`
    );
  };
  // 日期时间题
  const dateTimeHandle = () => {
    // 如果配置的逻辑中参数为空,则代表没有配置逻辑匹配值，此时不做校验
    if (!logChild.date || !logChild.operator || !logChild.time) {
      return true;
    }
    let status = false;
    if (answer.date && answer.time) {
      // 如果同时配置了日期和时间
      status = answer.date === logChild.date && answer.time === logChild.time;
    } else if (answer.date) {
      // 如果只配置了日期
      status = answer.date === logChild.date;
    } else if (answer.time) {
      // 如果只配置了时间
      status = answer.time === logChild.time;
    }
    return status;
  };
  // psm
  const psmHandle = (config) => {
    // 如果配置的逻辑中参数为空,则代表没有配置逻辑匹配值，此时不做校验
    if (!logChild.value) {
      return true;
    }
    const answerIndex = answer[5];
    const status = String(config.price_gradient[answerIndex - 1]) === logChild.value;
    return status;
  };
  // 级联题
  const cascaderHandle = () => {
    // 如果配置的逻辑中参数为空,则代表没有配置逻辑匹配值，此时不做校验
    if (logChild.option_index === 0 && !logChild.option_index) {
      return true;
    }
    let status = false;
    if (logChild.is_select) {
      // 如果配置的是选中, 则判断answer答案里面是否包含配置的选项
      status = Object.keys(answer).includes(logChild.option_index);
    } else {
      // 如果配置的是未选中, 则判断answer答案里面是否不包含配置的选项
      status = !Object.keys(answer).includes(logChild.option_index);
    }
    return status;
  };
  return {
    choiceHandle,
    choiceCheckBoxHandle,
    inputHandle,
    agreementHandle,
    rateHandle,
    matrixRadioHandle,
    matrixCheckboxHandle,
    matrixRateHandle,
    matrixInputHandle,
    imgRadioHandle,
    imgCheckBoxHandle,
    classifyHandle,
    sortHandle,
    constantSumHandle,
    dateTimeHandle,
    psmHandle,
    cascaderHandle
  };
}
function getConditionStatus(logChild) {
  const resultStatus = [];
  // 拿到当前题的答案
  const answer = answerQues.find((ques) => ques.question_index === logChild.question_index)?.answer;
  // 拿到当前题的config信息
  const config = answerQues.find((ques) => ques.question_index === logChild.question_index)?.config;
  // 如果逻辑是不为空则为作答
  if (logChild.is_answer) {
    // 每个题型有不同的判断逻辑
    const quesHandles = quesHandle(answer, logChild);
    let quesStatus = false;
    if (answer) {
      try {
        switch (logChild.question_type) {
          case 1:
            quesStatus = quesHandles.choiceHandle(config);
            break;
          case 2:
            quesStatus = quesHandles.choiceCheckBoxHandle(config);
            break;
          case 3:
            quesStatus = quesHandles.cascaderHandle();
            break;
          case 4:
            quesStatus = quesHandles.inputHandle();
            break;
          case 5:
            quesStatus = quesHandles.rateHandle();
            break;
          case 7:
            quesStatus = quesHandles.dateTimeHandle();
            break;
          case 8:
            quesStatus = quesHandles.matrixInputHandle();
            break;
          case 9:
            quesStatus = quesHandles.matrixRadioHandle(config);
            break;
          case 10:
            quesStatus = quesHandles.matrixCheckboxHandle(config);
            break;
          case 11:
            quesStatus = quesHandles.matrixRateHandle();
            break;
          case 13:
            quesStatus = quesHandles.imgRadioHandle();
            break;
          case 14:
            quesStatus = quesHandles.imgCheckBoxHandle();
            break;
          case 15:
            quesStatus = quesHandles.classifyHandle();
            break;
          case 16:
            quesStatus = quesHandles.sortHandle();
            break;
          case 17:
            quesStatus = quesHandles.constantSumHandle();
            break;
          case 23:
            quesStatus = quesHandles.agreementHandle();
            break;
          case 101:
            quesStatus = quesHandles.psmHandle(config);
            break;
          default:
            break;
        }
      } catch (error) {
        // console.log(error);
        quesStatus = false;
      }
    }
    resultStatus.push(...[!!answer, quesStatus]);
  } else {
    // 如果为空则为不作答，判断当前题是否包含answer字段，如果有则已经作答，返回false。
    resultStatus.push(!answer);
  }
  // eslint-disable-next-line no-eval
  return eval(resultStatus.join('&&'));
}
function getlogicStatus(questionData) {
  answerQues = JSON.parse(JSON.stringify(questionData.questions));
  const logics = JSON.parse(JSON.stringify(questionData.logics));
  logics.forEach((logs) => {
    // 跳转逻辑
    const logic = logics.find(
      (logic) =>
        logic.question_index === logs.question_index && logic.skip_type === 0 && logic.logicStatus
    );
    if (logic) return;
    // 如果选择的是always，则直接返回true；
    if (logs.logic.length === 1 && logs.logic[0].logic === 'always') {
      logs.logicStatus = true;
    } else {
      // 处理每条逻辑(if或者and或者or)的结果
      // 将上一步获取到的每条逻辑状态整合起来，统一判断
      let statusStr = '';
      logs.logic.forEach((logChild /* condIndex */) => {
        const conditionStatus = getConditionStatus(logChild);
        // if (condIndex !== logs.logic.length - 1) {
        //   statusStr = statusStr + conditionStatus + (logChild.logic === "or" ? "||" : "&&");
        // } else {
        //   statusStr = statusStr + conditionStatus;
        // }
        statusStr =
          statusStr +
          (logChild.logic === 'and' ? '&&' : logChild.logic === 'or' ? '||' : '') +
          conditionStatus;
      });
      // eslint-disable-next-line no-eval
      logs.logicStatus = eval(statusStr);
    }
  });
  // console.log('logics', logics);
  return logics;
}
export default getlogicStatus;
