import * as question from "@/enums/question";
import { deepClone, parseJSON } from "./common";

export const formatQuKey = (key: string) =>
  /^QU/.test(key) ? key.replace(/^QU/, "") : key;
export const formatHistoryChild = (
  findQuestion: any,
  child: any,
  key: string
) => {
  const childAnswer = child.answer;
  console.log(childAnswer);
  if (!childAnswer) return;
  const keys = Object.keys(childAnswer);
  const values = Object.values(childAnswer);
  const findChild = findQuestion.children.find(
    (v: any) => v.sn == formatQuKey(key)
  );
  if (!keys.length) {
    if (child.type == question.QUESTION_TYPE_CHECKBOX) return [];
    return;
  }
  if (child.multipleAnswers) {
    console.log("没处理的地方", childAnswer);
  } else {
    if (findChild.type == question.QUESTION_TYPE_CHECKBOX) {
      findChild.value = Array.isArray(keys)
        ? keys.map((key: string, i: number) => {
            const findIdx = findChild.choices.findIndex(c => c.attr == key);
            if (findChild.choices[findIdx]?.isInput) {
              findChild.choices[findIdx].extra = values[i];
            }
            return findIdx;
          })
        : [];
    } else if (findChild.type == question.QUESTION_TYPE_RADIO) {
      findChild.value = findChild.choices.findIndex(c => c.attr == keys[0]);
      if (findChild.choices[findChild.value]?.isInput) {
        findChild.choices[findChild.value].extra = values[0];
      }
    } else if (findChild.type == question.QUESTION_TYPE_MATRIX) {
      findChild.matrix = findChild.matrix.map((row: boolean[], k1: number) => {
        row = row?.map((col: boolean, k2: number) => {
          return !!values.find(
            mV => mV[findChild.rows[k1].attr] && mV[findChild.columns[k2].attr]
          );
        });
        return row;
      });
    } else {
      findChild.value = Array.isArray(values) ? values.flat()[0] : values;
    }
  }
  return findChild.value;
};
export const formatHistoryItem = (item, idx?, rawList?) => {
  const { returnAnswer } = item;
  if (!returnAnswer) return "";
  let value;

  // const findQuestionIndx = rawList.value.findIndex(q => q.sn == item.sn)
  console.log("formatHistoryItem", item.title, item);
  switch (returnAnswer.type) {
    case question.QUESTION_TYPE_CHECKBOX:
      value = returnAnswer.checkboxAnswers.map(v => {
        const val = item.choices.findIndex(c => c.attr == v.key);
        if (item.choices[val]?.isInput) {
          item.choices[val].extra = v.value;
        }
        return val;
      });
      break;
    case question.QUESTION_TYPE_RADIO:
      value = item.choices.findIndex(c => c.attr == returnAnswer.answer.key);
      if (item.choices[value]?.isInput) {
        item.choices[value].extra = returnAnswer.answer.value;
      }
      break;
    case question.QUESTION_TYPE_SELECT:
      value = returnAnswer.checkboxAnswers;
      break;
    case question.QUESTION_TYPE_INPUT:
      if (returnAnswer.multipleAnswers) {
        const temp = returnAnswer.inputAnswers.value.map((v, k) => {
          return {
            ...deepClone(item),
            showDelete: true,
            showAdd: k >= returnAnswer.inputAnswers.value.length - 1,
            value: v
          };
        });
        rawList.value.splice(idx, 1, ...temp);
      }
      value = returnAnswer.inputAnswers.value[0];
      break;
    case question.QUESTION_TYPE_UPLOAD:
      value = returnAnswer.linkAnswers?.value || [];
      break;
    case question.QUESTION_TYPE_DATE:
      value = returnAnswer.answer.value;
      break;
    case question.QUESTION_TYPE_MATRIX:
      {
        const values = returnAnswer.matrixAnswers.map(
          v => `${v.xKey}${v.yKey}`
        );
        item.matrix = item.matrix.map((row: boolean[], k1: number) => {
          row = row?.map((col: boolean, k2: number) => {
            return values.includes(
              `${item.rows[k1].attr}${item.columns[k2].attr}`
            );
          });
          return row;
        });
        value = returnAnswer.matrixAnswers.map(v => `${v.xText}${v.yText}`);
      }
      break;
    case question.QUESTION_TYPE_GROUP:
      {
        const temp = returnAnswer.groupAnswers.map((v, k) => {
          const tempItem = deepClone(item);
          tempItem.children.forEach((child, childIdx) => {
            child.value = formatHistoryItem({
              ...child,
              returnAnswer: v[childIdx]
            });
          });
          return {
            ...tempItem,
            showDelete: true,
            showAdd: k >= returnAnswer.groupAnswers.length - 1,
            value: tempItem.children.map(v => v.value)
          };
        });
        rawList.value.splice(idx, 1, ...temp);
      }
      break;
  }
  return value;
};
export const formatHistory = (historyAnswer: any, rawList: any) => {
  rawList.value.forEach((v, k) => {
    v.value = formatHistoryItem(v, k, rawList);
  });
  // if (historyAnswer) {
  //   Object.keys(historyAnswer).forEach(questionKey => {
  //     const qKey = formatQuKey(questionKey)
  //     const findQuestionIndx = rawList.value.findIndex(q => q.sn == qKey)
  //     const findQuestion = rawList.value[findQuestionIndx]
  //     const answer = historyAnswer[questionKey].answer
  //     if (answer) {
  //       if (findQuestion.type == question.QUESTION_TYPE_GROUP) {
  //         if (findQuestion.isRepeat) {
  //           // console.log('组合多答', findQuestion, answer)
  //           const temp = Array.isArray(answer) ? answer.map((v: any, k: number) => {
  //             const tempVal = Object.keys(v)?.map((key, k) => {
  //               // console.log('组合多答', key, v[key], '处理完的', formatHistoryChild(findQuestion, v[key], key))
  //               return formatHistoryChild(findQuestion, v[key], key)
  //             })
  //             return {
  //               ...deepClone(findQuestion),
  //               showDelete: true,
  //               showAdd: k >= answer.length - 1,
  //               value: tempVal
  //             }
  //           }) : []
  //           temp.length && rawList.value.splice(findQuestionIndx, 1, ...temp)
  //           console.log('组合多答处理完的value', qKey, temp)
  //         } else {
  //           if (answer[0]) {
  //             rawList.value[findQuestionIndx].value = Object.keys(answer[0])?.map((key, k) => {
  //               return formatHistoryChild(findQuestion, answer[0][key], key)
  //             })
  //           }
  //         }
  //       } else {
  //         const keys = Object.keys(answer)
  //         const values: any = Object.values(answer)[0]
  //         if (findQuestion.isRepeat) {
  //           findQuestion.value = values[0]

  //           findQuestion.showDelete = values.length > 1
  //           findQuestion.showAdd = values.length == 1
  //           values?.forEach((v, k) => {
  //             if (k) {
  //               rawList.value.splice(findQuestionIndx, 0, {
  //                 ...findQuestion,
  //                 showDelete: values.length > 1,
  //                 showAdd: k == values.length - 1,
  //                 value: v
  //               })
  //             }
  //           })
  //         } else {
  //           if (findQuestion.type == question.QUESTION_TYPE_CHECKBOX) {
  //             const values = Object.values(answer)
  //             console.log('测试', values, Object.values(answer), answer);
  //             findQuestion.value = Array.isArray(keys) ? keys.map((key: string, i: number) => {
  //               const findIdx = findQuestion.choices.findIndex(c => c.attr == key)
  //               if (findQuestion.choices[findIdx]?.isInput) {
  //                 findQuestion.choices[findIdx].extra = values[i]
  //               }
  //               return findIdx
  //             }) : []
  //           } else if (findQuestion.type == question.QUESTION_TYPE_RADIO) {
  //             findQuestion.value = findQuestion.choices.findIndex(c => c.attr == keys[0])
  //             if (findQuestion.choices[findQuestion.value]?.isInput) {
  //               findQuestion.choices[findQuestion.value].extra = values
  //             }
  //           } else if (findQuestion.type == question.QUESTION_TYPE_MATRIX) {
  //             const matrixAnswerValue = Object.values(answer)
  //             findQuestion.matrix = findQuestion.matrix.map((row: boolean[], k1: number) => {
  //               row = row?.map((col: boolean, k2: number) => {
  //                 return !!matrixAnswerValue.find(mV => mV[findQuestion.rows[k1].attr] && mV[findQuestion.columns[k2].attr])
  //               })
  //               return row
  //             })
  //           } else {
  //             findQuestion.value = Array.isArray(values) ? values.flat()[0] : values
  //           }
  //         }
  //       }
  //     }
  //   })
  // }
};

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

        temp.value = cur.map(formatItemVal);

        temp.rawValue = cur.map((v2: any) => {
          if (v.type == question.QUESTION_TYPE_GROUP) {
            return v2.children.map((v3: any) => v3.value);
          } else {
            return v2.value;
          }
        });
        console.log(temp.value, temp.rawValue);
        list.push(temp);
      }
    } else {
      console.log(v.type == question.QUESTION_TYPE_GROUP && "出现组合题", v);
      if (v.type == question.QUESTION_TYPE_GROUP) {
        list.push({
          ...v,
          rawValue: v.children.map((child: any) => child.value),
          value: formatItemVal(v)
        });
      } else {
        list.push({
          ...v,
          rawValue: v.value,
          value: formatItemVal(v)
        });
      }
    }
  });
  return list;
};
export const formatItemVal = (item: any) => {
  if (item.type === question.QUESTION_TYPE_GROUP) {
    item.value = item.children.map((v: any) => formatItemVal(v));
    return item.value;
  } else if (item.type === question.QUESTION_TYPE_MATRIX) {
    const res: string[] = [];
    item.matrix?.forEach((cols: any[], k1: number) => {
      cols &&
        cols.forEach &&
        cols?.forEach((c: boolean, k2: number) => {
          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: any) =>
          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;
  }
};

export const formatData = (list: any[], item: any) => {
  const result = [];
  list.forEach((v: any) => {
    result.push({
      extraType: item.type,
      // extraId: item.extraId,
      answer: formatResultDataItem(v)
    });
  });
  return result;
};

export const formatResultDataItem = (item: any) => {
  const resultItem = {
    multipleAnswers: item.isRepeat,
    type: item.type,
    questionNo: item.sn,
    checkboxAnswers: null,
    inputAnswers: null,
    matrixAnswers: null,
    linkAnswers: null,
    groupAnswers: null,
    answer: undefined as any
  };
  switch (item.type) {
    case question.QUESTION_TYPE_CHECKBOX:
      {
        const tmp = [];
        if (Array.isArray(item.rawValue)) {
          item.rawValue?.forEach((childIdx: number, k: number) => {
            const findChoices = item.choices[childIdx];
            tmp.push({
              key: findChoices?.attr,
              value: item.value[k]
            });
          });
        }
        resultItem.checkboxAnswers = tmp;
      }
      break;
    case question.QUESTION_TYPE_RADIO:
      {
        resultItem.answer = {
          key: item.choices[item.rawValue]?.attr,
          value: item.value
        };
      }
      break;
    case question.QUESTION_TYPE_SELECT:
      console.log();
      {
        resultItem.checkboxAnswers = item.rawValue || [];
      }
      break;
    // case question.QUESTION_TYPE_MEDICINE:
    // case question.QUESTION_TYPE_DISEASE:
    //   {
    //     const tmp = {}
    //     if (item.isRepeat) {
    //       item.value?.forEach((val: any) => {
    //         if (item.config?.showInput) {
    //           if (!tmp[item.config.attr]) {
    //             tmp[item.config.attr] = []
    //           }
    //           tmp[item.config.attr].push(val)
    //         } else {
    //           const findCheckSearchItem = item.searchList.find(v => v.name == val)
    //           const key = findCheckSearchItem ? findCheckSearchItem.sn : item.config.attr
    //           if (!tmp[key]) {
    //             tmp[key] = []
    //           }
    //           tmp[key].push(val)
    //         }
    //       })
    //     } else {
    //       const findCheckSearchItem = item.searchList.find(v => v.name == item.value)
    //       if (findCheckSearchItem) {
    //         tmp[findCheckSearchItem.sn] = item.value
    //       } else {
    //         tmp[item.config.attr] = item.value
    //       }
    //     }
    //     resultItem.answer = tmp
    //   }
    //   break
    case question.QUESTION_TYPE_INPUT:
      {
        const tmp = {
          key: item.attr,
          value: []
        };
        if (item.isRepeat) {
          item.value?.forEach((val: any) => {
            tmp.value.push(val);
          });
        } else {
          tmp.value = Array.isArray(item.value) ? item.value : [item.value];
        }
        resultItem.inputAnswers = tmp;
      }
      break;
    case question.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.QUESTION_TYPE_DATE:
      {
        resultItem.answer = {
          key: item.attr,
          value: Array.isArray(item.value) ? item.value[0] : item.value
        };
      }
      break;
    case question.QUESTION_TYPE_MATRIX:
      resultItem.matrixAnswers = [];
      item.matrix.forEach((cols: boolean[], k1: number) => {
        cols.forEach((check: boolean, k2: number) => {
          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.QUESTION_TYPE_GROUP:
      resultItem.groupAnswers = [] as any[];
      (item.isRepeat ? item.value : [item.value])?.forEach(
        (val: any, k: number) => {
          const temp = [];
          item.children.forEach((child: any, childIdx: number) => {
            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;
};
export const formatValidator = (validator: any[]) => {
  const result: any[] = [];
  const opt = {};
  const repeatKey: string[] = [];
  validator.forEach(v => {
    const tempItem = {
      ...v
    };
    if (tempItem.type == question.QUESTION_TYPE_MATRIX) {
      if (
        !tempItem.matrix ||
        !tempItem.matrix.length ||
        tempItem.matrix.length !=
          tempItem.columns?.length * tempItem.rows?.length
      ) {
        tempItem.matrix = Array(tempItem.rows.length)
          .fill(0)
          .map(() => Array(tempItem.columns.length).fill(false));
      }
    }
    !repeatKey.includes(v.combination || v.attr) &&
      repeatKey.push(v.combination || v.attr);
    // 组合题
    // if (v.combination) {
    //   if (!opt[v.combination]) {
    //     opt[v.combination] = v.attr
    //   }
    //   const combinationIdx: number[] = []
    //   let combinationAdd = false
    //   result.forEach((v2: any, k2: number) => v2.combination === v.combination && combinationIdx.push(k2))

    //   opt[v.combination] == v.attr && result.push({
    //     type: 'combination',
    //     combination: v.combination,
    //     edit: true,
    //     isRepeat: v.isRepeat,
    //     showAdd: v.isRepeat,
    //     showDelete: false,
    //     title: '',
    //     value: '',
    //     config: {
    //       required: true,
    //       next: null,
    //       desc: '',
    //       rule: '',
    //     },
    //     children: [{...v}]
    //   })

    //   combinationIdx.forEach((findIdx: number) => {
    //     const findIsRepeat = result[findIdx].children.map((v2: any) => v2.attr).includes(tempItem.attr)
    //     if (!findIsRepeat && !combinationAdd) {
    //       result[findIdx].children.push(tempItem)
    //       result[findIdx].isRepeat = !result[findIdx].isRepeat ? tempItem.isRepeat : true
    //       result[findIdx].showAdd = result[findIdx].isRepeat
    //       combinationAdd = true
    //     }
    //   })
    // } else {
    // }
    tempItem.showAdd = !!tempItem.isRepeat;
    result.push(tempItem);
  });
  repeatKey.forEach((key: string) => {
    const filterResult = result.filter(
      (v: any) => v.combination === key || v.attr === key
    );
    console.log(key, filterResult);
    let count = 1;
    result.forEach((v2: any) => {
      if (v2.combination === key || v2.attr === key) {
        v2.showDelete = filterResult.length > 1;
        v2.showAdd = count === filterResult.length;
        count++;
      }
    });
  });
  console.log("repeatKey", repeatKey);

  console.log(result);
  return result;
};

/*******
 *  @description: 序列化显示档案值
 *  @return { * }
 */
export const formateArchivesModuleValue = (item: any, hasValue = true) => {
  // console.log(item.name, item);
  const list = [];
  if (item.fields?.length) {
    item.fields.forEach(filed => {
      if (filed.extra?.subjects) {
        filed.extra?.subjects.forEach(subject => {
          formatModuleItemValue(subject.name || subject.title, subject, list);
        });
      } else {
        if (filed.extra?.sn) {
          formatModuleItemValue(
            filed.extra.name || filed.extra.title,
            filed.extra,
            list
          );
        }
      }
    });
  }
  if (item.extra?.subjects) {
    item.extra?.subjects.forEach(subject => {
      formatModuleItemValue(subject.name || subject.title, subject, list);
    });
  } else {
    if (item.extra?.sn) {
      formatModuleItemValue(
        item.extra.name || item.extra.title,
        item.extra,
        list
      );
    }
  }
  if (hasValue) {
    item.hasValue = !!list.length;
    return list;
  } else {
    const filterList = list.filter(v => v.value || v.value === 0);
    item.hasValue = !!filterList.length;
    return filterList;
  }
};
const isImage = url =>
  /^https?:\/\/(.+\/)+.+(\.(gif|png|jpg|jpeg|webp|svg|psd|bmp|tif))$/i.test(
    url
  );
export const formatModuleItemValue = (label, subject, list, isPush = true) => {
  const { returnAnswer } = subject;
  console.log(subject);
  const validator = parseJSON(subject.validator) || subject;
  if (validator.isHidden) return;
  // console.log('validator', validator);
  let opt: any = undefined;
  if (returnAnswer) {
    let value;
    switch (returnAnswer.type) {
      case question.QUESTION_TYPE_CHECKBOX:
        {
          value = returnAnswer.checkboxAnswers.map(v => {
            const choice =
              validator?.choices?.find &&
              validator?.choices?.find(v2 => v2.attr == v.key);
            return choice?.isInput
              ? choice.label + (v.value ? ":" + v.value : v.value)
              : v.value;
          });
        }
        break;
      case question.QUESTION_TYPE_RADIO:
        {
          const choice =
            validator?.choices?.find &&
            validator?.choices?.find(v2 => v2.attr == returnAnswer.answer.key);
          value = choice?.isInput
            ? choice.label +
              (returnAnswer.answer.value
                ? ":" + returnAnswer.answer.value
                : returnAnswer.answer.value)
            : returnAnswer.answer.value;
        }
        break;
      case question.QUESTION_TYPE_INPUT:
        value = returnAnswer.inputAnswers.value;
        break;
      case question.QUESTION_TYPE_UPLOAD:
        value = returnAnswer.linkAnswers?.value;
        console.log(value);
        opt = {
          isImage,
          isFile: true
        };
        break;

      case question.QUESTION_TYPE_SELECT:
        {
          console.log("QUESTION_TYPE_SELECT", returnAnswer.checkboxAnswers);
          value = returnAnswer.checkboxAnswers.map(v => v.value);
        }
        break;
      case question.QUESTION_TYPE_DATE:
        value = returnAnswer.answer.value;
        break;
      case question.QUESTION_TYPE_MATRIX:
        value = returnAnswer.matrixAnswers.map(v => `${v.xText}${v.yText}`);
        break;
      case question.QUESTION_TYPE_GROUP:
        {
          const temp = {};
          returnAnswer.groupAnswers.forEach(arr => {
            arr.forEach((v, k) => {
              if (!temp[k]) {
                temp[k] = [];
              }
              temp[k].push(
                formatModuleItemValue(
                  validator.children[k]?.title,
                  {
                    ...validator.children[k],
                    returnAnswer: v
                  },
                  list,
                  false
                )
              );
            });
          });
          (temp[0] || []).forEach((_, valIdx) => {
            valIdx &&
              list.push({
                isPlaceholder: true,
                value: " ",
                style: 'height: 10px;'
              });
            Object.keys(temp).forEach(i => {
              const label = validator.children[i]?.title;
              list.push({
                label,
                value: Array.isArray(temp[i][valIdx])
                  ? temp[i][valIdx].join()
                  : temp[i][valIdx]
                // value: Array.isArray(temp[i]) ? temp[i].join() : temp[i]
              });
            });


          });
          console.log(temp);

          // value = returnAnswer.groupAnswers.map(arr => arr.map(v => formatModuleItemValue({
          //   returnAnswer: v
          // }, isJoinVal)))
        }
        break;
    }
    isPush &&
      list.push({
        label,
        value: Array.isArray(value) && !opt?.isFile ? value.join() : value,
        opt
      });
    return value;
    // return isJoinVal ? (Array.isArray(value) ? value.join() : value) : value
  }
};
