import { overviewApi } from "@/api";
import { GetOverviewListParams, OverviewParams } from "@/types";
import { formatDate } from "@/utils/date";
import {
  Button,
  DatePicker,
  Form,
  FormInstance,
  Input,
  Popconfirm,
  Table,
} from "antd";
import { debounce } from "lodash";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useNavigate } from "react-router-dom";

const { RangePicker } = DatePicker;
const DEFAULT_PARAMS: GetOverviewListParams = {
  startTime: "",
  endTime: "",
  searchKey: "",
  pageNum: 1,
  pageSize: 20,
};

export default function Overview() {
  const navigate = useNavigate();
  const [list, setList] = useState<OverviewParams[]>([]);
  const [total, setTotal] = useState(0);
  const formRef = useRef<FormInstance>(null);
  const [params, setParams] = useState<GetOverviewListParams>({
    ...DEFAULT_PARAMS,
  });

  const getOverviewList = useCallback(async () => {
    const data = await overviewApi.getList(params);
    setList(data.records);
    setTotal(data.total);
  }, [params]);

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

  const COLUMNS = useMemo(() => {
    return [
      {
        title: "企业名称",
        dataIndex: "name",
      },
      {
        title: "成立日期",
        dataIndex: "createDay",
      },
      {
        title: "简介",
        width: 400,
        ellipsis: true,
        render: (item: OverviewParams) =>
          item.description ? item.description : "（空）",
      },
      {
        title: "操作",
        width: 230,
        render(item: OverviewParams) {
          return (
            <>
              <>
                <Button
                  type="text"
                  onClick={() => navigate(`/overview/view/${item.id}`)}
                >
                  查看
                </Button>
                <Button
                  type="text"
                  onClick={() => navigate(`/overview/edit/${item.id}`)}
                >
                  编辑
                </Button>
                <Popconfirm
                  title="提示"
                  description="确认是否删除?"
                  onConfirm={handleDel.bind(undefined, item.id)}
                >
                  <Button type="text" danger>
                    删除
                  </Button>
                </Popconfirm>
              </>
            </>
          );
        },
      },
    ];
  }, [handleDel, navigate]);

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

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

  const debounceSearch = useMemo(
    () =>
      debounce(
        (
          changedVal: OverviewParams,
          vals: OverviewParams & { date: string[] }
        ) => {
          const { date, ...rest } = vals;

          let startTime = "";
          let endTime = "";
          if (date && date[0] && date[1]) {
            startTime = formatDate(date[0]) + " 00:00:00";
            endTime = formatDate(date[1]) + " 23:59:59";
          }

          setParams({ ...params, ...rest, startTime, endTime });
        },
        500
      ),
    [params]
  );

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

  return (
    <div className="overview">
      <Form layout="inline" ref={formRef} onValuesChange={debounceSearch}>
        <Form.Item label="企业名称：" name="searchKey">
          <Input
            className="w220"
            placeholder="请输入关键字"
            maxLength={30}
            allowClear
            showCount
          />
        </Form.Item>
        <Form.Item label="成立日期：" name="date">
          <RangePicker />
        </Form.Item>
        <Form.Item>
          <Button type="primary" onClick={handleAdd}>
            新增
          </Button>
        </Form.Item>
        <Form.Item>
          <Button onClick={handleReset}>重置</Button>
        </Form.Item>
      </Form>

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