import { Tabs } from "antd";
import { FC, useEffect, useMemo, useRef, useState } from "react";
import ReactECharts from "echarts-for-react";
import style from "./index.module.scss";
import { IPerformanceRank } from "@/types";
import { getPerRankApi } from "@/api";
import { SYMBOL_OPTIONS } from "@/pages/Assessment/Index/constants";

export interface ContainerProps {
  currentId: number | null;
}

export const Container: FC<ContainerProps> = ({ currentId }) => {
  const [loading, setLoading] = useState(false);
  const [list, setList] = useState<IPerformanceRank[]>([]);
  const activeTab = useRef("0");

  const warningLine = useMemo(() => {
    if (!list.length || !list[0].jsonWarn) return [];

    const data = JSON.parse(list[0].jsonWarn);
    const temp = [
      {
        ...SYMBOL_OPTIONS.find((i) => i.value === data.symbol),
        silent: true,
        lineStyle: {
          type: "solid",
          color: "red",
        },
        yAxis: data.num,
      },
    ];

    if (data.symbol2)
      temp.push({
        ...SYMBOL_OPTIONS.find((i) => i.value === data.symbol2),
        silent: true,
        lineStyle: {
          type: "solid",
          color: "red",
        },
        yAxis: data.num2,
      });

    return temp;
  }, [list]);

  const getRank = async () => {
    if (!currentId) return;

    try {
      setLoading(true);
      const data = await getPerRankApi(
        currentId,
        activeTab.current === "1" ? "dept" : undefined
      );
      setList(data);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    getRank();
  }, [currentId]);

  return (
    <Tabs
      defaultActiveKey={activeTab.current}
      className={style.tabs}
      items={[
        {
          label: "按时间",
          key: "0",
          children: (
            <ReactECharts
              style={{ height: "100%" }}
              option={{
                tooltip: {
                  trigger: "axis",
                  axisPointer: {
                    type: "shadow",
                  },
                  formatter: (params: any) => {
                    const item = params[0];
                    return `
                      <p>${item.name}</p>
                      <p>${list[item.dataIndex].dateStart} - ${
                      list[item.dataIndex].dateEnd
                    }</p>
                      <p>${item.seriesName}：${item.value}</p>
                    `;
                  },
                },
                calculable: true,
                xAxis: [
                  {
                    type: "category",
                    data: list.map((i) => i.assessName),
                  },
                ],
                yAxis: [
                  {
                    type: "value",
                    name: "评定得分",
                  },
                ],
                dataZoom: [
                  {
                    show: true,
                    start: 0,
                  },
                  {
                    type: "inside",
                    start: 0,
                  },
                  {
                    show: true,
                    yAxisIndex: 0,
                    filterMode: "empty",
                    width: 30,
                    height: "80%",
                    showDataShadow: false,
                    left: "93%",
                  },
                ],
                series: [
                  {
                    name: "评定得分",
                    type: "bar",
                    data: list.map((i) => i.opinionScore || 0),
                    markLine: {
                      symbol: "none",
                      silent: true,
                      label: {
                        position: "end",
                        color: "red",
                        fontSize: 14,
                        formatter: (params: any) => {
                          return `预警值${params.data.label}${params.data.value}`;
                        },
                      },
                      data: warningLine,
                    },
                  },
                ],
              }}
            />
          ),
        },
        {
          label: "按部门",
          key: "1",
          children: (
            <ReactECharts
              style={{ height: "100%" }}
              option={{
                tooltip: {
                  trigger: "axis",
                  axisPointer: {
                    type: "shadow",
                  },
                  formatter: (params: any) => {
                    const item = params[0];
                    return `
                      <p>${list[item.dataIndex].assessName}</p>
                      <p>${list[item.dataIndex].dateStart} - ${
                      list[item.dataIndex].dateEnd
                    }</p>
                      <p>${item.seriesName}：${item.value}</p>
                    `;
                  },
                },
                legend: {},
                grid: {
                  left: "3%",
                  right: "4%",
                  bottom: "3%",
                  containLabel: true,
                },
                xAxis: {
                  type: "value",
                  boundaryGap: [0, 0.01],
                },
                yAxis: {
                  type: "category",
                  data: list.map(
                    (i) => `
                      ${i.assessName}
                      ${i.deptName}
                    `
                  ),
                },
                series: [
                  {
                    name: "评定得分",
                    type: "bar",
                    data: list.map((i) => i.opinionScore || 0),
                    markLine: {
                      symbol: "none",
                      silent: true,
                      label: {
                        position: "end",
                        color: "red",
                        fontSize: 14,
                        formatter: (params: any) => {
                          return `预警值${params.data.label}${params.data.value}`;
                        },
                      },
                      data: warningLine.map((i) => {
                        const { yAxis, ...rest } = i;
                        return {
                          xAxis: yAxis,
                          ...rest,
                        };
                      }),
                    },
                  },
                ],
              }}
            />
          ),
        },
      ]}
      onChange={(v) => {
        activeTab.current = v;
        getRank();
      }}
    />
  );
};
