import React, { useCallback, useState, useMemo } from "react";
import {
  Table,
  Button,
  Space,
  Input,
  Select,
  Tag,
  Modal,
  Pagination,
} from "antd";
import { ExclamationCircleFilled } from "@ant-design/icons";
import { useGetAssetDraft } from "../hooks/assetData";
import { debounce } from "lodash";
import { appId } from "../../../../App";
import AssetDetailDrawer from "../../AssetManage/Component/AssetDetailDrawer";
import ImportModal from "./ImportModal";
import LocalStorage from "local-storage";
import "./index.less";

// 主组件
const AssetManagementTable = () => {
  const [draftParams, setDraftParams] = useState({
    visible: false,
    dirId: "",
    draftId: "",
    templateType: "",
  });
  const [importModalVisible, setImportModalVisible] = useState(false);
  const {
    loading,
    templates,
    currentTemplate,
    setCurrentTemplate,
    columns,
    setParams,
    pagination,
    setPagination,
    dataLoading,
    draftData,
    getDraftData,
    selectedRowKeys,
    setSelectedRowKeys,
    batchDelete,
    batchPublish,
  } = useGetAssetDraft({ setDraftParams });
  const [modal, contextHolder] = Modal.useModal();
  const changeTemplate = (value) => {
    LocalStorage.set(`templateType-${appId}`, value);
    setCurrentTemplate(value);
  };

  // 防抖更新查询条件
  const debouncedChangeParams = useCallback(
    debounce((key, value) => {
      setParams((prev) => ({
        ...prev,
        [key]: value,
      }));
    }, 500), // 500ms 防抖时间
    []
  );

  const changeParams = (key, value) => {
    debouncedChangeParams(key, value);
  };

  const handlePageChange = (page, size) => {
    setPagination((prev) => ({
      ...prev,
      pageNum: page,
      pageSize: size,
    }));
  };

  const rowSelection = {
    onChange: (selectedRowKeys) => {
      setSelectedRowKeys(selectedRowKeys);
    },
  };

  const showConfirm = (type) => {
    const confirmed = modal.confirm({
      title: "提示",
      content: `确认${type}选中的草稿吗？`,
      onOk: () => {
        if (type === "删除") {
          batchDelete();
        } else if (type === "送审") {
          batchPublish();
        }
        confirmed.destroy();
      },
    });
  };

  const handleExportDraft = () => {
    window.open(
      `/api/dataassetmanager/draftApi/exportByDraftIds?dataAssetIds=${selectedRowKeys.join(
        ","
      )}&templateType=${currentTemplate}`
    );
  };

  const hasItems = useMemo(() => {
    return selectedRowKeys.length === 0;
  }, [selectedRowKeys]);

  return (
    <div style={{ background: "#fff" }} className="container">
      {/* 操作按钮区域 */}
      <div
        style={{
          marginBottom: 16,
          display: "flex",
          justifyContent: "space-between",
          flexWrap: "wrap",
        }}
      >
        <Space>
          <Select
            loading={loading}
            style={{ width: 100 }}
            options={templates}
            fieldNames={{ label: "name", value: "type" }}
            value={currentTemplate}
            onChange={changeTemplate}
          />
          <Button
            onClick={() => {
              setImportModalVisible(true);
            }}
          >
            批量修改
          </Button>
          <Button disabled={hasItems} onClick={handleExportDraft}>
            导出
          </Button>
          <Button
            disabled={hasItems}
            type="primary"
            onClick={() => {
              showConfirm("送审");
            }}
          >
            送审
          </Button>
          <Button
            disabled={hasItems}
            danger
            onClick={() => {
              showConfirm("删除");
            }}
          >
            删除
          </Button>
        </Space>

        <Space>
          <Select
            placeholder="请选择状态"
            style={{ width: 120 }}
            allowClear
            options={[
              { label: "草稿", value: "draft" },
              { label: "审核中", value: "auditing" },
            ]}
            onChange={(value) => {
              changeParams("state", value);
            }}
          />
          {/* <Select placeholder="请选择搜索属性" style={{ width: 140 }}>
            <Option value="id">资产编号</Option>
            <Option value="engName">资产英文名</Option>
            <Option value="chnName">资产中文名</Option>
            <Option value="assetItem">资产项</Option>
          </Select> */}

          <Input
            placeholder="请输入关键字"
            style={{ width: 200 }}
            allowClear
            onChange={(e) => {
              changeParams("keyword", e.target.value);
            }}
          />
        </Space>
      </div>

      {/* 表格区域 */}
      <Table
        // rowSelection={rowSelection}
        columns={columns ?? []}
        dataSource={draftData ?? []}
        loading={dataLoading}
        pagination={null}
        size="middle"
        scroll={{ x: true }}
        rowSelection={rowSelection}
        rowKey={"id"}
      />
      <Pagination
        style={{ margin: "12px auto", textAlign: "center" }}
        showTotal={(total) => `共 ${total} 条记录`}
        showSizeChanger
        showQuickJumper
        pageSize={pagination.pageSize}
        current={pagination.pageNum}
        onChange={handlePageChange}
        onShowSizeChange={handlePageChange}
        total={pagination.total}
      />

      <AssetDetailDrawer
        {...draftParams}
        onCancel={() => {
          getDraftData();
          setDraftParams({
            visible: false,
            dirId: "",
            draftId: "",
            templateType: "",
          });
        }}
      />

      <ImportModal
        visible={importModalVisible}
        onCancel={() => {
          setImportModalVisible(false);
        }}
        onSuccess={() => {
          getDraftData();
          setImportModalVisible(false);
        }}
      />
      {contextHolder}
    </div>
  );
};

export default AssetManagementTable;
