import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
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 { RootState } from "@/store";
import { B1tableType } from "@/types";
import ExportJsonExcel from "js-export-excel";
import { MessageFu } from "@/utils/message";
import dayjs from "dayjs";
import { mapDataAll1 } from "../C1User/AddUser/city";
import { B1_APIgetlist, B1_APIgetlistAll } from "@/store/action/B1Plan";
import { forwardRef, useImperativeHandle } from "react";

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

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

type Props = {
  topType: "区域" | "机房";
  setTopType: (val: "区域") => void;
  ref: any;
};

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

      // 传给父组件
      setTopType("区域");
    },
    [setTopType]
  );

  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 = {};

    const temp = tableSelectRef.current.siteArr || [];
    objTemp.province = temp[0] || "";
    objTemp.city = temp[1] || "";
    objTemp.region = temp[2] || "";

    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) => state.B1Plan.B1TableList
  );

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

  // 给父组件调用，设置站址地区
  const fatherFu = useCallback((obj: any) => {
    // 把2个输入框和时间选择器清空
    setInputKey(Date.now());

    setTableSelect({ ...tableSelectTemp, ...obj });
    setTimeout(() => {
      setTimeKey(Date.now());
    }, 50);
  }, []);

  // 可以让父组件调用子组件的方法
  useImperativeHandle(ref, () => ({
    fatherFu,
  }));

  const columns = useMemo(() => {
    return [
      {
        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) || "（空）",
      },
    ];
  }, []);
  // 点击导出
  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 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.length, B1TableList.total]);

  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>
            <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={mapDataAll1}
              placeholder="全部"
              onChange={(e) =>
                setTableSelect({
                  ...tableSelect,
                  siteArr: e as string[],
                })
              }
            />
          </div>
          <div className="B1topRow">
            <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">
              <span>场景审核：</span>
              <Select
                disabled={!tableSelect.isUploadScene}
                style={{ width: 200 }}
                value={tableSelect.auditStatus}
                onChange={(e) =>
                  setTableSelect({ ...tableSelect, auditStatus: e })
                }
                options={B1options1}
              />
            </div>
            <div className="B1topRow">
              <span>场景推送：</span>
              <Select
                disabled={!tableSelect.isUploadScene}
                style={{ width: 200 }}
                value={tableSelect.pushStatus}
                onChange={(e) =>
                  setTableSelect({ ...tableSelect, pushStatus: e })
                }
                options={B1options2}
              />
            </div>
            <div className="B1topRow">
              <span>Json推送：</span>
              <Select
                disabled={!tableSelect.isUploadScene}
                style={{ width: 200 }}
                value={tableSelect.jsonStatus}
                onChange={(e) =>
                  setTableSelect({ ...tableSelect, jsonStatus: e })
                }
                options={B1options3}
              />
            </div>
            <div className="B1topRowCheck">
              <Checkbox
                checked={tableSelect.isUploadScene === 0}
                onChange={(e) => {
                  setTableSelect({
                    ...tableSelect,
                    isUploadScene: e.target.checked ? 0 : 1,
                    // 把 场景审核 场景推送 Json推送变成初始值
                    auditStatus: "",
                    pushStatus: "",
                    jsonStatus: "",
                  });
                }}
              >
                仅查看未上传的机房
              </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="idKey"
          pagination={{
            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>
    </>
  );
}

export default forwardRef(B1tab1);
