import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import styles from "./index.module.scss";
import { Button, Cascader, Input, Popconfirm, Select, Table } from "antd";
import { useDispatch, useSelector } from "react-redux";
import { A2FromDataType, options1 } from "./data";
import {
  A2_APIgetCity,
  A2_APIgetlist,
  A2_APIgetlistDerive,
  A2_APIremoves,
} from "@/store/action/A2Psychz";
import { RootState } from "@/store";
import { A2tableType } from "@/types";
import { MessageFu } from "@/utils/message";
import { A1addType } from "../A1Camera/data";
import AddPsychz from "./AddPsychz";
import dayjs from "dayjs";
import ExportJsonExcel from "js-export-excel";

function A2Psychz() {
  // 站址地区的数据-下拉框

  const [optionsCity, setOptionsCity] = useState<any>([]);

  const getCityFu = useCallback(async () => {
    const res = await A2_APIgetCity();
    if (res.code === 0) {
      const obj = res.data;

      const arr = [];

      for (const k in obj) {
        const temp1: any = {
          value: k,
          label: k,
          children: [],
        };

        const children1Obj = Reflect.get(obj, k);

        for (const k2 in children1Obj) {
          const children2Arr = Reflect.get(children1Obj, k2);

          const objTemp = {
            value: k2,
            label: k2,
            children: children2Arr.map((v2: any) => ({
              value: v2.region,
              label: v2.region,
            })),
          };
          temp1.children.push(objTemp);
        }

        arr.push(temp1);
      }

      setOptionsCity(arr);
      // console.log(123, res);
    }
  }, []);

  useEffect(() => {
    getCityFu();
  }, [getCityFu]);

  const dispatch = useDispatch();

  // 筛选和分页
  const [tableSelect, setTableSelect] = useState<A2FromDataType>({
    siteArr: undefined,
    province: "",
    city: "",
    region: "",
    searchKey: "",
    pmUser: "",
    typeIn: "",
    pageSize: 10,
    pageNum: 1,
  });

  const tableSelectRef = useRef({} as A2FromDataType);

  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] || "";
    }

    const obj = {
      ...tableSelectRef.current,
      ...objTemp,
    };
    dispatch(A2_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({
      siteArr: undefined,
      province: "",
      city: "",
      region: "",
      searchKey: "",
      pmUser: "",
      typeIn: "",
      pageSize: 10,
      pageNum: 1,
    });

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

  // 从仓库获取列表
  const A2TableList = useSelector(
    (state: RootState) => state.A2Psychz.A2TableList
  );
  // 页码变化
  const paginationChange = useCallback(
    () => (pageNum: number, pageSize: number) => {
      setTableSelect({ ...tableSelect, pageNum, pageSize });
      setTimeout(() => {
        setTimeKey(Date.now());
      }, 50);
    },
    [tableSelect]
  );

  // 点击删除
  const delByIdFu = useCallback(
    async (id: number) => {
      const res = await A2_APIremoves(id);
      if (res.code === 0) {
        MessageFu.success("删除成功!");
        getListFu();
        getCityFu();
      }
    },
    [getCityFu, getListFu]
  );

  const columns = useMemo(() => {
    return [
      {
        title: "站址地区",
        render: (item: A2tableType) =>
          !item.province && !item.city && !item.region
            ? "（空）"
            : `${item.province}-${item.city}-${item.region}`,
      },
      {
        title: "详细地址",
        render: (item: A2tableType) =>
          item.address ? (
            item.address.length >= 25 ? (
              <span style={{ cursor: "pointer" }} title={item.address}>
                {item.address.substring(0, 25) + "..."}
              </span>
            ) : (
              item.address
            )
          ) : (
            "（空）"
          ),
      },
      {
        title: "站址名称",
        render: (item: A2tableType) => item.name || "（空）",
      },
      {
        title: "站址编号",
        render: (item: A2tableType) => item.siteNum || "（空）",
      },
      {
        title: "机房编码",
        dataIndex: "roomNum",
      },
      {
        title: "项目经理",
        render: (item: A2tableType) => {
          if (item.pmUserId === 1) return "管理员";
          else {
            return item.pmName || "（空）";
          }
        },
      },
      {
        title: "最近编辑时间",
        dataIndex: "updateTime",
      },

      {
        title: "录入方式",
        render: (item: A2tableType) =>
          item.typeIn === "pc"
            ? "系统"
            : item.typeIn === "app-scan"
            ? "移动端扫码"
            : "移动端手工",
      },
      {
        title: "操作",
        render: (item: A2tableType) => (
          <>
            <Button
              size="small"
              type="text"
              onClick={() => setOpenInfo({ id: item.id, txt: "编辑" })}
            >
              编辑
            </Button>
            <Popconfirm
              title="删除后无法恢复，是否删除?"
              okText="删除"
              cancelText="取消"
              onConfirm={() => delByIdFu(item.id)}
              okButtonProps={{ loading: false }}
            >
              <Button size="small" type="text" danger>
                删除
              </Button>
            </Popconfirm>
          </>
        ),
      },
    ];
  }, [delByIdFu]);

  const [openInfo, setOpenInfo] = useState<A1addType>({ id: 0, txt: "" });

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

    if (A2TableList.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 A2_APIgetlistDerive({
      ...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: A2tableType) => ({
              ...v,
              myCity:
                !v.province && !v.city && !v.region
                  ? "（空）"
                  : `${v.province}-${v.city}-${v.region}`,
              address: v.address || "（空）",
              name: v.name || "（空）",
              siteNum: v.siteNum || "（空）",
              pmName: v.pmUserId === 1 ? "管理员" : v.pmName || "（空）",
              typeIn:
                v.typeIn === "pc"
                  ? "系统"
                  : v.typeIn === "app-scan"
                  ? "移动端扫码"
                  : "移动端手工",
            })),
            sheetName: name,
            sheetFilter: [
              "myCity",
              "address",
              "name",
              "siteNum",
              "roomNum",
              "pmName",
              "updateTime",
              "typeIn",
            ],
            sheetHeader: [
              "站址地区",
              "详细地址",
              "站址名称",
              "站址编号",
              "机房编码",
              "项目经理",
              "最近编辑时间",
              "录入方式",
            ],
            columnWidths: [10, 10, 10, 10, 10, 10, 10, 10],
          },
        ],
      };

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

  return (
    <div className={styles.A2Psychz}>
      <div className="pageTitle">
        {openInfo.txt === "新增"
          ? "新增机房"
          : openInfo.txt === "编辑"
          ? "编辑机房"
          : "机房管理"}
      </div>
      {/* 顶部筛选 */}
      <div className="A2top">
        {/* 左侧输入框 */}
        <div className="A2top1">
          <div className="A2topRow">
            <span>站址地区：</span>

            <Cascader
              changeOnSelect
              style={{ width: 240 }}
              options={optionsCity}
              value={tableSelect.siteArr}
              placeholder="全部"
              onChange={(e) =>
                setTableSelect({
                  ...tableSelect,
                  siteArr: e as string[],
                })
              }
            />
          </div>

          <div className="A2topRow">
            <span>搜索项：</span>
            <Input
              key={inputKey}
              maxLength={24}
              style={{ width: 322 }}
              placeholder="请输入站址名称/站置编号/机房编码,最多24字"
              allowClear
              onChange={(e) => txtChangeFu(e.target.value, "searchKey")}
            />
          </div>
        </div>

        <div className="A2top2">
          <div>
            <div className="A2topRow">
              <span>项目经理：</span>
              <Input
                key={inputKey}
                maxLength={10}
                style={{ width: 240 }}
                placeholder="请输入姓名,最多10字"
                allowClear
                onChange={(e) => txtChangeFu(e.target.value, "pmUser")}
              />
            </div>
            <div className="A2topRow">
              <span>录入方式：</span>
              <Select
                style={{ width: 150 }}
                value={tableSelect.typeIn}
                onChange={(e) => setTableSelect({ ...tableSelect, typeIn: e })}
                options={options1}
              />
            </div>
          </div>
          {/* 按钮 */}
          <div>
            <Button onClick={resetSelectFu}>重置</Button>&emsp;
            <Button type="primary" onClick={clickSearch}>
              查询
            </Button>
            &emsp;
            <Button
              type="primary"
              onClick={() => setOpenInfo({ id: -1, txt: "新增" })}
            >
              新增
            </Button>
            &emsp;
            <Button type="primary" onClick={deriveFu}>
              导出表格
            </Button>
          </div>
        </div>
      </div>

      {/* 表格主体 */}
      <div className="tableMain">
        <Table
          scroll={{ y: 578 }}
          dataSource={A2TableList.list}
          columns={columns}
          rowKey="id"
          pagination={{
            showQuickJumper: true,
            position: ["bottomCenter"],
            showSizeChanger: true,
            current: tableSelect.pageNum,
            pageSize: tableSelect.pageSize,
            total: A2TableList.total,
            onChange: paginationChange(),
          }}
        />
      </div>

      {/* 新增和编辑出来的页面 */}
      {openInfo.id ? (
        <AddPsychz
          openInfo={openInfo}
          closeFu={() => setOpenInfo({ id: 0, txt: "" })}
          upTableFu={() => {
            getListFu();
            getCityFu();
          }}
          addTableFu={() => {
            resetSelectFu();
            getCityFu();
          }}
        />
      ) : null}

      {/*  右下角的列表数量 */}
      <div className="tableNumBox">
        共 <span>{A2TableList.total}</span> 条数据
      </div>
    </div>
  );
}

const MemoA2Psychz = React.memo(A2Psychz);

export default MemoA2Psychz;
