import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import styles from "./index.module.scss";
import {
  Button,
  Cascader,
  Checkbox,
  Input,
  Select,
  Table,
  Tooltip,
} from "antd";
import {
  B1options1,
  B1options1Obj,
  B1options2,
  B1options2Obj,
  B1options3,
  B2FromDataType,
} from "./data";
import {
  ExclamationCircleOutlined,
  QuestionCircleOutlined,
} from "@ant-design/icons";
import { useDispatch, useSelector } from "react-redux";
import {
  B1_APIgetlist,
  B1_APIgetlistAll,
  B1_APIgetlistArea,
} from "@/store/action/B1Plan";
import { RootState } from "@/store";
import { B1tableAreaType, B1tableType } from "@/types";
import ExportJsonExcel from "js-export-excel";
import { MessageFu } from "@/utils/message";
import dayjs from "dayjs";
import { mapDataAll1, mapDataAll2 } from "../C1User/AddUser/city";

const tableSelectTemp: B2FromDataType = {
  // 按机房统计
  siteArr: undefined,
  isUploadScene: 1,
  province: "",
  city: "",
  region: "",
  searchKey: "",
  pmUser: "",
  auditStatus: "",
  pushStatus: "",
  jsonStatus: "",
  pageSize: 10,
  pageNum: 1,
};

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

