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

// 主组件
const AssetManagementTable = () => {
  const [draftParams, setDraftParams] = useState({
    visible: false,
    dirId: "",
    draftId: "",
    templateType: "",
  });
  const [importModalVisible, setImportModalVisible] = useState(false);

  const sendFlow = (id = "") => {
    let reason = "";
    const confirmed = modal.confirm({
      title: "请输入送审原因",
      content: <Input onChange={(e) => (reason = e.target.value)} />,
      onOk: () => {
        if (reason?.trim() === "") return showMessage("warn", "请输入送审原因");
        batchPublish(id ? id : selectedRowKeys, reason);
        confirmed.destroy();
      },
    });
  };

  const {
    loading,
    templates,
    currentTemplate,
    setCurrentTemplate,
    columns,
    setParams,
    pagination,
    setPagination,
    dataLoading,
    draftData,
    getDraftData,
    selectedRowKeys,
    setSelectedRowKeys,
    batchDelete,
    batchPublish,
  } = useGetAssetDraft({ setDraftParams, sendFlow });
  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);
    },
    selectedRowKeys,
  };

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

  const handleExportDraft = () => {
    const payload = {
      draftIds: selectedRowKeys,
    };

    window.open(
      `/api/dataassetmanager/draftApi/exportByDraftIds?${qs.stringify(payload, {
        arrayFormat: "repeat",
      })}&templateType=${currentTemplate}`
    );
  };

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

  // 能否送审
  const canFlow = useMemo(() => {
    if (selectedRowKeys?.length === 0) return true;
    let isFlow = false;
    draftData?.forEach((item) => {
      if (item.draftState !== "draft" && selectedRowKeys?.includes(item.id)) {
        isFlow = true;
      }
    });
    return isFlow;
  }, [selectedRowKeys, draftData]);

  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={canFlow}
            type="primary"
            onClick={() => {
              sendFlow();
            }}
          >
            送审
          </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;
