import React, { useCallback, useEffect, useRef, useState } from "react";
import styles from "./index.module.scss";
import * as echarts from "echarts/core";
import { GridComponent } from "echarts/components";
import { LineChart } from "echarts/charts";
import { UniversalTransition } from "echarts/features";
import { CanvasRenderer } from "echarts/renderers";
import { TooltipComponent, LegendComponent } from "echarts/components";

import { PieChart } from "echarts/charts";
import { LabelLayout } from "echarts/features";

import { A6_APIgetLikeList, A6_APIgetNumList } from "@/store/action/A6hot";
import { Button, Empty } from "antd";
import dayjs from "dayjs";
import ExportJsonExcel from "js-export-excel";

echarts.use([
  GridComponent,
  LineChart,
  CanvasRenderer,
  UniversalTransition,
  TooltipComponent,
  LegendComponent,
  PieChart,
  LabelLayout,
]);

type dataType = { name: string; value: string | number }[];

function A6hot() {
  const echartsRef1 = useRef(null);
  const echartsRef2 = useRef(null);

  // 折线图
  const echartsFu1 = useCallback((dom: HTMLDivElement, data: dataType) => {
    const myChart1 = echarts.getInstanceByDom(dom) || echarts.init(dom);
    const option1 = {
      grid: {
        left: "15", //距左边边框的距离
        right: "0%", //距右边边框的距离
        bottom: "10", //距下面边框的距离
        top: "15", //距上面边框的距离
        containLabel: true,
      },

      xAxis: {
        type: "category",
        data: data.map((v) => v.name),
        axisLine: {
          show: false, //隐藏X轴
        },
        axisTick: {
          show: false, //隐藏刻度线
        },
        axisLabel: {
          // show: false, //隐藏X轴文字
        },
      },
      yAxis: {
        type: "value",
      },
      series: [
        {
          data: data.map((v) => v.value),
          type: "line",
          // 平滑曲线
          // smooth: true
        },
      ],
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "cross",
          label: {
            backgroundColor: "#6a7985",
          },
        },
        // formatter: "{a} <br/>{b} : {c}"
      },
    };
    option1 && myChart1.setOption(option1);
  }, []);

  const deriveDataRef1 = useRef<any>([]);

  // 左边-云展-馆藏 折线图是否有数据(没有数据为true)
  const [leftFlag, setLeftFlag] = useState([false, false]);

  // 获取左边数据
  const getListFu1 = useCallback(async () => {
    let leftFlagTemp = [false, false];

    const res1 = await A6_APIgetLikeList("exhibition");
    const obj1 = {};
    if (res1.code === 0) {
      leftFlagTemp[0] = res1.data.length <= 0;

      const data1: dataType = [];
      res1.data.forEach((v: any) => {
        Reflect.set(obj1, v.groupKey, v.pcsStar);

        data1.push({
          name: v.groupKey,
          value: v.pcsStar,
        });
      });

      echartsFu1(echartsRef1.current!, data1);
    }

    const res2 = await A6_APIgetLikeList("goods");
    const obj2 = {};
    if (res2.code === 0) {
      leftFlagTemp[1] = res2.data.length <= 0;

      setLeftFlag(leftFlagTemp);

      const data2: dataType = [];
      res2.data.forEach((v: any) => {
        Reflect.set(obj2, v.groupKey, v.pcsStar);

        data2.push({
          name: v.groupKey,
          value: v.pcsStar,
        });
      });
      echartsFu1(echartsRef2.current!, data2);
    }

    const tempArr: any = [];

    const objMax =
      Object.keys(obj1).length >= Object.keys(obj2).length ? obj1 : obj2;

    for (const k in objMax) {
      tempArr.push({
        name: k,
        num1: Reflect.get(obj1, k) || "",
        num2: Reflect.get(obj2, k) || "",
      });
    }
    tempArr.push({ name: "", num1: "", num2: "" });
    tempArr.push({ name: "云展名称", num1: "点赞数", num2: "" });

    deriveDataRef1.current = tempArr;
  }, [echartsFu1]);

  const [rightData1, setRightData1] = useState<{ pcs: number; name: string }[]>(
    []
  );

  const [rightData2, setRightData2] = useState<{ pcs: number; name: string }[]>(
    []
  );

  const [isOk, setIsOk] = useState(false);

  // 获取右边数据
  const getListFu2 = useCallback(async () => {
    const res1 = await A6_APIgetNumList("exhibition");
    if (res1.code === 0) {
      setRightData1(res1.data);

      const res2 = await A6_APIgetNumList("goods");
      if (res2.code === 0) {
        setRightData2(res2.data);

        setIsOk(true);
      }
    }
  }, []);

  useEffect(() => {
    getListFu1();
    getListFu2();
  }, [getListFu1, getListFu2]);

  // 点击导出
  const deriveFu = useCallback(async () => {
    const name = "热度统计" + dayjs(new Date()).format("YYYY-MM-DD HH:mm");

    const option = {
      fileName: name,
      datas: [
        {
          sheetData: [
            ...deriveDataRef1.current,
            ...rightData1.map((v) => ({ name: v.name, num1: v.pcs, num2: "" })),
            { name: "", num1: "", num2: "" },
            { name: "馆藏名称", num1: "点赞数", num2: "" },
            ...rightData2.map((v) => ({ name: v.name, num1: v.pcs, num2: "" })),
          ],
          sheetName: name,
          sheetFilter: ["name", "num1", "num2"],
          sheetHeader: ["日期", "云展点赞数", "馆藏点赞数"],
          columnWidths: [10, 10, 10],
        },
      ],
    };

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

  return (
    <div className={styles.A6hot}>
      <div className="pageTitle">热度统计</div>
      <div className="A6box1">
        <div className="A6box1_1">
          <div className="A6tit">云展点赞趋势</div>
          <div className="echBox" ref={echartsRef1}></div>
          {leftFlag[0] && isOk ? (
            <div className="echBoxNone">暂无数据</div>
          ) : null}
        </div>
        <div className="A6box1_1">
          <div className="A6tit">馆藏点赞趋势</div>
          <div className="echBox" ref={echartsRef2}></div>
          {leftFlag[1] && isOk ? (
            <div className="echBoxNone">暂无数据</div>
          ) : null}
        </div>
      </div>
      <div className="A6box2">
        <div className="A6box2_1">
          <div className="A6tit">云展点赞排行</div>
          <div className="A6RowBox">
            <div className="A6RowBox1">
              <div>名称</div>
              <div>点赞</div>
            </div>
            {rightData1.length <= 0 && isOk ? (
              <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
            ) : (
              <>
                {rightData1.map((v) => (
                  <div className="A6RowBox1" key={v.name + v.pcs}>
                    <div title={v.name}>{v.name}</div>
                    <div>{v.pcs}</div>
                  </div>
                ))}
              </>
            )}
          </div>
        </div>
        <div className="A6box2_1">
          <div className="A6tit">馆藏点赞排行</div>
          <div className="A6RowBox">
            <div className="A6RowBox1">
              <div>名称</div>
              <div>点赞</div>
            </div>
            {rightData2.length <= 0 && isOk ? (
              <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
            ) : (
              <>
                {rightData2.map((v) => (
                  <div className="A6RowBox1" key={v.name + v.pcs}>
                    <div title={v.name}>{v.name}</div>
                    <div>{v.pcs}</div>
                  </div>
                ))}
              </>
            )}
          </div>
        </div>
      </div>

      <div className="A6DeriveBox">
        <Button type="primary" onClick={deriveFu}>
          导出
        </Button>
      </div>
    </div>
  );
}

const MemoA6hot = React.memo(A6hot);

export default MemoA6hot;
