import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import styles from "./index.module.scss";
import { Button, Input, Table } from "antd";
import { useDispatch, useSelector } from "react-redux";
import store, { RootState } from "@/store";
import { A2_APIgetList } from "@/store/action/A2Gallery";
import { A2TableType } from "@/types";
import A2Edit from "./A2Edit";
function A2Gallery() {
  const dispatch = useDispatch();

  const [fromData, setFromData] = useState({
    pageNum: 1,
    pageSize: 10,
    searchKey: "",
  });

  const getListFu = useCallback(() => {
    dispatch(A2_APIgetList(fromData));
  }, [dispatch, fromData]);

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

  // 名称的输入
  const nameTime = useRef(-1);
  const nameChange = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      clearTimeout(nameTime.current);
      nameTime.current = window.setTimeout(() => {
        setFromData({
          ...fromData,
          searchKey: e.target.value,
          pageNum: 1,
        });
      }, 500);
    },
    [fromData]
  );

  // 从仓库获取表格数据
  const tableInfo = useSelector(
    (state: RootState) => state.A2Gallery.tableInfo
  );
  // 页码变化
  const paginationChange = useCallback(
    () => (pageNum: number, pageSize: number) => {
      setFromData({ ...fromData, pageNum, pageSize });
    },
    [fromData]
  );

  const columns = useMemo(() => {
    return [
      {
        title: "展馆名称",
        dataIndex: "name",
      },
      {
        title: "地址",
        render: (item: A2TableType) =>
          item.address ? (
            item.address.length >= 40 ? (
              <span style={{ cursor: "pointer" }} title={item.address}>
                {item.address.substring(0, 40) + "..."}
              </span>
            ) : (
              item.address
            )
          ) : (
            "（空）"
          ),
      },

      {
        title: "展馆介绍",
        render: (item: A2TableType) =>
          item.description ? (
            item.description.length >= 70 ? (
              <span style={{ cursor: "pointer" }} title={item.description}>
                {item.description.substring(0, 70) + "..."}
              </span>
            ) : (
              item.description
            )
          ) : (
            "（空）"
          ),
      },
      {
        title: "操作",
        render: (item: A2TableType) => (
          <>
            <Button
              size="small"
              type="text"
              onClick={() => setEditInfo({ type: "look", id: item.id })}
            >
              查看
            </Button>
            <Button
              size="small"
              type="text"
              onClick={() => setEditInfo({ type: "edit", id: item.id })}
            >
              编辑
            </Button>
          </>
        ),
      },
    ];
  }, []);

  // 打开查看或者编辑
  const [editInfo, setEditInfo] = useState({ type: "", id: 0 });

  //从编辑/查看页回来的时候 清空 二级的仓库 表格数据，防止闪动
  const closeFu = useCallback(() => {
    store.dispatch({ type: "A2/inGetList", payload: [] });
    setEditInfo({ type: "", id: 0 });
  }, []);

  useEffect(() => {
    return () => {
      // 离开页面也清空 二级的仓库 表格数据，防止闪动
      store.dispatch({ type: "A2/inGetList", payload: [] });
    };
  }, []);

  return (
    <div className={styles.A2Gallery}>
      <div className="pageTitle">
        {editInfo.type === "look"
          ? "展馆详情"
          : editInfo.type === "edit"
          ? "展馆编辑"
          : "展馆管理"}
      </div>
      <div className="pageTop">
        <span>展馆名称：</span>
        <Input
          maxLength={50}
          style={{ width: 200 }}
          placeholder="请输入关键字"
          allowClear
          onChange={(e) => nameChange(e)}
        />
      </div>
      {/* 表格主体 */}
      <div className="tableBox">
        <Table
          scroll={{ y: 617 }}
          dataSource={tableInfo.list}
          columns={columns}
          rowKey="id"
          pagination={{
            showQuickJumper: true,
            position: ["bottomCenter"],
            showSizeChanger: true,
            current: fromData.pageNum,
            pageSize: fromData.pageSize,
            total: tableInfo.total,
            onChange: paginationChange(),
          }}
        />
      </div>

      {/* 编辑或者查看 */}
      {editInfo.id ? (
        <A2Edit
          editInfo={editInfo}
          editFu={() => getListFu()}
          closeFu={closeFu}
        />
      ) : null}
    </div>
  );
}

const MemoA2Gallery = React.memo(A2Gallery);

export default MemoA2Gallery;
