import { industrialMetaApi } from "@/api";
import { GetHistoryListParams, HistoryItem } from "@/types";
import { Button, Form, FormInstance, Input, Table } from "antd";
import { debounce } from "lodash";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useNavigate } from "react-router-dom";

const DEFAULT_PARAMS: GetHistoryListParams = {
  pageNum: 1,
  pageSize: 20,
};

export default function IndustrialMeta() {
  const navigate = useNavigate();
  const formRef = useRef<FormInstance>(null);
  const [list, setList] = useState<HistoryItem[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [params, setParams] = useState<GetHistoryListParams>({
    ...DEFAULT_PARAMS,
  });

  const getList = useCallback(async () => {
    setLoading(true);
    try {
      const { data } = await industrialMetaApi.getList(params);
      setList(data.records);
      setTotal(data.total);
    } finally {
      setLoading(false);
    }
  }, [params]);

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

  const debounceSearch = useMemo(
    () =>
      debounce((changedVal: unknown, vals: GetHistoryListParams) => {
        setParams({ ...params, ...vals });
      }, 500),
    [params]
  );

  const paginationChange = useCallback(
    () => (pageNum: number, pageSize: number) => {
      setParams({ ...params, pageNum, pageSize });
    },
    [params]
  );

  const handleReset = useCallback(() => {
    setParams({ ...DEFAULT_PARAMS });
    formRef.current?.resetFields();
  }, [formRef]);

  const COLUMNS = useMemo(() => {
    return [
      {
        title: "名称",
        dataIndex: "name",
      },
      {
        title: "简介",
        width: 400,
        ellipsis: true,
        render: (item: HistoryItem) =>
          item.description ? item.description : "（空）",
      },
      {
        title: "操作",
        width: 230,
        render: (item: HistoryItem) => (
          <>
            <Button
              type="text"
              onClick={() => navigate(`/industrial-meta/edit/${item.id}`)}
            >
              编辑
            </Button>
          </>
        ),
      },
    ];
  }, [navigate]);

  return (
    <div className="industrial-meta">
      <Form ref={formRef} layout="inline" onValuesChange={debounceSearch}>
        <Form.Item label="名称" name="searchKey">
          <Input
            className="w220"
            placeholder="请输入关键字"
            maxLength={30}
            showCount
            allowClear
          />
        </Form.Item>
        <Form.Item>
          <Button onClick={handleReset}>重置</Button>
        </Form.Item>
      </Form>

      <Table
        loading={loading}
        className="c-table"
        dataSource={list}
        columns={COLUMNS}
        rowKey="id"
        pagination={{
          showQuickJumper: true,
          position: ["bottomCenter"],
          showSizeChanger: true,
          current: params.pageNum,
          pageSize: params.pageSize,
          total,
          onChange: paginationChange(),
        }}
      />
    </div>
  );
}
