import { Button, Input, Popconfirm, Table } from "antd";
import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import styles from "./index.module.scss";
import { useDispatch, useSelector } from "react-redux";
import store, { RootState } from "@/store";
import classNames from "classnames";
import {
  smartGetListAPI,
  smartRemoveAPI,
  smartSaveAPI,
  smartSortAPI,
} from "@/store/action/B6Smart";
// 表格拖动排序-----------------
import { SmartTableType } from "@/types";
import { MessageFu } from "@/utils/message";

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

  useEffect(() => {
    dispatch(smartGetListAPI("hot"));
  }, [dispatch]);

  // 从仓库中获取列表数据
  const results = useSelector((state: RootState) => state.smartReducer.hotList);

  // 点击编辑或者新增
  const editIdRef = useRef(0);

  const editTableFu = useCallback(
    (id: number) => {
      if (id === -1 && results.length >= 5)
        return MessageFu.warning("最多可配置5个搜索热词！");
      editIdRef.current = id;
      setValueOk(false);

      if (id === -1) {
        setValue("");
        const newList: SmartTableType[] = [
          { id: Date.now(), type: "edit", name: "" },
          ...results,
        ];
       store.dispatch({ type: "smart/getHotList", payload: newList });
      } else {
        const newList = [...results];
        newList.forEach((v) => {
          if (v.id === id) {
            setValue(v.name);
            v.type = "edit";
          }
        });
        store.dispatch({ type: "smart/getHotList", payload: newList });
      }
    },
    [results]
  );

  // 点击删除
  const delTableFu = useCallback(
    async (id: number) => {
      const res: any = await smartRemoveAPI(id);
      if (res.code === 0) {
        MessageFu.success("删除成功!");
        dispatch(smartGetListAPI("hot"));
      }
    },
    [dispatch]
  );

  // 新增和编辑点击完成

  const [value, setValue] = useState("");
  const [valueOk, setValueOk] = useState(false);

  const btnOk = useCallback(async () => {
    setValueOk(true);
    if (value === "") return;
    const res = await smartSaveAPI({
      name: value,
      id: editIdRef.current > 0 ? editIdRef.current : null,
      type: "hot",
    });
    if (res.code === 0) {
      MessageFu.success(editIdRef.current > 0 ? "编辑成功!" : "新增成功!");
      dispatch(smartGetListAPI("hot"));
    }
  }, [dispatch, value]);

  // 点击上移和下移动
  const moveTableFu = useCallback(
    async (id1: number, id2: number) => {
      const res = await smartSortAPI(id1, id2);
      if (res.code === 0) dispatch(smartGetListAPI("hot"));
    },
    [dispatch]
  );

  // --------表格数据
  const columns = useMemo(() => {
    return [
      {
        title: "内容",
        render: (item: SmartTableType) => {
          if (item.type === "edit") {
            return (
              <div className="tableRow">
                <Input
                  style={{ width: 200 }}
                  value={value}
                  onChange={(e) => setValue(e.target.value.replace(/\s+/g, ""))}
                  maxLength={6}
                  showCount
                  placeholder="请输入关键字"
                />
                <div
                  className={classNames(
                    "rowTit",
                    valueOk && value === "" ? "rowTitAc" : ""
                  )}
                >
                  内容不能为空!
                </div>
              </div>
            );
          } else {
            return item.name;
          }
        },
      },
      {
        title: "操作",
        render: (item: SmartTableType, record: any, index: number) => {
          if (item.type === "edit") {
            return (
              <>
                <Button size="small" type="text" onClick={btnOk}>
                  完成
                </Button>
                <Button
                  size="small"
                  type="text"
                  danger
                  onClick={() => dispatch(smartGetListAPI("hot"))}
                >
                  取消
                </Button>
              </>
            );
          } else {
            return (
              <>
                <Button
                  size="small"
                  type="text"
                  onClick={() => moveTableFu(item.id, results[index - 1].id)}
                  disabled={index === 0}
                >
                  上移
                </Button>
                <Button
                  size="small"
                  type="text"
                  onClick={() => moveTableFu(item.id, results[index + 1].id)}
                  disabled={index === results.length - 1}
                >
                  下移
                </Button>
                <Button
                  size="small"
                  type="text"
                  onClick={() => editTableFu(item.id)}
                  disabled={
                    results &&
                    results.length > 0 &&
                    results.some((v) => v.type === "edit")
                  }
                >
                  编辑
                </Button>

                <Popconfirm
                  title="删除后无法恢复，是否删除?"
                  okText="删除"
                  cancelText="取消"
                  onConfirm={() => delTableFu(item.id)}
                >
                  <Button size="small" type="text" danger>
                    删除
                  </Button>
                </Popconfirm>
              </>
            );
          }
        },
      },
    ];
  }, [
    btnOk,
    delTableFu,
    dispatch,
    editTableFu,
    moveTableFu,
    results,
    value,
    valueOk,
  ]);

  return (
    <div className={styles.SmartHotTable}>
      <div className="topTit">
        <div className="titleTxt">搜索热词</div>
        <Button
          type="primary"
          disabled={
            results &&
            results.length > 0 &&
            results.some((v) => v.type === "edit")
          }
          onClick={() => editTableFu(-1)}
        >
          新增热词
        </Button>
      </div>
      {/* 表格主体 */}
      <div className="tableHotBox">
        <Table
          scroll={{ y: 215 }}
          columns={columns}
          dataSource={results}
          rowKey="id"
          pagination={false}
        />
      </div>
    </div>
  );
}

const MemoSmartHotTable = React.memo(SmartHotTable);

export default MemoSmartHotTable;