function B1Plan() {
  const [topTyep, setTopType] = useState<"区域" | "机房">("区域");
  const topTyepRef = useRef<"区域" | "机房">("区域");

  // 切换 区域 和 机房
  const setTopTypeFu = useCallback((value: "区域" | "机房", falg?: string) => {
    if (value === topTyepRef.current) return;
    setTopType(value);
    setInputKey(Date.now());

    const objTemp: any = {};
    if (falg) {
      const arrTemp = falg.split("/");
      objTemp.siteArr = arrTemp;
      objTemp.province = arrTemp[0] || "";
      objTemp.city = arrTemp[1 || ""];
      objTemp.region = arrTemp[2] || "";
    }

    setTableSelect({ ...tableSelectTemp, ...objTemp });

    topTyepRef.current = value;
    setTimeout(() => {
      setTimeKey(Date.now());
    }, 50);
  }, []);

  const dispatch = useDispatch();

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

  const tableSelectRef = useRef({} as B2FromDataType);

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

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

  // 点击搜索
  const clickSearch = useCallback(() => {
    setTableSelect({ ...tableSelect, pageNum: 1 });
    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] || "";
    }

    if (topTyepRef.current === "区域") {
      dispatch(B1_APIgetlistArea({ ...tableSelectRef.current, ...objTemp }));
    } else {
      const obj = {
        ...tableSelectRef.current,
        ...objTemp,
      };
      dispatch(B1_APIgetlist(obj));
    }
  }, [dispatch]);

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

  // 输入框的改变
  const txtChangeFu = useCallback(
    (txt: string, key: "pmUser" | "searchKey") => {
      setTableSelect({ ...tableSelect, [key]: txt });
    },
    [tableSelect]
  );

  // 点击重置
  const [inputKey, setInputKey] = useState(1);
  const resetSelectFu = useCallback(() => {
    // 把2个输入框和时间选择器清空
    setInputKey(Date.now());
    setTableSelect({ ...tableSelectTemp });
    setTimeout(() => {
      setTimeKey(Date.now());
    }, 50);
  }, []);

  // 从仓库获取列表
  const B1TableList: any = useSelector((state: RootState) => {
    return topTyep === "区域"
      ? state.B1Plan.B1TableListArea
      : state.B1Plan.B1TableList;
  });

  // 页码变化
  const paginationChange = useCallback(
    () => (pageNum: number, pageSize: number) => {
      setTableSelect({ ...tableSelect, pageNum, pageSize });
      setTimeout(() => {
        setTimeKey(Date.now());
      }, 50);
    },
    [tableSelect]
  );

  // 按 区域统计 点击 表格的 查看明细
  const [areaLook, setAreaLook] = useState({
    type: "",
  });

  const columns = useMemo(() => {
    return topTyep === "区域"
      ? [
          {
            title: "站址地区",
            render: (item: B1tableAreaType) => item.id || "空",
          },
          {
            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">
                  按日期查看
                </Button>
                <Button
                  size="small"
                  type="text"
                  disabled={!item.id}
                  onClick={() => setTopTypeFu("机房", item.id)}
                >
                  按机房查看
                </Button>
              </>
            ),
          },
        ]
      : [
          {
            title: "站址名称",
            render: (item: B1tableType) => item.name || "（空）",
          },
          {
            title: "站址编号",
            render: (item: B1tableType) => item.siteNum || "（空）",
          },
          {
            title: "站址地区",
            render: (item: B1tableType) =>
              !item.province && !item.city && !item.region
                ? "（空）"
                : `${item.province}-${item.city}-${item.region}`,
          },
          {
            title: "机房编码",
            dataIndex: "roomNum",
          },
          {
            title: "项目经理",
            render: (item: B1tableType) => item.pmName || "（空）",
          },
          {
            title: "场景码",
            render: (item: B1tableType) => item.sceneCode || "（空）",
          },
          {
            title: "场景审核状态",
            render: (item: B1tableType) =>
              Reflect.get(B1options1Obj, item.auditStatus) || "（空）",
          },
          {
            title: "场景推送状态",
            render: (item: B1tableType) => (
              <>
                {Reflect.get(B1options2Obj, item.pushStatus) || "（空）"}
                <span style={{ cursor: "pointer" }} hidden={!item.pushDesc}>
                  <Tooltip title={item.pushDesc}>
                    &nbsp;
                    <QuestionCircleOutlined rev={undefined} />
                  </Tooltip>
                </span>
              </>
            ),
          },
          {
            title: "Json推送状态",
            render: (item: B1tableType) =>
              Reflect.get(B1options2Obj, item.jsonStatus) || "（空）",
          },
        ];
  }, [setTopTypeFu, topTyep]);
  // 点击导出
  const deriveFu = useCallback(async () => {
    if (B1TableList.list.length === 0)
      return MessageFu.warning("当前搜索条件没有数据!");
    const name = "进度统计" + dayjs(new Date()).format("YYYY-MM-DD HH:mm");

    if (topTyep === "区域") {
      const option = {
        fileName: name,
        datas: [
          {
            sheetData: B1TableList.list.map((v: B1tableAreaType) => ({
              ...v,
              id: v.id || "（空）",
            })),
            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(); //保存
    } else {
      const objTemp: any = {};

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

      const res = await B1_APIgetlistAll({
        ...tableSelectRef.current,
        ...objTemp,
        pageNum: 1,
        pageSize: 99999,
      });

      if (res.code === 0) {
        if (res.data.records.length <= 0)
          return MessageFu.warning("当前搜索条件没有数据!");

        const option = {
          fileName: name,
          datas: [
            {
              sheetData: res.data.records.map((v: B1tableType) => ({
                name: v.name || "（空）",
                siteNum: v.siteNum || "（空）",
                myCity:
                  !v.province && !v.city && !v.region
                    ? "（空）"
                    : `${v.province}-${v.city}-${v.region}`,
                roomNum: v.roomNum,
                pmName: v.pmName || "（空）",
                sceneCode: v.sceneCode || "（空）",
                auditStatus:
                  Reflect.get(B1options1Obj, v.auditStatus) || "（空）",
                pushStatus:
                  Reflect.get(B1options2Obj, v.pushStatus) || "（空）",
                jsonStatus:
                  Reflect.get(B1options2Obj, v.jsonStatus) || "（空）",
              })),
              sheetName: name,
              sheetFilter: [
                "name",
                "siteNum",
                "myCity",
                "roomNum",
                "pmName",
                "sceneCode",
                "auditStatus",
                "pushStatus",
                "jsonStatus",
              ],
              sheetHeader: [
                "站址名称",
                "站址编号",
                "站址地区",
                "机房编码",
                "项目经理",
                "场景码",
                "场景审核状态",
                "场景推送状态",
                "Json推送状态",
              ],
              columnWidths: [10, 10, 10, 10, 10, 10, 10, 10, 10],
            },
          ],
        };

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

  return (
    <div className={styles.B1Plan}>
      <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 === topTyep ? "primary" : "default"}
                key={v}
              >
                按{v}统计
              </Button>
            ))}
          </div>
          <div className="B1topRow" hidden={topTyep === "区域"}>
            <span>搜索项：</span>
            <Input
              key={inputKey}
              maxLength={24}
              style={{ width: 323 }}
              placeholder="请输入站址名称/站置编号/机房编码,最多24字"
              allowClear
              onChange={(e) => txtChangeFu(e.target.value, "searchKey")}
            />
          </div>
          <div className="B1topRow">
            <span>站址地区：</span>
            <Cascader
              changeOnSelect
              value={tableSelect.siteArr}
              style={{ width: 160 }}
              options={topTyep === "区域" ? mapDataAll2 : mapDataAll1}
              placeholder="全部"
              onChange={(e) =>
                setTableSelect({
                  ...tableSelect,
                  siteArr: e as string[],
                })
              }
            />
          </div>
          <div className="B1topRow" hidden={topTyep === "区域"}>
            <span>项目经理：</span>
            <Input
              key={inputKey}
              maxLength={10}
              style={{ width: 200 }}
              placeholder="请输入姓名,最多10字"
              allowClear
              onChange={(e) => txtChangeFu(e.target.value, "pmUser")}
            />
          </div>
        </div>
        <div className="B1topSon B1topSon2">
          <div>
            <div className="B1topRow" hidden={topTyep === "区域"}>
              <span>场景审核：</span>
              <Select
                style={{ width: 200 }}
                value={tableSelect.auditStatus}
                onChange={(e) =>
                  setTableSelect({ ...tableSelect, auditStatus: e })
                }
                options={B1options1}
              />
            </div>
            <div className="B1topRow" hidden={topTyep === "区域"}>
              <span>场景推送：</span>
              <Select
                style={{ width: 200 }}
                value={tableSelect.pushStatus}
                onChange={(e) =>
                  setTableSelect({ ...tableSelect, pushStatus: e })
                }
                options={B1options2}
              />
            </div>
            <div className="B1topRow" hidden={topTyep === "区域"}>
              <span>Json推送：</span>
              <Select
                style={{ width: 200 }}
                value={tableSelect.jsonStatus}
                onChange={(e) =>
                  setTableSelect({ ...tableSelect, jsonStatus: e })
                }
                options={B1options3}
              />
            </div>
            <div className="B1topRowCheck" hidden={topTyep === "区域"}>
              <Checkbox
                checked={tableSelect.isUploadScene === 0}
                onChange={(e) => {
                  setInputKey(Date.now());
                  setTableSelect({
                    ...tableSelect,
                    isUploadScene: e.target.checked ? 0 : 1,
                  });
                }}
              >
                仅查看未上传的机房
              </Checkbox>
            </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={
            topTyep === "区域"
              ? false
              : {
                  showQuickJumper: true,
                  position: ["bottomCenter"],
                  showSizeChanger: true,
                  current: tableSelect.pageNum,
                  pageSize: tableSelect.pageSize,
                  total: B1TableList.total,
                  onChange: paginationChange(),
                }
          }
        />
      </div>
      {/*  右下角的列表数量 */}
      <div className="tableNumBox">
        共 <span>{B1TableList.total}</span> 条数据
      </div>
    </div>
  );
}

const MemoB1Plan = React.memo(B1Plan);

export default MemoB1Plan;
