import classNames from "classnames";
import { useCallback, useEffect, useMemo, useState } from "react";
import { Button, Form, Input, Select, Table } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import { useNavigate } from "react-router-dom";
import { PageContainer } from "@/components";
import { DageTableActions } from "@dage/pc-components";
import style from "./index.module.scss";
import {
  PUBLISH_STATUS_MAP,
  ASSESSMENT_TYPE_OPTIONS,
  PUBLISH_STATUS_OPTIONS,
} from "../../../constants";
import { deleteManageIndexApi, getManageIndexListApi } from "@/api";
import { debounce } from "lodash";
import { ASS_INDEX_TYPE, IManageIndexDetail } from "@/types";

const DEFAULT_PARAMS = {
  pageNum: 1,
  pageSize: 20,
  searchKey: "",
  status: "",
  type: "",
};

const ManagementIndexPage = () => {
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [params, setParams] = useState({
    ...DEFAULT_PARAMS,
  });
  const [total, setTotal] = useState(0);
  const [list, setList] = useState<IManageIndexDetail[]>([]);

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

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

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

  const handleDelete = async (item: IManageIndexDetail) => {
    await deleteManageIndexApi(item.id);
    getList();
  };

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

  return (
    <PageContainer
      title="考核管理"
      headerSlot={
        <div>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            size="large"
            className="second-button"
            onClick={() =>
              navigate("/management/index/create/" + ASS_INDEX_TYPE.FIXED)
            }
          >
            新增定级评估考核
          </Button>

          <Button
            type="primary"
            icon={<PlusOutlined />}
            size="large"
            className="second-button"
            onClick={() =>
              navigate("/management/index/create/" + ASS_INDEX_TYPE.OPERATION)
            }
          >
            新增运行评估考核
          </Button>
        </div>
      }
    >
      <div className={style.filter}>
        <Form
          form={form}
          layout="inline"
          className="inline-form"
          onValuesChange={debounceSearch}
        >
          <Form.Item label="考核类别">
            <div className="w160">
              <Form.Item noStyle name="type">
                <Select
                  allowClear
                  placeholder="请选择"
                  options={ASSESSMENT_TYPE_OPTIONS}
                />
              </Form.Item>
            </div>
          </Form.Item>
          <Form.Item label="发布状态">
            <div className="w160">
              <Form.Item noStyle name="status">
                <Select
                  allowClear
                  placeholder="请选择"
                  options={PUBLISH_STATUS_OPTIONS}
                />
              </Form.Item>
            </div>
          </Form.Item>
          <Form.Item label="搜索" name="searchKey">
            <Input allowClear className="w160" placeholder="请输入考核名称" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" onClick={getList}>
              查询
            </Button>
          </Form.Item>
        </Form>
      </div>

      <div className={style.table}>
        <Table
          loading={loading}
          className={classNames("cus-table large")}
          dataSource={list}
          rowKey="id"
          scroll={{ x: "max-content" }}
          columns={[
            {
              title: "名称",
              dataIndex: "name",
              align: "center",
              minWidth: 100,
            },
            {
              title: "类别",
              align: "center",
              minWidth: 100,
              render: (item: IManageIndexDetail) => {
                return ASSESSMENT_TYPE_OPTIONS.find(
                  (i) => i.value === item.type
                )?.label;
              },
            },
            {
              title: "说明",
              dataIndex: "remark",
              align: "center",
              minWidth: 100,
              ellipsis: true,
            },
            {
              title: "考核周期",
              align: "center",
              minWidth: 100,
              render: (item: IManageIndexDetail) => {
                return `${item.dateStart}-${item.dateEnd}`;
              },
            },
            {
              title: "发布状态",
              align: "center",
              minWidth: 100,
              render: (item: IManageIndexDetail) => {
                return (
                  <p style={{ color: PUBLISH_STATUS_MAP[item.status].color }}>
                    {PUBLISH_STATUS_MAP[item.status].label}
                  </p>
                );
              },
            },
            {
              title: "编辑时间",
              dataIndex: "updateTime",
              align: "center",
              minWidth: 160,
            },
            {
              title: "编辑人",
              dataIndex: "creatorName",
              align: "center",
              minWidth: 100,
            },
            {
              title: "操作",
              align: "center",
              fixed: "right",
              render: (item: IManageIndexDetail) => {
                return (
                  <DageTableActions
                    onEdit={() =>
                      navigate(`/management/index/edit/${item.type}/${item.id}`)
                    }
                    onDelete={handleDelete.bind(undefined, item)}
                    renderBefore={
                      <>
                        <Button
                          type="text"
                          className={style.button}
                          onClick={() => navigate("/management/index/detail/1")}
                        >
                          查看
                        </Button>
                        <Button
                          type="text"
                          className={style.button}
                          onClick={() =>
                            navigate(
                              `/management/index/setting-index/${item.type}/${item.id}`
                            )
                          }
                        >
                          设置指标
                        </Button>
                        <Button
                          type="text"
                          className={style.button}
                          onClick={() =>
                            navigate("/management/index/setting-role")
                          }
                        >
                          设置角色
                        </Button>
                      </>
                    }
                  />
                );
              },
            },
          ]}
          pagination={{
            showQuickJumper: true,
            position: ["bottomCenter"],
            showSizeChanger: true,
            current: params.pageNum,
            pageSize: params.pageSize,
            total,
            onChange: paginationChange(),
          }}
        />
      </div>
    </PageContainer>
  );
};

export default ManagementIndexPage;
