import { useCallback, useEffect, useMemo, useState } from "react";
import { Button, Input, Table } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import { useNavigate } from "react-router-dom";
import { PageContainer } from "@/components";
import style from "./index.module.scss";
import { deleteAssTemplateApi, getAssTemplateListApi } from "@/api";
import { ASS_INDEX_TYPE, IAssTemplateDetail } from "@/types";
import { DageTableActions } from "@dage/pc-components";
import { useHashQuery } from "@/hooks";
import { debounce } from "lodash";

const { Search } = Input;

const TemplatePage = () => {
  const navigate = useNavigate();
  const [tab, setTab] = useHashQuery("tab", ASS_INDEX_TYPE.FIXED);
  const [fixedLoading, setFixedLoading] = useState(false);
  const [operationLoading, setOperationLoading] = useState(false);
  const [fixedList, setFixedList] = useState<IAssTemplateDetail[]>([]);
  const [operationList, setOperationList] = useState<IAssTemplateDetail[]>([]);
  const [searchKey, setSearchKey] = useState("");
  const isFixed = useMemo(() => tab === ASS_INDEX_TYPE.FIXED, [tab]);

  const getList = async (type: ASS_INDEX_TYPE, keyword = searchKey) => {
    const _isFixed = type === ASS_INDEX_TYPE.FIXED;
    try {
      _isFixed ? setFixedLoading(true) : setOperationLoading(true);
      const data = await getAssTemplateListApi(type, keyword);
      _isFixed ? setFixedList(data) : setOperationList(data);
    } finally {
      _isFixed ? setFixedLoading(false) : setOperationLoading(false);
    }
  };

  const handleTab = (type: ASS_INDEX_TYPE) => {
    setTab(type);
    getList(type);
  };

  const handleEdit = (item: IAssTemplateDetail) => {
    navigate(`/assessment/template/edit/${tab}/${item.id}`);
  };

  const handleDelete = async (item: IAssTemplateDetail) => {
    await deleteAssTemplateApi(item.id);
    getList(tab);
  };

  const handleSearch = useMemo(
    () =>
      debounce((keyword: string) => {
        getList(tab, keyword);
      }, 500),
    [tab]
  );

  useEffect(() => {
    getList(ASS_INDEX_TYPE.FIXED);
    getList(ASS_INDEX_TYPE.OPERATION);
  }, []);

  return (
    <PageContainer
      title="考核模板"
      headerSlot={
        <div className={style.pageTools}>
          <div>
            <Button
              type="primary"
              ghost={!isFixed}
              size="large"
              onClick={handleTab.bind(undefined, ASS_INDEX_TYPE.FIXED)}
            >
              定级评估模板 {fixedLoading ? "-" : fixedList.length}
            </Button>
            <Button
              type="primary"
              ghost={isFixed}
              size="large"
              onClick={handleTab.bind(undefined, ASS_INDEX_TYPE.OPERATION)}
            >
              运行评估模板 {operationLoading ? "-" : operationList.length}
            </Button>
          </div>

          <div className={style.pageToolsRight}>
            <label>搜索</label>
            <Search
              value={searchKey}
              size="large"
              placeholder="请输入模板名称"
              allowClear
              style={{ width: 170 }}
              onChange={(e) => {
                setSearchKey(e.target.value);
                handleSearch(e.target.value);
              }}
              onSearch={() => getList(tab)}
            />

            <Button
              type="primary"
              icon={<PlusOutlined />}
              size="large"
              className={style.secondButton}
              onClick={() => navigate(`/assessment/template/create/${tab}`)}
            >
              新增{isFixed ? "定级" : "运行"}评估模板
            </Button>
          </div>
        </div>
      }
    >
      <Table
        rowKey="id"
        loading={isFixed ? fixedLoading : operationLoading}
        className="cus-table large"
        dataSource={isFixed ? fixedList : operationList}
        columns={[
          {
            title: "名称",
            dataIndex: "name",
            align: "center",
          },
          {
            title: "说明",
            dataIndex: "remark",
            align: "center",
            ellipsis: true,
          },
          {
            title: "编辑时间",
            dataIndex: "updateTime",
            align: "center",
          },
          {
            title: "编辑人",
            dataIndex: "creatorName",
            align: "center",
          },
          {
            title: "操作",
            align: "center",
            render: (item: IAssTemplateDetail) => {
              return (
                <DageTableActions
                  onEdit={handleEdit.bind(undefined, item)}
                  onDelete={handleDelete.bind(undefined, item)}
                />
              );
            },
          },
        ]}
      />
    </PageContainer>
  );
};

export default TemplatePage;
