import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import styles from "./index.module.scss";
import { useDispatch, useSelector } from "react-redux";
import {
  A2_APIgetListSort,
  A2_APIgetListSortAll,
  A2_APIsort,
} from "@/store/action/A2Gallery";
import { RootState } from "@/store";
import { Input, Table, Tooltip } from "antd";
import { A2TableType } from "@/types";
import ImageLazy from "@/components/ImageLazy";

import {
  SortAscendingOutlined,
  ExclamationCircleFilled,
} from "@ant-design/icons";
import { MessageFu } from "@/utils/message";

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

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

  const getListFu = useCallback(() => {
    dispatch(A2_APIgetListSort(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.sortTableInfo
  );
  // 页码变化
  const paginationChange = useCallback(
    () => (pageNum: number, pageSize: number) => {
      setFromData({ ...fromData, pageNum, pageSize });
    },
    [fromData]
  );

  // 所有数据
  const [dataAll, setDataAll] = useState({
    list: [] as A2TableType[],
    total: 0,
  });

  const getListAll = useCallback(async () => {
    const res = await A2_APIgetListSortAll();
    if (res.code === 0) {
      setDataAll({ list: res.data.records, total: res.data.total });
    }
  }, []);

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

  // 有关排序的操作：

  const showInpRef = useRef<HTMLInputElement>(null);
  const [sortClickNum, setSortClickNum] = useState(-1);

  const [sortValue, setSortValue] = useState("");

  //  点击排序
  const sortShowFu = useCallback((sort: number) => {
    setSortClickNum(sort);
    setSortValue(sort + "");
    setTimeout(() => {
      if (showInpRef.current) showInpRef.current.focus();
    }, 100);
  }, []);

  const sortValueChange = useCallback((val: string) => {
    // if (Number(val) > dataAll.total) val = dataAll.total + "";
    setSortValue(val.replace(/^(0+)|[^\d]+/g, ""));
  }, []);

  const sortOkFu = useCallback(
    async (sort: number) => {
      if (!sortValue) return MessageFu.warning("请输入排序标识!");

      let oldId = 0;
      let newId = 0;

      dataAll.list.forEach((v) => {
        if (v.sort === sort) oldId = v.id;
        if (Number(sortValue) === v.sort) newId = v.id;
      });

      if (oldId === newId)
        return MessageFu.warning("不能和之前的排序标识一样!");

      if (dataAll.list.some((v) => v.sort === Number(sortValue))) {
        const res = await A2_APIsort(oldId, newId);

        if (res.code === 0) {
          MessageFu.success("修改排序标识成功!");
          setSortClickNum(-1);
          getListFu();
        }
      } else MessageFu.warning("找不到该排序标识!");
    },
    [dataAll.list, getListFu, sortValue]
  );

  const inputKeyFu = useCallback(
    (e: React.KeyboardEvent<HTMLInputElement>, sort: number) => {
      if (e.key === "Enter") {
        sortOkFu(sort);
        e.preventDefault();
      }
    },
    [sortOkFu]
  );

  const columns = useMemo(() => {
    return [
      // {
      //   title: "序号",
      //   width: 100,
      //   render: (text: any, record: any, index: any) =>
      //     index + 1 + (fromData.pageNum - 1) * fromData.pageSize,
      // },
      {
        title: "展览名称",
        dataIndex: "name",
      },
      {
        title: "封面图",
        render: (item: A2TableType) => (
          <div className="tableImgAuto">
            <ImageLazy width={60} height={60} src={item.thumb} />
          </div>
        ),
      },
      {
        title: "标签",
        render: (item: A2TableType) => (item.tag ? item.tag : "（空）"),
      },
      {
        title: "展览地点",
        dataIndex: "address",
      },
      {
        title: "排序标识",
        width: 100,
        dataIndex: "sort",
      },
      {
        title: "操作",
        width: 200,
        render: (item: A2TableType) => (
          <div className="sortBox">
            &nbsp;
            <SortAscendingOutlined
              hidden={sortClickNum === item.sort}
              onClick={() => sortShowFu(item.sort)}
              rev={undefined}
            />
            {sortClickNum === item.sort ? (
              <input
                onBlur={() => setSortClickNum(-1)}
                onKeyDown={(e) => inputKeyFu(e, item.sort)}
                ref={showInpRef}
                maxLength={5}
                type="text"
                value={sortValue}
                onChange={(e) => sortValueChange(e.target.value)}
              />
            ) : null}
          </div>
        ),
      },
    ];
  }, [inputKeyFu, sortClickNum, sortShowFu, sortValue, sortValueChange]);

  return (
    <div className={styles.A2ZSort}>
      <div className="pageTitle">展览排序</div>

      <div className="pageTop">
        <span>展览名称：</span>
        <Input
          maxLength={50}
          style={{ width: 200 }}
          placeholder="请输入关键字"
          allowClear
          onChange={(e) => nameChange(e)}
        />

        <div className="sortTit" hidden={dataAll.total <= 1}>
          <Tooltip
            title={
              <>
                点击 &emsp;
                <SortAscendingOutlined rev={undefined} />
                &emsp;输入&emsp;排序标识，按&emsp;Enter键&emsp;交换位置（排序标识会累加，删除的排序标识不会在出现）
              </>
            }
          >
            <div className="inco">
              <ExclamationCircleFilled rev={undefined} />
            </div>
          </Tooltip>
        </div>

        <span></span>
      </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>
    </div>
  );
}

const MemoA2ZSort = React.memo(A2ZSort);

export default MemoA2ZSort;
