import { getTokenInfo } from "@/utils/storage";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import styles from "./index.module.scss";
import dayjs from "dayjs";
import { Button, message } from "antd";
import classNames from "classnames";
import * as echarts from "echarts/core";
import { TooltipComponent, GridComponent } from "echarts/components";
import { BarChart } from "echarts/charts";
import { CanvasRenderer } from "echarts/renderers";
import history from "@/utils/history";
import { getStores2API1 } from "@/store/action/stores1";
import { getHomeNumsAPI } from "@/store/action/login";
import { useSelector } from "react-redux";
import { RootState } from "@/store";
import { MessageFu } from "@/utils/message";

echarts.use([TooltipComponent, GridComponent, BarChart, CanvasRenderer]);

export default function Home() {
  // 顶部右侧数据
  const tabListTemp = useMemo(() => {
    return [
      { id: 1, done: false, path: "/object", name: "藏品登记" },
      { id: 2, done: false, path: "/object/2", name: "藏品总账" },
      { id: 3, done: false, path: "/object/3", name: "入库管理" },
      { id: 4, done: false, path: "/object/4", name: "出库管理" },
      { id: 5, done: false, path: "/object/6", name: "藏品注销" },
    ];
  }, []);
  // 右下方的数据
  const tempDone = useMemo(() => {
    return [
      { id: 1, done: false, path: "/object", num: 0, name: "藏品登记" },
      { id: 2, done: false, path: "/object/3", num: 0, name: "入库管理" },
      { id: 3, done: false, path: "/object/4", num: 0, name: "出库管理" },
      { id: 4, done: false, path: "/object/5", num: 0, name: "藏品修改" },
      { id: 5, done: false, path: "/object/6", num: 0, name: "藏品注销" },
      { id: 6, done: false, path: "/stores/3", num: 0, name: "藏品移库" },
    ];
  }, []);

  const [tabList, setTabList] = useState(tabListTemp);
  const powerInfo = useSelector(
    (state: RootState) => state.loginStore.authPageArr
  );

  useEffect(() => {
    powerInfo.forEach((v: any) => {
      if (v.id === 100) tabListTemp[0].done = tempDone[0].done = true;
      if (v.id === 200) tabListTemp[1].done = true;
      if (v.id === 300) tabListTemp[2].done = tempDone[1].done = true;
      if (v.id === 400) tabListTemp[3].done = tempDone[2].done = true;
      if (v.id === 500) tempDone[3].done = true;
      if (v.id === 600) tabListTemp[4].done = tempDone[4].done = true;
      if (v.id === 800) tempDone[5].done = true;
    });

    window.setTimeout(() => {
      setTabList(tabListTemp);
    }, 100);
  }, [powerInfo, tabListTemp, tempDone]);

  // 实时时间
  const [nowTime, setNowTime] = useState(
    dayjs(Date.now()).format("YYYY年MM月DD HH:mm")
  );

  // 点击头部右侧和下面右侧
  const toPageFu = useCallback((path: string, flag: boolean) => {
    if (flag) return MessageFu.warning("没有该模块权限!");
    history.push(path);
  }, []);

  const timeRef = useRef(-1);
  useEffect(() => {
    timeRef.current = window.setInterval(() => {
      setNowTime(() => {
        return dayjs(Date.now()).format("YYYY年MM月DD HH:mm");
      });
    }, 1000);
    return () => {
      clearInterval(timeRef.current);
    };
  }, []);

  const userInfo = useMemo(() => {
    return getTokenInfo().user;
  }, []);

  // -----------图表
  const echartsFu = useCallback(async () => {
    const res = await getStores2API1();
    let list = res.data;

    if (list && list.length && list.length > 7) {
      list = list.slice(0, 7);
    } else {
      const num = 7 - list.length;
      for (let i = 0; i < num; i++) {
        if (i % 2 !== 0) list.unshift({ groupKey: "", count: null });
        else list.push({ groupKey: "", count: null });
      }
    }
    const chartDom: any = document.querySelector(".chart");
    const myChart = echarts.init(chartDom);
    const option = {
      color: ["#9F1927"],
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "shadow",
        },
      },
      grid: {
        left: "3%",
        right: "4%",
        bottom: "3%",
        containLabel: true,
      },
      xAxis: [
        {
          type: "category",
          data: list.map((v: any) => v.groupKey),
          axisTick: {
            show: false,
            alignWithLabel: false,
          },
          axisLabel: {
            interval: 0, //强制文字产生间隔
            textStyle: {
              color: "#000", //坐标值得具体的颜色
              fontSize: 12,
            },
          },
          axisLine: {
            //Y轴坐标轴
            show: true,
            // 坐标的颜色和宽度
            lineStyle: {
              width: 2,
              color: "#9F1927",
            },
          },
        },
      ],
      yAxis: [
        {
          type: "value",
          axisLabel: {
            textStyle: {
              color: "#000", //坐标值得具体的颜色
            },
          },
          axisLine: {
            //Y轴坐标轴
            show: true,
            lineStyle: {
              width: 2,
              color: "#9F1927",
            },
          },
          // 隐藏背景坐标线段
          splitLine: {
            show: false,
          },
        },
      ],
      series: [
        {
          name: "",
          type: "bar",
          barMaxwidth: "50%",
          data: list.map((v: any) => v.count),
          itemStyle: {
            normal: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: "rgba(159, 25, 39, .5)" }, //渐变头部色
                { offset: 1, color: "rgba(159, 25, 39, 1)" },
              ]),

              barBorderRadius: 2,
              label: {
                show: true, //开启显示
                position: "top", //在上方显示
                textStyle: {
                  //数值样式
                  color: "#9F1927",
                  fontSize: 16,
                },
              },
            },
          },
        },
      ],
    };
    option && myChart.setOption(option);
  }, []);

  // 代办提醒
  const [doneList, setDoneList] = useState(tempDone);

  const doneNumsAPIFu = useCallback(async () => {
    const res = await getHomeNumsAPI();
    const data = [...tempDone];
    res.data.forEach((v: any) => {
      if (v.groupKey === "register") data[0].num = v.count;
      else if (v.groupKey === "in") data[1].num = v.count;
      else if (v.groupKey === "out") data[2].num = v.count;
      else if (v.groupKey === "edit") data[3].num = v.count;
      else if (v.groupKey === "cancel") data[4].num = v.count;
      else if (v.groupKey === "move") data[5].num = v.count;
    });
    setDoneList(data);
  }, [tempDone]);

  useEffect(() => {
    echartsFu();
    doneNumsAPIFu();
  }, [doneNumsAPIFu, echartsFu]);

  return (
    <div className={styles.Home}>
      <div className="homeMain">
        {/* 顶部页面 */}
        <div className="title">
          <div className="titleL">
            <h3>
              欢迎 {userInfo.realName} 进入
              <br />
              <br />
              乐山大佛博物馆馆藏管理系统！
            </h3>
            <p>{nowTime}</p>
          </div>
          <div className="titleR">
            {tabList.map((v, i) => (
              <div
                onClick={() => toPageFu(v.path, !v.done)}
                className={classNames("row", !v.done ? "noAuth" : "")}
                key={v.id}
              >
                <div className={`bac${v.id}`}></div>
                <p>{v.name}</p>
              </div>
            ))}
          </div>
        </div>
        {/* 下面数据 */}
        <div className="flooBox">
          <div className="flooBoxL">
            <div className="flooTit">
              <div>藏馆统计</div>
              <Button onClick={() => history.push("/stores/2")}>
                查看更多
              </Button>
            </div>
            {/* 图表 */}
            <div className="chartBox">
              <div className="chartTit">（件）</div>
              <div className="chart"></div>
            </div>
          </div>
          <div className="flooBoxR">
            <div className="flooTit">
              <div>审核提醒</div>
            </div>
            <div className="doneBox">
              {doneList.map((v, i) => (
                <div
                  onClick={() => toPageFu(v.path, !v.done)}
                  className={classNames(
                    "doneRow",
                    i >= 4 ? "noneRow" : "",
                    !v.done ? "noAuth" : ""
                  )}
                  key={v.id}
                >
                  <div className="doneRow_tit">{v.name}</div>
                  <div className="doneRow_txt">
                    共有&emsp;<span>{v.num}</span>&emsp;待审核事项
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
