import React, { useCallback, useEffect, useState } from "react";
import styles from "./index.module.scss";
import { A6Q_APIresList, A6Q_APIresTabList } from "@/store/action/A6_1ques";
import { Button, Table } from "antd";
import classNames from "classnames";
import htmlToPdf2 from "@/utils/htmlToPdf2";
import { domShowFu } from "@/utils/domShow";
import { MessageFu } from "@/utils/message";
import dayjs from "dayjs";
import EchBox from "./EchBox";
import Tab1Look from "./Tab2Look";
import {
  DataResListType,
  DataResTabListOptionsType,
  DataResTabListTabCutType,
  DataResTabListTxtType,
  DataResTabListType,
  columnsObj,
} from "./data";
import EchTxt from "./EchTxt";

type DataType = {
  id: number;
  name: string;
  publishDate: string;
  description: string;
  resList: DataResListType[];
  resTabList: DataResTabListType[];
};

type Props = {
  sId: number;
  closeFu: () => void;
};

const tabCutArr = [
  { id: 1, name: "结果明细" },
  { id: 2, name: "结果统计" },
];

function A6QInfo({ sId, closeFu }: Props) {
  const getInfoFu = useCallback(async () => {
    const res1 = await A6Q_APIresList(sId);
    const res2 = await A6Q_APIresTabList(sId);
    if (res1.code === 0 && res2.code === 0) {
      const temp1 = res1.data;
      const temp2 = res2.data;
      setData({
        id: temp2.id,
        name: temp2.name,
        publishDate: temp2.publishDate,
        description: temp2.description,
        resList: temp1,
        resTabList: temp2.questions.map((v: any) => ({
          ...v,
          tabCut: [
            { name: "表格", done: true },
            { name: "柱状图", done: false },
            { name: "折线图", done: false },
            { name: "饼图", done: false },
          ],
          tabAc: "表格",
          optionsCount: v.optionsCount
            ? v.optionsCount.map((v2: any, index: number) => ({
                ...v2,
                id: v.id + "" + index,
              }))
            : [],
        })),
      });
    }
  }, [sId]);

  useEffect(() => {
    getInfoFu();
  }, [getInfoFu]);

  // 全部数据
  const [data, setData] = useState({} as DataType);

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

  // 结果明细和结果统计切换
  const [tabCut, setTabCut] = useState(1);

  // 隐藏 结果明细 文字 用于导出
  const [isToPdf, setIsToPdf] = useState(false);

  // 点击 切换 表格 和图表
  const cutTableOrEch = useCallback(
    (id: number, name: DataResTabListTabCutType) => {
      setData({
        ...data,
        resTabList: data.resTabList.map((v) => ({
          ...v,
          tabCut:
            v.id === id
              ? v.tabCut.map((v2) => ({
                  name: v2.name,
                  done: name === v2.name ? true : v2.done,
                }))
              : v.tabCut,
          tabAc: v.id === id ? name : v.tabAc,
        })),
      });
    },
    [data]
  );

  // 表格数据
  const columnsFu = useCallback(
    (flag: boolean, type?: DataResTabListTxtType) => {
      let arr: any = [];
      if (flag && type) {
        // --------------结果统计

        if (type === "填空") {
          arr = [
            {
              width: 300,
              title: "选择人数",
              dataIndex: "pcs",
            },
            {
              title: "选项描述",
              render: (item: DataResTabListOptionsType) =>
                item.customDesc
                  ? item.customDesc
                      .split(";")
                      .filter((c) => c)
                      .map((v, i) => (
                        <div key={i} className="A6QtableLeft">
                          <span>{i + 1}：</span>{v}
                        </div>
                      ))
                  : "（空）",
            },
          ];
        } else {
          arr = [
            {
              width: type === "排序" ? 100 : 150,
              title: "选项",
              render: (
                item: DataResTabListOptionsType,
                _: any,
                index: number
              ) =>
                item.name === "其他"
                  ? "自定义回答"
                  : Reflect.get(columnsObj, index),
            },
            {
              width: type === "排序" ? 100 : 150,
              title: "选择人数",
              dataIndex: "pcs",
            },
          ];

          if (type === "排序") {
            arr.push({
              width: type === "排序" ? 100 : 150,
              title: "选项得分",
              render: (item: DataResTabListOptionsType) => item.score || 0,
            });
          }
          arr.push({
            title: "选项描述",
            render: (item: DataResTabListOptionsType) => {
              if (item.name !== "其他") return item.name || "（空）";
              else {
                return item.customDesc
                  ? item.customDesc
                      .split(";")
                      .filter((c) => c)
                      .map((v, i) => (
                        <div key={i} className="A6QtableLeft">
                          <span>{i + 1}：</span>{v}
                        </div>
                      ))
                  : "（空）";
              }
            },
          });
        }
      } else {
        // ---------------结果明细
        arr = [
          {
            title: "提交时间",
            dataIndex: "createTime",
          },
          {
            title: "操作",
            render: (item: DataResListType) => (
              <>
                <Button
                  size="small"
                  type="text"
                  onClick={() =>
                    setTab1Info({
                      id: item.id,
                      time: item.createTime,
                      txt: "查看",
                    })
                  }
                >
                  查看
                </Button>
                <Button
                  size="small"
                  type="text"
                  onClick={() =>
                    setTab1Info({
                      id: item.id,
                      time: item.createTime,
                      txt: "导出结果",
                    })
                  }
                >
                  导出结果
                </Button>
              </>
            ),
          },
        ];
      }
      return arr;
    },
    []
  );

  // 点击右边的 导出问卷
  const html2PdfFu = useCallback(() => {
    setIsToPdf(true);
    domShowFu("#AsyncSpinLoding", true);

    setTabCut(2);

    window.setTimeout(() => {
      const dom = document.querySelector(".A6QInfoBox") as HTMLDivElement;
      if (dom) {
        const name =
          "问卷统计结果" + dayjs(new Date()).format("YYYY-MM-DD HH:mm");

        htmlToPdf2(dom, name, () => {
          setIsToPdf(false);
          domShowFu("#AsyncSpinLoding", false);
        });
      } else {
        MessageFu.warning("找不到元素!");
        setIsToPdf(false);
        domShowFu("#AsyncSpinLoding", false);
      }
    }, 500);
  }, []);

  // 点击 左侧的结果明细 查看 和导出
  const [tab1Info, setTab1Info] = useState({
    id: 0,
    time: "",
    txt: "" as "" | "查看" | "导出结果",
  });

  return (
    <div className={styles.A6QInfo}>
      <div className="A6QInfoBoxCC">
        {/* 右上角的返回 */}
        <div className="A6QtopBack">
          <Button type="primary" onClick={html2PdfFu}>
            导出问卷
          </Button>
          <Button onClick={closeFu}>返回</Button>
        </div>
        {/* 主体 */}
        <div className="A6QInfoBox">
          <div className="A6Qtop">{data.name} </div>
          <div className="A6Qmain">
            <div className="A6QM1">
              <span>发布日期：</span>
              {data.publishDate}
            </div>
            {data.description ? (
              <div
                className="A6QM2"
                dangerouslySetInnerHTML={{ __html: data.description }}
              ></div>
            ) : null}

            {/* 结果明细 结果统计 */}
            <div className="A6QCbox">
              <div className="A6QC1">
                {tabCutArr.map((v) => (
                  <div
                    hidden={isToPdf && v.id === 1}
                    onClick={() => setTabCut(v.id)}
                    className={classNames(v.id === tabCut ? "A6QC1Ac" : "")}
                    key={v.id}
                  >
                    {v.name}
                  </div>
                ))}
              </div>
              {data.resList ? (
                <div className="A6QC2" hidden={tabCut !== 1}>
                  <Table
                    columns={columnsFu(false)}
                    dataSource={data.resList}
                    rowKey="id"
                    pagination={false}
                  />
                </div>
              ) : null}
              {data.resTabList && data.resTabList.length ? (
                data.resTabList.map((v, i) => (
                  <div className="A6QC2" hidden={tabCut !== 2} key={v.id}>
                    <div className="A6QC2Txt">
                      <span>
                        {i + 1}.{v.type}：
                      </span>
                      {v.question}
                    </div>

                    {/* 切换内容 */}
                    <div className="A6QC2Tab" hidden={isToPdf}>
                      {/* 填空题只有 表格 */}
                      {v.tabCut.map((v2) => (
                        <Button
                          type={v.tabAc === v2.name ? "primary" : "default"}
                          hidden={v.type === "填空" && v2.name !== "表格"}
                          className={classNames(
                            // 没有数据的隐藏
                            v.optionsCount && v.optionsCount.length
                              ? ""
                              : "A6QC2TabDis"
                          )}
                          key={v2.name}
                          onClick={() => cutTableOrEch(v.id, v2.name)}
                        >
                          {v2.name}
                        </Button>
                      ))}
                    </div>

                    {/* 内容展示 */}
                    <div className="A6QC2Centen">
                      {/* 表格 */}
                      {v.optionsCount && v.optionsCount.length ? (
                        <div hidden={v.tabAc !== "表格"}>
                          <Table
                            columns={columnsFu(true, v.type)}
                            dataSource={v.optionsCount}
                            rowKey="id"
                            pagination={false}
                          />
                        </div>
                      ) : (
                        <div className="sonTableNone">暂无数据</div>
                      )}
                    </div>

                    <div className="A6FechBox">
                      {v.tabCut.find((v) => v.name === "柱状图")?.done ? (
                        <EchBox
                          hidden={v.tabAc !== "柱状图"}
                          type={v.tabAc}
                          info={v}
                        />
                      ) : null}
                      {v.tabCut.find((v) => v.name === "折线图")?.done ? (
                        <EchBox
                          hidden={v.tabAc !== "折线图"}
                          type={v.tabAc}
                          info={v}
                        />
                      ) : null}
                      {v.tabCut.find((v) => v.name === "饼图")?.done ? (
                        <EchBox
                          hidden={v.tabAc !== "饼图"}
                          type={v.tabAc}
                          info={v}
                        />
                      ) : null}

                      <EchTxt info={v} hidden={v.tabAc === "表格"} />
                    </div>
                  </div>
                ))
              ) : (
                <div className="A6QC2None" hidden={tabCut !== 2}>
                  暂无数据
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* 结果明细的 查看 和 导出 */}
      {tab1Info.txt ? (
        <Tab1Look
          waiId={sId}
          fatherInfo={tab1Info}
          colseFu={() => setTab1Info({ id: 0, time: "", txt: "" })}
        />
      ) : null}
    </div>
  );
}

const MemoA6QInfo = React.memo(A6QInfo);

export default MemoA6QInfo;
