import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import { B2FromDataArer } from "./data";
import { useDispatch, useSelector } from "react-redux";
import { B1_APIgetlistArea } from "@/store/action/B1Plan";
import { RootState } from "@/store";
import { B1tableAreaType } from "@/types";
import { Button, Cascader, Table } from "antd";
import { MessageFu } from "@/utils/message";
import dayjs from "dayjs";
import ExportJsonExcel from "js-export-excel";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import { mapDataAll2 } from "../C1User/AddUser/city";
import PlanModal from "./PlanModal";

const tableSelectTemp: B2FromDataArer = {
  // 按机房统计
  siteArr: undefined,
  province: "",
  city: "",
};

const topTypeArr = ["区域", "机房"] as ("机房" | "区域")[];

type Props = {
  topType: "区域" | "机房";
  setTopType: (val: "机房", arrTemp?: string[]) => void;
};

function B1tab1({ topType, setTopType }: Props) {
  // 切换 区域 和 机房
  const setTopTypeFu = useCallback(
    (value: "区域" | "机房", flag?: string) => {
      if (value === "区域") return;

      if (flag) {
        const arrTemp = flag.split("/");

        // 传给父组件
        setTopType("机房", arrTemp);
      } else setTopType("机房");
    },
    [setTopType]
  );

  const dispatch = useDispatch();

  // 筛选和分页
  const [tableSelect, setTableSelect] = useState<B2FromDataArer>({
    ...tableSelectTemp,
  });

  const tableSelectRef = useRef({} as B2FromDataArer);

  useEffect(() => {
    tableSelectRef.current = { ...tableSelect };
  }, [tableSelect]);

  // 点击搜索的 时间戳
  const [timeKey, setTimeKey] = useState(-1);

  // 点击搜索
  const clickSearch = useCallback(() => {
    setTableSelect({ ...tableSelect });
    setTimeout(() => {
      setTimeKey(Date.now());
    }, 50);
  }, [tableSelect]);

  // 发送接口的函数
  const getListFu = useCallback(() => {
    const objTemp: any = {};

    if (tableSelectRef.current.siteArr) {
      const temp = tableSelectRef.current.siteArr;
      objTemp.province = temp[0] || "";
      objTemp.city = temp[1] || "";
      objTemp.region = temp[2] || "";
    }
    dispatch(B1_APIgetlistArea({ ...tableSelectRef.current, ...objTemp }));
  }, [dispatch]);

  useEffect(() => {
    getListFu();
  }, [getListFu, timeKey]);

  // 点击重置
  const resetSelectFu = useCallback(() => {
    setTableSelect({ ...tableSelectTemp });
    setTimeout(() => {
      setTimeKey(Date.now());
    }, 50);
  }, []);

  // 从仓库获取列表
  const B1TableList = useSelector(
    (state: RootState) => state.B1Plan.B1TableListArea
  );

  const columns = useMemo(() => {
    return [
      {
        title: "站址地区",
        render: (item: B1tableAreaType) => item.cityAll || "空",
      },
      {
        title: "机房总数",
        render: (item: B1tableAreaType) => item.pcsRoom || 0,
      },
      {
        title: "上传场景",
        render: (item: B1tableAreaType) => item.pcsScene || 0,
      },
      {
        title: "完成场景计算",
        render: (item: B1tableAreaType) => item.pcsCalculate || 0,
      },
      {
        title: "初审通过",
        render: (item: B1tableAreaType) => item.pcsFirst || 0,
      },
      {
        title: "审核通过",
        render: (item: B1tableAreaType) => item.pcsPass || 0,
      },
      {
        title: "审核驳回",
        render: (item: B1tableAreaType) => item.pcsReject || 0,
      },
      {
        title: "场景推送成功",
        render: (item: B1tableAreaType) => item.pcsPushScene || 0,
      },
      {
        title: "链接推送成功",
        render: (item: B1tableAreaType) => item.pcsPushLink || 0,
      },
      {
        title: "Json推送成功",
        render: (item: B1tableAreaType) => item.pcsPushJson || 0,
      },
      {
        title: "操作",
        render: (item: B1tableAreaType) => (
          <>
            {/* 带完善 */}
            <Button
              size="small"
              type="text"
              disabled={!item.cityAll}
              onClick={() => setModalTitle(item.cityAll)}
            >
              按日期查看
            </Button>
            <Button
              size="small"
              type="text"
              disabled={!item.cityAll}
              onClick={() => setTopTypeFu("机房", item.cityAll)}
            >
              按机房查看
            </Button>
          </>
        ),
      },
    ];
  }, [setTopTypeFu]);

  // 点击导出
  const deriveFu = useCallback(async () => {
    if (B1TableList.total > 30000)
      return MessageFu.warning(
        "只支持导出最多30000条数据。请增加筛选条件，并重新尝试"
      );

    if (B1TableList.list.length === 0)
      return MessageFu.warning("当前搜索条件没有数据!");
    const name = "进度统计" + dayjs(new Date()).format("YYYY-MM-DD HH:mm");

    const option = {
      fileName: name,
      datas: [
        {
          sheetData: B1TableList.list.map((v: B1tableAreaType) => ({
            ...v,
            id: v.cityAll || "（空）",
          })),
          sheetName: name,
          sheetFilter: [
            "id",
            "pcsRoom",
            "pcsScene",
            "pcsCalculate",
            "pcsFirst",
            "pcsPass",
            "pcsReject",
            "pcsPushScene",
            "pcsPushLink",
            "pcsPushJson",
          ],
          sheetHeader: [
            "站址地区",
            "机房总数",
            "上传场景",
            "完成场景计算",
            "初审通过",
            "审核通过",
            "审核驳回",
            "场景推送成功",
            "链接推送成功",
            "Json推送成功",
          ],
          columnWidths: [10, 5, 5, 5, 5, 5, 5, 5, 5, 5],
        },
      ],
    };

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

  // 点击 按日期查看
  const [modalTitle, setModalTitle] = useState("");

  return (
    <>
      <div className="pageTitle">
        进度统计&emsp;
        <ExclamationCircleOutlined rev={undefined} />
        <div>
          当存在重复的机房编码时，请在[场景审核]中删除多余场景码后，重新统计
        </div>
      </div>
      {/* 顶部筛选 */}
      <div className="B1top">
        <div className="B1topSon">
          <div className="B1topRow">
            {topTypeArr.map((v) => (
              <Button
                onClick={() => setTopTypeFu(v)}
                type={v === topType ? "primary" : "default"}
                key={v}
              >
                按{v}统计
              </Button>
            ))}
          </div>

          <div className="B1topRow">
            <span>站址地区：</span>
            <Cascader
              changeOnSelect
              value={tableSelect.siteArr}
              style={{ width: 160 }}
              options={mapDataAll2}
              placeholder="全部"
              onChange={(e) =>
                setTableSelect({
                  ...tableSelect,
                  siteArr: e as string[],
                })
              }
            />
          </div>
        </div>
        <div className="B1topSon B1topSon2">
          <div></div>
          <div>
            <Button onClick={resetSelectFu}>重置</Button>&emsp;
            <Button type="primary" onClick={clickSearch}>
              查询
            </Button>
            &emsp;
            <Button type="primary" onClick={deriveFu}>
              导出表格
            </Button>
          </div>
        </div>
      </div>
      {/* 表格主体 */}
      <div className="tableMain">
        <Table
          scroll={{ y: 578 }}
          dataSource={B1TableList.list}
          columns={columns}
          rowKey="id"
          pagination={false}
        />
      </div>
      {/*  右下角的列表数量 */}
      <div className="tableNumBox">
        共 <span>{B1TableList.total}</span> 条数据
      </div>

      {/* 点击 按日期查看 出来的页面 */}
      {modalTitle ? (
        <PlanModal title={modalTitle} closePageFu={() => setModalTitle("")} />
      ) : null}
    </>
  );
}

const MemoB1tab1 = React.memo(B1tab1);

export default MemoB1tab1;
