import BreadTit from "@/components/BreadTit";
import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import styles from "./index.module.scss";
import classNames from "classnames";
import dayjs from "dayjs";
import * as echarts from "echarts/core";
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
} from "echarts/components";
import { PieChart } from "echarts/charts";
import { LabelLayout } from "echarts/features";
import { CanvasRenderer } from "echarts/renderers";
import { Button, Table } from "antd";
import {
  getStores2API1,
  getStores2API2,
  getStores2API3,
  getStores2API4,
} from "@/store/action/stores1";
import ExportJsonExcel from "js-export-excel";
import { MessageFu } from "@/utils/message";

echarts.use([
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  PieChart,
  CanvasRenderer,
  LabelLayout,
]);

function Stores2() {
  const [titData, setTitData] = useState([
    { id: 1, name: "文物类别", domId: "echarts1", done: true, ref: "one" },
    { id: 2, name: "藏品级别", domId: "echarts2", done: true, ref: "tow" },
    { id: 3, name: "藏品来源", domId: "echarts3", done: true, ref: "three" },
    { id: 4, name: "完残程度", domId: "echarts4", done: true, ref: "four" },
  ]);

  // 生成图表的函数
  const echartsFu = useCallback((dom: any, data: any) => {
    const chartDom: any = document.getElementById(dom);
    const myChart = echarts.init(chartDom);
    const option = {
      tooltip: {
        trigger: "item",
      },

      series: [
        {
          type: "pie",
          radius: ["40%", "70%"],
          data,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: "rgba(0, 0, 0, 0.5)",
            },
          },
        },
      ],
    };
    option && myChart.setOption(option);
  }, []);

  const dataRef = useRef<any>({});
  const [results, setResults] = useState<any>([]);
  // 获取数据的函数
  const getInfo = useCallback(async () => {
    const res1 = await getStores2API1();
    setResults(res1.data);
    const data1 = res1.data.map((v: any) => {
      return {
        value: v.count,
        name: v.groupKey + Number(v.percent * 100).toFixed(1) + "%",
      };
    });
    dataRef.current.one = data1;
    echartsFu("echarts1", data1);

    const res2 = await getStores2API2();
    const data2 = res2.data.map((v: any) => {
      return {
        value: v.count,
        name: v.groupKey + Number(v.percent * 100).toFixed(1) + "%",
      };
    });
    dataRef.current.tow = data2;
    echartsFu("echarts2", data2);

    const res3 = await getStores2API3();
    const data3 = res3.data.map((v: any) => {
      return {
        value: v.count,
        name: v.groupKey + Number(v.percent * 100).toFixed(1) + "%",
      };
    });
    dataRef.current.three = data3;
    echartsFu("echarts3", data3);

    const res4 = await getStores2API4();
    const data4 = res4.data.map((v: any) => {
      return {
        value: v.count,
        name: v.groupKey + Number(v.percent * 100).toFixed(1) + "%",
      };
    });
    dataRef.current.four = data4;
    echartsFu("echarts4", data4);

    // 获取到所有数据并且渲染完图表之后在隐藏
    setTitData([
      { id: 1, name: "文物类别", domId: "echarts1", done: true, ref: "one" },
      { id: 2, name: "藏品级别", domId: "echarts2", done: true, ref: "tow" },
      { id: 3, name: "藏品来源", domId: "echarts3", done: false, ref: "three" },
      { id: 4, name: "完残程度", domId: "echarts4", done: false, ref: "four" },
    ]);
  }, [echartsFu]);

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

  // 图表的显示和隐藏
  const showEchartFu = useCallback(
    (id: number) => {
      const data = titData.map((v) => {
        return {
          ...v,
          done: id === v.id ? !v.done : v.done,
        };
      });
      setTitData(data);
    },
    [titData]
  );

  // 表格数据
  const columns = useMemo(() => {
    return [
      {
        title: "文物类别",
        dataIndex: "groupKey",
      },
      {
        title: "数量",
        dataIndex: "count",
      },
    ];
  }, []);

  // 点击导出
  const deriveFu = useCallback((ref: string, name: string) => {
    const data = dataRef.current[ref];
    if (data && data.length === 0) return MessageFu.warning("当前没有数据!");
    const option = {
      fileName: name,
      datas: [
        {
          sheetData: data,
          sheetName: name,
          sheetFilter: ["name", "value"],
          sheetHeader: [name + "和占比", "数量"],
          columnWidths: [20, 20],
        },
      ],
    };

    const toExcel = new ExportJsonExcel(option); //new
    toExcel.saveExcel(); //保存
  }, []);

  return (
    <div className={styles.Stores2}>
      <div className="breadTit">
        <BreadTit>
          <div className="breadTitRow active">统计报表</div>
        </BreadTit>
      </div>
      <div className="objectSonMain">
        <div className="mainBox">
          <div className="stores2Tit">
            <span>统计类型：</span>
            {titData.map((v) => (
              <div
                onClick={() => showEchartFu(v.id)}
                key={v.id}
                className={classNames("stores2Tit_row", v.done ? "active" : "")}
              >
                {v.name}
              </div>
            ))}
          </div>
          <div className="stores2Main">
            <div className="stores2Main_top">
              {titData.map((v) => (
                <div className="rowTop" key={v.id} hidden={!v.done}>
                  <div className="rowTopTit">
                    <p>{v.name + "发布"}</p>
                    <p className="rowTopTit_2">
                      {dayjs(Date.now()).format("YYYY年MM月DD")} | 每日0：00刷新
                    </p>
                  </div>
                  <div className="rowTopBtn">
                    <Button onClick={() => deriveFu(v.ref, v.name)}>
                      导出
                    </Button>
                  </div>
                  <div className="echartsBox" id={v.domId}></div>
                </div>
              ))}
            </div>
            {/* 表格 */}
            <div className="stores2Main_table">
              <div className="stores2Main_tableTit">藏品报表</div>
              {results ? (
                <Table
                  size="small"
                  dataSource={results}
                  columns={columns}
                  rowKey="groupKey"
                  pagination={false}
                />
              ) : null}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

const MemoStores2 = React.memo(Stores2);

export default MemoStores2;
