import { historyApi } from "@/api";
import { GetHistoryListParams, HistoryDictItem, HistoryItem } from "@/types";
import {
  Button,
  Form,
  FormInstance,
  Input,
  Popconfirm,
  Select,
  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 History() {
  const navigate = useNavigate();
  const formRef = useRef<FormInstance>(null);
  const [list, setList] = useState<HistoryItem[]>([]);
  const [dictList, setDictList] = useState<HistoryDictItem[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [params, setParams] = useState<GetHistoryListParams>({
    ...DEFAULT_PARAMS,
  });

  const getHistoryDictList = async () => {
    const { data } = await historyApi.getHistoryDictList();
    setDictList(data);
  };

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

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

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

  const handleDel = useCallback(
    async (id: number) => {
      await historyApi.del(id);
      getList();
    },
    [getList]
  );

  const handleAdd = useCallback(() => {
    navigate("/history/create");
  }, [navigate]);

  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: "所属阶段",
        dataIndex: "stage",
      },
      {
        title: "品牌",
        render: (item: HistoryItem) =>
          item.companyName ? item.companyName : "（空）",
      },
      {
        title: "简介",
        width: 400,
        ellipsis: true,
        render: (item: HistoryItem) =>
          item.description ? item.description : "（空）",
      },
      {
        title: "操作",
        width: 230,
        render: (item: HistoryItem) => (
          <>
            <Button
              type="text"
              onClick={() => navigate(`/history/view/${item.id}`)}
            >
              查看
            </Button>
            <Button
              type="text"
              onClick={() => navigate(`/history/edit/${item.id}`)}
            >
              编辑
            </Button>
            <Popconfirm
              title="提示"
              description="确认是否删除?"
              onConfirm={handleDel.bind(undefined, item.id)}
            >
              <Button type="text" danger>
                删除
              </Button>
            </Popconfirm>
          </>
        ),
      },
    ];
  }, [handleDel, navigate]);

  return (
    <div className="history">
      <Form ref={formRef} layout="inline" onValuesChange={debounceSearch}>
        <Form.Item label="姓名" name="searchKey">
          <Input
            className="w220"
            placeholder="请输入关键字"
            maxLength={30}
            showCount
            allowClear
          />
        </Form.Item>
        <Form.Item label="所属阶段" name="stage">
          <Select
            style={{ width: 220 }}
            placeholder="请选择"
            allowClear
            options={dictList.map((i) => ({
              value: i.name,
              label: i.name,
            }))}
          />
        </Form.Item>
        <Form.Item>
          <Button type="primary" onClick={handleAdd}>
            新增
          </Button>
        </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>
  );
}
