import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import styles from "./index.module.scss";
import { Button, Input, Popconfirm, Select, Table } from "antd";
import { A1addType, TableSelectType, options1, options2 } from "./data";
import { useDispatch, useSelector } from "react-redux";
import {
  A1_APIgetlist,
  A1_APIgetlistDerive,
  A1_APIremove,
} from "@/store/action/A1Camera";
import { RootState } from "@/store";
import { A1ListType } from "@/types";
import ExportJsonExcel from "js-export-excel";
import { MessageFu } from "@/utils/message";
import dayjs from "dayjs";
import AddCamera from "./AddCamera";
import LogCamera from "./LogCamera";

function A1Camera() {
  const dispatch = useDispatch();

  // 筛选和分页
  const [tableSelect, setTableSelect] = useState<TableSelectType>({
    cameraSn: "",
    searchKey: "",
    status: "全部",
    typeIn: "全部",
    pageSize: 10,
    pageNum: 1,
  });

  const tableSelectRef = useRef({} as TableSelectType);

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

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

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

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

  // 发送接口的函数
  const getListFu = useCallback(() => {
    const obj = {
      ...tableSelectRef.current,
      status:
        tableSelectRef.current.status === "全部"
          ? ""
          : tableSelectRef.current.status,
      typeIn:
        tableSelectRef.current.typeIn === "全部"
          ? ""
          : tableSelectRef.current.typeIn,
    };
    dispatch(A1_APIgetlist(obj));
  }, [dispatch]);

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

  // 从仓库获取列表
  const A1TableList = useSelector(
    (state: RootState) => state.A1Camera.A1TableList
  );
  // 页码变化
  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 A1_APIremove(id);
      if (res.code === 0) {
        MessageFu.success("删除成功!");
        getListFu();
      }
    },
    [getListFu]
  );

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

    if (A1TableList.list.length === 0)
      return MessageFu.warning("当前搜索条件没有数据!");
    const name = "相机管理" + dayjs(new Date()).format("YYYY-MM-DD HH:mm");

    const res = await A1_APIgetlistDerive({
      ...tableSelect,
      status: tableSelect.status === "全部" ? "" : tableSelect.status,
      typeIn: tableSelect.typeIn === "全部" ? "" : tableSelect.typeIn,
      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: A1ListType) => ({
              ...v,
              typeIn: v.typeIn === "pc" ? "系统" : "移动端",
              remark: v.remark || "（空）",
              pmName: v.id === 1 ? "管理员" : v.pmName || "（空）",
            })),
            sheetName: name,
            sheetFilter: [
              "cameraSn",
              "pmName",
              "status",
              "typeIn",
              "updateTime",
              "remark",
            ],
            sheetHeader: [
              "相机SN码",
              "项目经理",
              "相机工况",
              "录入方式",
              "最近编辑时间",
              "备注",
            ],
            columnWidths: [10, 10, 10, 10, 10, 20],
          },
        ],
      };

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

  const columns = useMemo(() => {
    return [
      {
        title: "相机SN码",
        dataIndex: "cameraSn",
      },
      {
        title: "项目经理",
        render: (item: A1ListType) => {
          if (item.id === 1) return "管理员";
          else {
            return item.pmName || "（空）";
          }
        },
      },
      {
        title: "相机工况",
        dataIndex: "status",
      },
      {
        title: "录入方式",
        render: (item: A1ListType) =>
          item.typeIn === "pc" ? "系统" : "移动端",
      },
      {
        title: "最近编辑时间",
        dataIndex: "updateTime",
      },

      {
        title: "备注",
        render: (item: A1ListType) =>
          item.remark ? (
            item.remark.length >= 25 ? (
              <span style={{ cursor: "pointer" }} title={item.remark}>
                {item.remark.substring(0, 25) + "..."}
              </span>
            ) : (
              item.remark
            )
          ) : (
            "（空）"
          ),
      },
      {
        title: "操作",
        render: (item: A1ListType) => (
          <>
            <Button
              size="small"
              type="text"
              onClick={() => setLogSn(item.cameraSn)}
            >
              领用记录
            </Button>
            <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 [inputKey, setInputKey] = useState(1);
  const resetSelectFu = useCallback(() => {
    // 把2个输入框和时间选择器清空
    setInputKey(Date.now());
    setTableSelect({
      cameraSn: "",
      searchKey: "",
      status: "全部",
      typeIn: "全部",
      pageSize: 10,
      pageNum: 1,
    });
    setTimeout(() => {
      setTimeKey(Date.now());
    }, 50);
  }, []);

  // 点击新增和编辑的数据
  const [openInfo, setOpenInfo] = useState<A1addType>({ id: 0, txt: "" });

  // 左上角的 title
  const leftTitle = useMemo(() => {
    const obj = {
      "": "相机管理",
      新增: "新增相机",
      编辑: "编辑相机",
    };
    return obj[openInfo.txt];
  }, [openInfo.txt]);

  // 点击 领用记录
  const [logSn, setLogSn] = useState("");

  return (
    <div className={styles.A1Camera}>
      <div className="pageTitle">
        {leftTitle}
        {logSn ? " - 领用记录" : ""}
      </div>
      {/* 顶部筛选 */}
      <div className="A1top">
        {/* 左侧输入框 */}
        <div className="A1top1">
          <div className="A1topRow">
            <span>SN码：</span>
            <Input
              key={inputKey}
              maxLength={10}
              style={{ width: 190 }}
              placeholder="请输入SN码，最多10字"
              allowClear
              onChange={(e) => txtChangeFu(e.target.value, "cameraSn")}
            />
          </div>

          <div className="A1topRow">
            <span>项目经理：</span>
            <Input
              key={inputKey}
              maxLength={10}
              style={{ width: 190 }}
              placeholder="请输入姓名，最多10字"
              allowClear
              onChange={(e) => txtChangeFu(e.target.value, "searchKey")}
            />
          </div>

          <div className="A1topRow">
            <span>相机工况：</span>
            <Select
              style={{ width: 150 }}
              value={tableSelect.status}
              onChange={(e) => setTableSelect({ ...tableSelect, status: e })}
              options={options1}
            />
          </div>

          <div className="A1topRow">
            <span>录入方式：</span>
            <Select
              style={{ width: 150 }}
              value={tableSelect.typeIn}
              onChange={(e) => setTableSelect({ ...tableSelect, typeIn: e })}
              options={options2}
            />
          </div>
        </div>
        {/* 右侧按钮 */}
        <div className="A1top2">
          <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 className="tableMain">
        <Table
          scroll={{ y: 625 }}
          dataSource={A1TableList.list}
          columns={columns}
          rowKey="id"
          pagination={{
            showQuickJumper: true,
            position: ["bottomCenter"],
            showSizeChanger: true,
            current: tableSelect.pageNum,
            pageSize: tableSelect.pageSize,
            total: A1TableList.total,
            onChange: paginationChange(),
          }}
        />
      </div>

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

      {/* 领用记录 */}
      {logSn ? <LogCamera logSn={logSn} closeFu={() => setLogSn("")} /> : null}

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

const MemoA1Camera = React.memo(A1Camera);

export default MemoA1Camera;
