import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import styles from "./index.module.scss";
import { Button, Checkbox, Input, Modal, Select } from "antd";
import MyPopconfirm from "@/components/MyPopconfirm";
import { A6QListType, A6QListTypeSlist, options1, options2 } from "../data";
import { MessageFu } from "@/utils/message";
import TextArea from "antd/es/input/TextArea";
import { CloseCircleOutlined } from "@ant-design/icons";
import classNames from "classnames";
import {
  A6Q_API_Tadds,
  A6Q_API_Tdels2,
  A6Q_API_Tedit,
  A6Q_API_TgetInfo,
} from "@/store/action/A6_1ques";

const oneObj: A6QListType = {
  id: 1,
  name: "",
  type: "单选",
  skip: "不需要",
  custom: false,
  num: 1,
  sList: [
    { id: 1.1, txt: "", skip2: false, num2: 1 },
    { id: 1.2, txt: "", skip2: false, num2: 1 },
  ],
};

type Props = {
  moInfo: { id: number; num: number };
  closeFu: () => void;
  tableLen: number; //当前已经有的题目数量（表格）
  upTableFu: () => void;
  // 最外层 表格 的id
  fatherId: number;
};

function QTadd({ moInfo, closeFu, tableLen, upTableFu, fatherId }: Props) {
  const sListOldIds = useRef([] as number[]);
  const sListDelIds = useRef([] as number[]);

  const getInfoFu = useCallback(async (id: number) => {
    const res = await A6Q_API_TgetInfo(id);
    if (res.code === 0) {
      const data = res.data;
      const sListArr: A6QListTypeSlist[] = [];
      data.options.forEach((v: any) => {
        // 编辑的时候存下 之前信息的id数组 判断 提交时选项 id是否要传null
        sListOldIds.current.push(v.id);
        if (v.name !== "其他") {
          sListArr.push({
            id: v.id,
            txt: v.name,
            skip2: v.skip,
            num2: v.skipQuestionNum,
          });
        }
      });

      setList([
        {
          id: data.id,
          name: data.question,
          type: data.type,
          skip: data.skip,
          num: data.skipQuestionNum,
          custom: data.custom,
          sList: sListArr,
        },
      ]);
    }
  }, []);

  useEffect(() => {
    if (moInfo.id > 0) getInfoFu(moInfo.id);
    else {
      // 新增
      setList([oneObj]);
    }
  }, [getInfoFu, moInfo.id]);

  // 是否 已经点击过确定
  const [fileCheck, setFileCheck] = useState(false);

  // 题目的数组
  const [list, setList] = useState<A6QListType[]>([]);

  // useEffect(() => {
  //   console.log("------", list);
  // }, [list]);

  // 点击新增题目
  const addListFu = useCallback(
    (rank: 1 | 2, length?: number, id?: number) => {
      if (rank === 1 && list.length + tableLen >= 50)
        return MessageFu.warning("最多支持50题!");
      if (length && length >= 6) return MessageFu.warning("最多6个选项!");
      if (rank === 1) {
        setList([
          ...list,
          {
            id: Date.now(),
            name: "",
            type: "单选",
            skip: "不需要",
            custom: false,
            num: 1,
            sList: [
              { id: Date.now() - 100, txt: "", skip2: false, num2: 1 },
              { id: Date.now() - 200, txt: "", skip2: false, num2: 1 },
            ],
          },
        ]);
      } else {
        setList(
          list.map((v, i) => ({
            ...v,
            sList:
              v.id === id
                ? [
                    ...v.sList,
                    {
                      id: Date.now() - 300 - i * 10,
                      txt: "",
                      skip2: false,
                      num2: 1,
                    },
                  ]
                : v.sList,
          }))
        );
      }
    },
    [list, tableLen]
  );

  // 点击删除
  const delListFu = useCallback(
    (rank: 1 | 2, id: number) => {
      if (rank === 1) {
        setList(list.filter((v) => v.id !== id));
      } else {
        if (sListOldIds.current.includes(id)) {
          sListDelIds.current.push(id);
        }

        setList(
          list.map((v) => ({
            ...v,
            sList: v.sList.filter((v2) => v2.id !== id),
          }))
        );
      }
    },
    [list]
  );

  // 信息的改变(不包含 选择跳题 题目的下拉框)
  const dataChangeFu = useCallback(
    (
      e: string | boolean,
      id: number,
      key: "name" | "type" | "skip" | "custom" | "txt" | "skip2",
      index: number
    ) => {
      let value: string | boolean;
      if (typeof e === "string") value = e.replace(/\s+/g, "");
      else value = e;

      let num = index;
      if (index === 1) num = 2;
      else num = 1;

      // 第二级信息的改变
      if (key === "txt" || key === "skip2") {
        setList(
          list.map((v) => ({
            ...v,
            sList: v.sList.map((v2) => ({
              ...v2,
              num2: id === v2.id ? num : v2.num2,
              [key]: id === v2.id ? value : v2[key],
            })),
          }))
        );
      } else {
        // 第一级信息的改变

        setList(
          list.map((v) => ({
            ...v,
            num: id === v.id ? num : v.num,
            [key]: id === v.id ? value : v[key],
          }))
        );
      }
    },
    [list]
  );

  // 选择跳题 题目的下拉框
  const skipChangeFu = useCallback(
    (e: number, id: number, len: 1 | 2) => {
      if (len === 1) {
        setList(
          list.map((v) => ({
            ...v,
            num: id === v.id ? e : v.num,
          }))
        );
      } else {
        setList(
          list.map((v) => ({
            ...v,
            sList: v.sList.map((v2) => ({
              ...v2,
              num2: v2.id === id ? e : v2.num2,
            })),
          }))
        );
      }
    },
    [list]
  );

  // 跳题的数组
  const numList = useMemo(() => {
    let arr: number[] = [];

    let numRes = tableLen;
    if (moInfo.id < 0) numRes += list.length;

    for (let ii = 0; ii < numRes; ii++) {
      arr.push(ii + 1);
    }
    return arr;
  }, [list.length, moInfo.id, tableLen]);

  // 单个题目是否全部填写标准
  const oneFlag = useCallback((info: A6QListType) => {
    let flag = false;

    // 题目和选项是否填写
    if (!info.name) flag = true;
    else if (info.type !== "填空") {
      flag = info.sList.some((v) => !v.txt);
    }

    // 下拉框勾选了选项跳题，但是子选项一个跳题都没有勾选
    if (info.skip === "选项跳题" && info.sList.every((v) => !v.skip2))
      flag = true;

    return flag;
  }, []);

  // 点击提交
  const btnOkFu = useCallback(async () => {
    setFileCheck(true);

    const dom = document.querySelector(".A6Qlist2SonErrBox");
    if (dom) return MessageFu.warning("请规范填写题目信息!");

    const arrTemp = [] as any;

    let ohterFlag = false;

    list.forEach((v) => {
      const optionsTemp = [] as any;
      v.sList.forEach((v2) => {
        if (v2.txt === "其他") ohterFlag = true;

        optionsTemp.push({
          id: sListOldIds.current.includes(v2.id) ? v2.id : null,
          name: v2.txt,
          skip: v2.skip2,
          skipQuestionNum: v2.num2,
        });
      });

      arrTemp.push({
        custom: v.custom,
        id: moInfo.id > 0 ? v.id : null,
        question: v.name,
        questionnaireId: fatherId,
        skip: v.skip,
        skipQuestionNum: v.num,
        type: v.type,
        options: optionsTemp,
      });
    });

    // 选项 字段 不能为其他
    if (ohterFlag) return MessageFu.warning("选项字段不能为 其他 !");

    if (moInfo.id < 0) {
      // 新增
      const res = await A6Q_API_Tadds(arrTemp);
      if (res.code === 0) {
        MessageFu.success("新增成功!");
        upTableFu();
        closeFu();
      }
    } else {
      // 编辑
      // 删除 选项id
      if (sListDelIds.current.length)
        await A6Q_API_Tdels2(sListDelIds.current.join(","));

      const res2 = await A6Q_API_Tedit(arrTemp[0]);
      if (res2.code === 0) {
        MessageFu.success("编辑成功!");
        upTableFu();
        closeFu();
      }
    }
  }, [closeFu, fatherId, list, moInfo.id, upTableFu]);

  // 下拉框的筛选数字/题目序号
  const selectNum = useCallback(
    (i: number) => {
      return moInfo.id > 0 ? moInfo.num : tableLen + i + 1;
    },
    [moInfo.id, moInfo.num, tableLen]
  );

  return (
    <Modal
      wrapClassName={styles.QTadd}
      open={true}
      title={
        <div className="QTatitle">
          <div>{moInfo.id > 0 ? "编辑" : "新增"}题目</div>
          <div>
            {moInfo.id < 0 ? (
              <>
                <span className="QTatitleS">最多支持50题</span>
                &emsp;
                <Button
                  type="primary"
                  onClick={() => addListFu(1)}
                  disabled={tableLen + list.length >= 50}
                >
                  新增
                </Button>
              </>
            ) : null}
          </div>
        </div>
      }
      footer={
        [] // 设置footer为空，去掉 取消 确定默认按钮
      }
    >
      <div className="QTmain">
        <div className="A6Qlist">
          <div className="A6Qlist2">
            {list.map((v, i) => (
              <div
                className={classNames(
                  "A6Qlist2Son",
                  oneFlag(v) && fileCheck ? "A6Qlist2SonErr" : "",
                  oneFlag(v) ? "A6Qlist2SonErrBox" : ""
                )}
                key={v.id}
              >
                {/* 1级 删除 */}
                {i === 0 ? null : (
                  <MyPopconfirm
                    txtK="删除"
                    onConfirm={() => delListFu(1, v.id)}
                    Dom={
                      <div className="A6Q2del">
                        <CloseCircleOutlined rev={undefined} />
                      </div>
                    }
                  />
                )}

                {/* 题目 */}
                <div className="A6Q2_1">
                  <div>
                    <span>*</span> 题目 {selectNum(i)}
                  </div>
                  <div>
                    <TextArea
                      value={v.name}
                      onChange={(e) =>
                        dataChangeFu(e.target.value, v.id, "name", selectNum(i))
                      }
                      className="A6text"
                      placeholder="请输入内容"
                      showCount
                      maxLength={200}
                    />
                  </div>
                </div>

                <div className="A6Q2_2">
                  {/* 类型 跳题 自定义 */}
                  <div>
                    类型&emsp;
                    <Select
                      disabled={v.skip === "选项跳题"}
                      value={v.type}
                      onChange={(e) =>
                        dataChangeFu(e, v.id, "type", selectNum(i))
                      }
                      placeholder="请选择"
                      style={{ width: 100 }}
                      options={options1}
                    />
                    &emsp;&emsp;跳题&emsp;
                    <Select
                      value={v.skip}
                      onChange={(e) =>
                        dataChangeFu(e, v.id, "skip", selectNum(i))
                      }
                      placeholder="请选择"
                      style={{ width: 100 }}
                      options={
                        v.type === "单选"
                          ? options2
                          : options2.filter((c) => c.label !== "选项跳题")
                      }
                    />
                    <span hidden={v.skip !== "答完跳题"}>
                      &emsp;&emsp;跳至第&emsp;
                      <Select
                        value={v.num}
                        onChange={(e) => skipChangeFu(e, v.id, 1)}
                        placeholder="请选择"
                        style={{ width: 100 }}
                        options={numList
                          .filter((b) => b !== selectNum(i))
                          .map((c) => ({
                            value: c,
                            label: c,
                          }))}
                      />
                      &emsp;题
                    </span>
                    &emsp;&emsp;
                    {v.type === "填空" ? null : (
                      <Checkbox
                        checked={v.custom}
                        onChange={(e) =>
                          dataChangeFu(
                            e.target.checked,
                            v.id,
                            "custom",
                            selectNum(i)
                          )
                        }
                      >
                        支持填写自定义回答
                      </Checkbox>
                    )}
                  </div>

                  {/* 子选项 */}
                  <div className="A6Q2_21main" hidden={v.type === "填空"}>
                    {v.sList.map((v2, i2) => (
                      <div className="A6Q2_21Son" key={v2.id}>
                        <div>
                          <span>*</span> 选项 {i2 + 1}
                        </div>

                        <div>
                          <Input
                            value={v2.txt}
                            onChange={(e) =>
                              dataChangeFu(
                                e.target.value,
                                v2.id,
                                "txt",
                                selectNum(i)
                              )
                            }
                            maxLength={50}
                            showCount
                            placeholder="请输入内容"
                          />
                        </div>

                        {/* 2级 跳题 */}
                        <span
                          className="A6Q2skip2"
                          hidden={v.skip !== "选项跳题"}
                        >
                          <Checkbox
                            checked={v2.skip2}
                            onChange={(e) =>
                              dataChangeFu(
                                e.target.checked,
                                v2.id,
                                "skip2",
                                selectNum(i)
                              )
                            }
                          >
                            跳题
                          </Checkbox>
                          <span hidden={!v2.skip2}>
                            &nbsp;跳至第&nbsp;
                            <Select
                              value={v2.num2}
                              onChange={(e) => skipChangeFu(e, v2.id, 2)}
                              placeholder="请选择"
                              style={{ width: 80 }}
                              options={numList
                                .filter(
                                  (b) =>
                                    b !==
                                    (moInfo.id > 0
                                      ? moInfo.num
                                      : tableLen + i + 1)
                                )
                                .map((c) => ({
                                  value: c,
                                  label: c,
                                }))}
                            />
                            &nbsp;题
                          </span>
                        </span>

                        {/* 2级 删除 */}
                        {i2 <= 1 ? null : (
                          <MyPopconfirm
                            txtK="删除"
                            onConfirm={() => delListFu(2, v2.id)}
                            Dom={
                              <div className="A6Q2del2">
                                <CloseCircleOutlined rev={undefined} />
                              </div>
                            }
                          />
                        )}
                      </div>
                    ))}
                  </div>
                  {/* 子选项的新增 */}
                  <div className="A6Q2_22" hidden={v.type === "填空"}>
                    <Button
                      onClick={() => addListFu(2, v.sList.length, v.id)}
                      disabled={v.sList.length >= 6}
                    >
                      新增选项
                    </Button>
                    &emsp;
                    <span>最多支持6个选项</span>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>

        <div className="QTbtn">
          <Button type="primary" onClick={btnOkFu}>
            提交
          </Button>
          &emsp;
          <MyPopconfirm txtK="取消" onConfirm={closeFu} />
        </div>
      </div>
    </Modal>
  );
}

const MemoQTadd = React.memo(QTadd);

export default MemoQTadd;
