import classNames from "classnames";
import { useCallback, useEffect, useMemo, useState } from "react";
import { Button, Dropdown, 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,
  publishManageIndexApi,
} from "@/api";
import { debounce } from "lodash";
import { ASS_INDEX_TYPE, IManageIndexDetail, PUBLISH_ENUM } 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();
  };

  const handlePublish = async (id: number, stop?: boolean) => {
    await publishManageIndexApi(
      id,
      stop ? PUBLISH_ENUM.ENDED : PUBLISH_ENUM.PUBLISHED
    );
    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) => {
                const isEnded = item.status === PUBLISH_ENUM.ENDED;
                const isPending = item.status === PUBLISH_ENUM.PENDING;
                const showStopBtn = [
                  PUBLISH_ENUM.EVALUATED,
                  PUBLISH_ENUM.PUBLISHED,
                ].includes(item.status);

                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/${item.id}`)
                          }
                        >
                          查看
                        </Button>
                        {isPending && (
                          <Button
                            variant="text"
                            color="primary"
                            className={style.button}
                            onClick={handlePublish.bind(
                              undefined,
                              item.id,
                              false
                            )}
                          >
                            发布
                          </Button>
                        )}
                        {showStopBtn && (
                          <Button
                            variant="text"
                            color="danger"
                            className={style.button}
                            onClick={handlePublish.bind(
                              undefined,
                              item.id,
                              true
                            )}
                          >
                            终止
                          </Button>
                        )}
                        {!isEnded && (
                          <Dropdown
                            placement="bottom"
                            arrow
                            menu={{
                              items: [
                                {
                                  key: 1,
                                  label: (
                                    <p
                                      onClick={() =>
                                        navigate(
                                          `/management/index/setting-index/${item.type}/${item.id}`
                                        )
                                      }
                                    >
                                      考核指标
                                    </p>
                                  ),
                                },
                                {
                                  key: 2,
                                  label: (
                                    <p
                                      onClick={() =>
                                        navigate(
                                          `/management/index/setting-role/${item.type}/${item.id}/${item.status}`
                                        )
                                      }
                                    >
                                      考核角色
                                    </p>
                                  ),
                                },
                              ],
                            }}
                          >
                            <Button type="text" className={style.button}>
                              设置
                            </Button>
                          </Dropdown>
                        )}
                      </>
                    }
                  />
                );
              },
            },
          ]}
          pagination={{
            showQuickJumper: true,
            position: ["bottomCenter"],
            showSizeChanger: true,
            current: params.pageNum,
            pageSize: params.pageSize,
            total,
            onChange: paginationChange(),
          }}
        />
      </div>
    </PageContainer>
  );
};

export default ManagementIndexPage;
