import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import styles from "./index.module.scss";
import { Button, Input, Popconfirm, Table } from "antd";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "@/store";
import { A1tableType } from "@/types";
import {
  A1_APIdel,
  A1_APIgetList,
  isTokenFlagAPI,
} from "@/store/action/A1List";
import { MessageFu } from "@/utils/message";
import history from "@/utils/history";
import { removeTokenInfo } from "@/utils/storage";

const isTokenFlagFu = (val: boolean, url: string) => {
  if (val) {
    // token 有效
    window.open(url);
  } else {
    // token 失效
    MessageFu.warning("登录失效，请重新登录!");
    removeTokenInfo();
    history.push("/login");
  }
};

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

  // 顶部筛选
  const [tableSelect, setTableSelect] = useState({
    pageNum: 1,
    pageSize: 10,
    searchKey: "",
  });

  const getListFu = useCallback(() => {
    dispatch(A1_APIgetList(tableSelect));
  }, [dispatch, tableSelect]);

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

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

  const { tableInfo } = useSelector((state: RootState) => state.A1List);

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

  const lookFu = useCallback(async (code: string) => {
    const res = await isTokenFlagAPI();
    if (res.code === 0) {
      isTokenFlagFu(res.data, `/scene/index.html?m=${code}`);
    }
  }, []);

  const editFu = useCallback(async (code: string) => {
    const res = await isTokenFlagAPI();
    if (res.code === 0) {
      isTokenFlagFu(res.data, `/scene/edit.html?m=${code}`);
    }
  }, []);

  const delTableFu = useCallback(
    async (id: number) => {
      const res = await A1_APIdel(id);
      if (res.code === 0) {
        MessageFu.success("删除成功!");
        getListFu();
      }
    },
    [getListFu]
  );

  const columns = useMemo(() => {
    return [
      {
        title: "编号",
        dataIndex: "sceneCode",
      },
      {
        title: "场景名称",
        dataIndex: "name",
      },
      {
        title: "发布时间",
        dataIndex: "createTime",
      },

      {
        title: "操作",
        render: (item: A1tableType) => (
          <>
            <Button
              size="small"
              type="text"
              onClick={() => lookFu(item.sceneCode)}
            >
              查看
            </Button>

            <Button
              size="small"
              type="text"
              onClick={() => editFu(item.sceneCode)}
            >
              编辑
            </Button>
            <Popconfirm
              title="删除后无法恢复，是否删除?"
              okText="删除"
              cancelText="取消"
              okButtonProps={{ loading: false }}
              onConfirm={() => delTableFu(item.id)}
            >
              <Button size="small" type="text" danger>
                删除
              </Button>
            </Popconfirm>
          </>
        ),
      },
    ];
  }, [delTableFu, editFu, lookFu]);

  return (
    <div className={styles.A1List}>
      <div className="pageTitle">场景管理</div>
      <div className="A1Top">
        <div className="selectBox">
          <div className="selectBoxL">
            <div className="row">
              <span>场景名称：</span>
              <Input
                maxLength={30}
                style={{ width: 300 }}
                placeholder="请输入"
                allowClear
                onChange={(e) => nameChange(e)}
              />
            </div>
          </div>
        </div>
      </div>
      {/* 表格主体 */}
      <div className="tableBox">
        <Table
          scroll={{ y: 605 }}
          dataSource={tableInfo.list}
          columns={columns}
          rowKey="id"
          pagination={{
            showQuickJumper: true,
            position: ["bottomCenter"],
            // showSizeChanger: true,
            current: tableSelect.pageNum,
            pageSize: tableSelect.pageSize,
            total: tableInfo.total,
            onChange: paginationChange(),
          }}
        />
      </div>
    </div>
  );
}

const MemoA1List = React.memo(A1List);

export default MemoA1List;
