import { RootState } from "@/store";
import {
  getTopicListAPI,
  topicDisplayAPI,
  topicRemoveAPI,
} from "@/store/action/B5Topic";
import { TopicTableType } from "@/types";
import { MessageFu } from "@/utils/message";
import { Button, Input, Popconfirm, Select, Switch, Table } from "antd";
import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import { useDispatch, useSelector } from "react-redux";
import styles from "./index.module.scss";
import TopicAdd from "./TopicAdd";
function Topic() {
  const dispatch = useDispatch();
  const pageNumRef = useRef(1);
  const pagePageRef = useRef(10);

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

  // 封装发送请求的函数

  const getList = useCallback(async () => {
    const data = {
      ...tableSelect,
      type: tableSelect.type === -1 ? null : tableSelect.type,
      pageNum: pageNumRef.current,
    };
    dispatch(getTopicListAPI(data));
  }, [dispatch, tableSelect]);

  // 当前页码统一
  useEffect(() => {
    pageNumRef.current = tableSelect.pageNum;
    pagePageRef.current = tableSelect.pageSize;
  }, [tableSelect.pageNum, tableSelect.pageSize]);

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

  // 题目标题的输入
  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 nameTime2 = useRef(-1);
  const nameChange2 = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      clearTimeout(nameTime2.current);
      nameTime2.current = window.setTimeout(() => {
        setTableSelect({
          ...tableSelect,
          goodsName: e.target.value,
          pageNum: 1,
        });
      }, 500);
    },
    [tableSelect]
  );

  // 从仓库获取表格列表信息
  const tableInfo = useSelector(
    (state: RootState) => state.topicReducer.tableInfo
  );

  // 点击重置
  const [inputKey, setInputKey] = useState(1);
  const resetSelectFu = useCallback(() => {
    // 把2个输入框和时间选择器清空
    setInputKey(Date.now());
    setTableSelect({
      searchKey: "",
      goodsName: "",
      type: -1,
      pageSize: 10,
      pageNum: 1,
    });
  }, []);

  // 切换表格中的启用停用状态
  const isEnabledClickFu = useCallback(
    async (val: boolean, id: number) => {
      const isDisable = val ? 1 : 0;
      const res = await topicDisplayAPI(id, isDisable);
      if (res.code === 0) getList();
    },
    [getList]
  );

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

  const columns = useMemo(() => {
    return [
      {
        title: "题目",
        render: (item: TopicTableType) =>
          item.question.length >= 50 ? (
            <span style={{ cursor: "pointer" }} title={item.question}>
              {item.question.substring(0, 50) + "..."}
            </span>
          ) : (
            item.question
          ),
      },
      {
        title: "文物",
        dataIndex: "goodsName",
      },
      {
        title: "回答数",
        dataIndex: "pcsAnswer",
      },
      {
        title: "正确率",
        render: (item: TopicTableType) =>
          item.pcsAnswer ? item.pcsAccuracy + "%" : "（空）",
      },
      {
        title: "最后编辑时间",
        dataIndex: "updateTime",
      },
      {
        title: "编辑人",
        dataIndex: "creatorName",
      },
      {
        title: "展示状态",
        render: (item: TopicTableType) => (
          <Switch
            checkedChildren="启用"
            unCheckedChildren="停用"
            checked={item.display === 1}
            onChange={(val) => isEnabledClickFu(val, item.id!)}
          />
        ),
      },
      {
        title: "操作",
        render: (item: TopicTableType) => (
          <>
            <Button size="small" type="text" onClick={() => setAddId(item.id)}>
              编辑
            </Button>
            <Popconfirm
              title="删除后无法恢复，是否删除?"
              okText="删除"
              cancelText="取消"
              onConfirm={() => delTableFu(item.id)}
            >
              <Button size="small" type="text" danger>
                删除
              </Button>
            </Popconfirm>
          </>
        ),
      },
    ];
  }, [delTableFu, isEnabledClickFu]);

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

  // 新增或者编辑的弹窗
  const [addId, setAddId] = useState(0);

  return (
    <div className={styles.Topic}>
      <div className="pageTitlt">
        {addId === 0 ? "题库管理" : addId > 0 ? "编辑题目" : "新增题目"}
      </div>
      {/* 上面的搜索盒子 */}
      <div className="searchTopBox" hidden={addId !== 0}>
        <div className="searchTopBoxRow">
          <span>题目标题：</span>
          <Input
            key={inputKey}
            maxLength={100}
            style={{ width: 200 }}
            placeholder="请输入关键字"
            allowClear
            onChange={(e) => nameChange(e)}
          />
        </div>
        <div className="searchTopBoxRow">
          <span>关联文物：</span>
          <Input
            key={inputKey}
            maxLength={25}
            style={{ width: 200 }}
            placeholder="请输入关键字"
            allowClear
            onChange={(e) => nameChange2(e)}
          />
        </div>
        <div className="searchTopBoxRow">
          <span>回答情况：</span>
          <Select
            placeholder="请选择"
            style={{ width: 120 }}
            value={tableSelect.type}
            onChange={(e) =>
              setTableSelect({ ...tableSelect, type: e, pageNum: 1 })
            }
            options={[
              { value: -1, label: "全部" },
              { value: 0, label: "无人回答" },
              { value: 1, label: "有人回答" },
            ]}
          />
        </div>
        <div className="searchTopBoxRow">
          &emsp;&emsp;<Button onClick={resetSelectFu}>重置</Button>&emsp;&emsp;
          <Button type="primary" onClick={() => setAddId(-1)}>
            新增
          </Button>
        </div>
      </div>
      {/* 表格主体 */}
      <div className="tableBox" hidden={addId !== 0}>
        <Table
          scroll={{ y: 620 }}
          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>
      {/* 新增和编辑的弹窗 */}
      {addId ? (
        <TopicAdd
          id={addId}
          closeMoalFu={() => setAddId(0)}
          addTableFu={resetSelectFu}
          editTableFu={getList}
        />
      ) : null}
    </div>
  );
}

const MemoTopic = React.memo(Topic);

export default MemoTopic;
