import classNames from "classnames";
import { useCallback, useEffect, useMemo, useState } from "react";
import { Button, Form, Input, Table } from "antd";
import { useNavigate } from "react-router-dom";
import { DageTableActions } from "@dage/pc-components";
import { PageContainer } from "@/components";
import style from "../../Management/Form/index.module.scss";
import { deleteReportApi, getReportApi, getReportListApi } from "@/api";
import { IRepoListParams } from "@/types";
import { debounce } from "lodash";
import { ChooseFormModal } from "./components/ChooseFormModal";
// @ts-ignore
import htmlDocx from "html-docx-js/dist/html-docx";
import { saveAs } from "file-saver";

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

const ManagementEvaluationPage = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [params, setParams] = useState<IRepoListParams>({
    ...DEFAULT_PARAMS,
  });
  const [total, setTotal] = useState(0);
  const [list, setList] = useState([]);
  const [chooseFormVisible, setChooseFormVisible] = useState(false);

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

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

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

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

  const handleExport = async (id: number) => {
    const data = await getReportApi(id);
    const docx = htmlDocx.asBlob(data.rtf);
    saveAs(docx, `${data.name}.docx`);
  };

  const handleDelete = async (id: number) => {
    await deleteReportApi(id);
    getList();
  };

  return (
    <PageContainer title="考核评定">
      <div className={style.filter}>
        <Form
          layout="inline"
          className="inline-form"
          onValuesChange={debounceSearch}
        >
          <Form.Item label="搜索" name="searchKey">
            <Input placeholder="请输入报告标题" className="w160" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" onClick={getList}>
              查询
            </Button>
          </Form.Item>
          <Form.Item>
            <Button
              type="primary"
              ghost
              onClick={() => setChooseFormVisible(true)}
            >
              生成报告
            </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: "编辑时间",
              dataIndex: "updateTime",
              align: "center",
              minWidth: 100,
            },
            {
              title: "编辑人",
              dataIndex: "creatorName",
              align: "center",
              minWidth: 100,
            },
            {
              title: "操作",
              align: "center",
              fixed: "right",
              render: (item: any) => {
                return (
                  <DageTableActions
                    renderBefore={
                      <Button
                        size="small"
                        type="link"
                        onClick={handleExport.bind(undefined, item.id)}
                      >
                        导出
                      </Button>
                    }
                    onDelete={handleDelete.bind(undefined, item.id)}
                    onEdit={() => navigate("/perfomance/form/edit/" + item.id)}
                  />
                );
              },
            },
          ]}
          pagination={{
            showQuickJumper: true,
            position: ["bottomCenter"],
            showSizeChanger: true,
            current: params.pageNum,
            pageSize: params.pageSize,
            total,
            onChange: paginationChange(),
          }}
        />
      </div>

      <ChooseFormModal
        open={chooseFormVisible}
        onOk={(id) => {
          navigate(`/perfomance/form/create/${id}`);
        }}
        onCancel={() => setChooseFormVisible(false)}
      />
    </PageContainer>
  );
};

export default ManagementEvaluationPage;
