import { useEffect, useState } from "react";
import { Tooltip, Typography, Button, Tag, Popconfirm, message } from "antd";
import {
  getTemplates,
  getDraftDataAsset,
  listFilterElementsGroupByType,
  deleteDraftDataAsset,
  auditDraftDataAsset,
} from "../../../../service/dataassetmanager";
import { AssetItem } from "../../AssetManage/Component/AssetTable";
import { showMessage, showErrorNotifaction } from "../../../../util";
import LocalStorage from "local-storage";
import { appId } from "../../../../App";
const { Text } = Typography;

// ../standardmanage/hooks/sourceMap
export function useGetAssetDraft({ setDraftParams }) {
  const [loading, setLoading] = useState(false);
  const [templates, setTemplates] = useState();
  const [currentTemplate, setCurrentTemplate] = useState();
  const [columns, setColumns] = useState([]);
  const [params, setParams] = useState({
    state: "",
  });
  const [pagination, setPagination] = useState({
    pageNum: 1,
    pageSize: 10,
    total: 0,
  });
  const [dataLoading, setDataLoading] = useState(false);
  const [draftData, setDraftData] = useState();
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);

  // 批量删除
  const batchDelete = async (id = "") => {
    try {
      await deleteDraftDataAsset({
        data: id ? id : selectedRowKeys,
      });
      showMessage("success", "删除成功");
      setSelectedRowKeys([]);
      getDraftData();
    } catch (error) {
      console.log("error", error);
      let message = error?.ApiError?.cnMessage || "操作失败，请稍后再试";
      showErrorNotifaction("提示", message, 3);
    }
  };
  // 批量送审
  const batchPublish = async (id = "") => {
    try {
      await auditDraftDataAsset({
        draftIds: id ? id : selectedRowKeys,
      });
      showMessage("success", "送审成功");
      setSelectedRowKeys([]);
      getDraftData();
    } catch (error) {
      console.log("error", error);
      let message = error?.ApiError?.cnMessage || "操作失败，请稍后再试";
      showErrorNotifaction("提示", message, 3);
    }
  };

  const getTemplatesList = async () => {
    try {
      setLoading(true);
      const res = await getTemplates();
      setTemplates(res);
      setCurrentTemplate(res?.[0]?.type);
      LocalStorage.set(`templateType-${appId}`, res?.[0]?.type);
      let event = new Event("storage");
      event.key = "assetTemplateChange";
      window?.dispatchEvent(event);
      setLoading(false);
    } catch (error) {
      setLoading(false);
    }
  };
  // 获取模板
  useEffect(() => {
    getTemplatesList();
  }, []);

  const getColumns = async () => {
    try {
      const data = await listFilterElementsGroupByType({
        templateType: currentTemplate,
        isAdmin: true,
      });
      let _columns = [];
      let index = 0,
        _metadataIndex = "";
      (data || []).forEach((group) => {
        (group.names || []).forEach((name, i) => {
          index++;
          const params = {
            title: name,
            dataIndex: `element${index}`,
            ellipsis: true,
            render: (text, record) => {
              return (
                <Tooltip title={text || ""}>
                  <Text ellipsis={true}>{text || ""}</Text>
                </Tooltip>
              );
            },
          };
          // if (name === "编号") {
          //   params.width = 60;
          //   // params.fixed = 'left';
          // } else if (name === "中文名称") {
          //   params.width = 160;
          //   // params.fixed = 'left';
          // } else if (name === "英文名称") {
          //   // params.fixed = 'left';
          //   // params.render = (text, record) => {
          //   //   return (
          //   //     <Tooltip title={text||''}>
          //   //       <a onClick={()=>{detailAsset(record);}}>
          //   //       {text||''}
          //   //       </a>
          //   //     </Tooltip>
          //   //   );
          //   // }
          if (name === "资产项") {
            // params.width = 120;
            params.render = (metadata, _) => {
              return <AssetItem metadata={metadata} />;
            };
            _metadataIndex = `element${index}`;
          } else if (name === "资产目录路径") {
            params.render = (text, record) => {
              return (
                <Tooltip title={text || ""}>
                  <Text ellipsis={true}>
                    <a
                      onClick={() => {
                        let event = new Event("storage");
                        event.key = "assetDirChangeEvent";
                        event.dirId = record.dirId || "";
                        window?.dispatchEvent(event);
                      }}
                    >
                      {text || ""}
                    </a>
                  </Text>
                </Tooltip>
              );
            };
          }

          _columns.push(params);
        });
      });

      // 添加草稿操作列
      _columns.push({
        title: "草稿操作",
        dataIndex: "operationType",
        key: "operationType",
        render: (text, record) => {
          let statusText = "";
          let color = "";
          switch (text) {
            case "change":
              statusText = "修改";
              color = "orange";
              break;
            case "release":
              statusText = "新增";
              color = "green";
              break;
            case "offline":
              statusText = "下线";
              color = "grey";
              break;
            case "delete":
              statusText = "删除";
              color = "red";
              break;
            default:
              statusText = text || "-";
          }
          return <Tag color={color}>{statusText}</Tag>;
        },
      });

      // 添加草稿状态列
      _columns.push({
        title: "草稿状态",
        dataIndex: "draftState",
        key: "draftState",
        render: (text, record) => {
          let statusText = "";
          let color = "";
          switch (text) {
            case "draft":
              statusText = "草稿";
              color = "orange";
              break;
            case "auditing":
              statusText = "审核中";
              color = "green";
              break;
            default:
              statusText = text || "未设置";
          }
          return <Tag color={color}>{statusText}</Tag>;
        },
      });

      // 添加操作列
      _columns.push({
        title: "操作",
        key: "action",
        width: 160,
        render: (text, record) => {
          const disabled = record?.draftState !== "draft";

          const handleEdit = (record) => {
            // 编辑操作逻辑
            console.log("编辑记录:", record);
            setDraftParams({
              visible: true,
              dirId: record?.dirId,
              draftId: record?.id,
              templateType: currentTemplate,
            });
          };
          return (
            <div>
              <Popconfirm
                title="确认送审吗？"
                onConfirm={() => {
                  batchPublish([record?.id]);
                }}
              >
                <Button disabled={disabled} type="link" size="small">
                  送审
                </Button>
              </Popconfirm>
              <Button
                size="small"
                waring
                disabled={disabled}
                type="link"
                onClick={() => {
                  handleEdit(record);
                }}
              >
                编辑
              </Button>
              <Popconfirm
                title="确认删除草稿？"
                onConfirm={() => {
                 batchPublish([record?.id]);
                }}
              >
                <Button disabled={disabled} size="small" type="link" danger>
                  删除
                </Button>
              </Popconfirm>
            </div>
          );
        },
      });
      setColumns(_columns);
    } catch (error) {
      console.error("获取列配置失败:", error);
    }
  };

  useEffect(() => {
    if (currentTemplate) {
      getColumns();
    }
  }, [currentTemplate]);

  const getDraftData = async () => {
    try {
      // 设置数据加载状态为true，表示开始加载
      setDataLoading(true);
      const data = await getDraftDataAsset({
        ...pagination,
        ...params,
        templateType: currentTemplate,
        total: undefined,
      });

      const _assets = [];

      (data.data || []).forEach((asset) => {
        let _asset = { ...asset },
          index = 0;
        (asset.elementValues || []).forEach((elementValue) => {
          (elementValue.values || []).forEach((value, i) => {
            index++;
            let metadata = {};
            try {
              metadata = JSON.parse(value);
              _asset["metadata"] = metadata;
              _asset[`element${index}`] = metadata;
            } catch (error) {
              metadata = value;
              _asset["metadata"] = metadata;
              _asset[`element${index}`] = metadata;
            }
          });
        });

        _assets.push(_asset);
      });

      setDraftData(_assets);
      setPagination((pre) => ({
        ...pre,
        total: data?.total,
      }));
      setDataLoading(false);
    } catch (error) {
      setDataLoading(false);
    } finally {
    }
  };

  useEffect(() => {
    if (currentTemplate) {
      getDraftData();
    }
  }, [currentTemplate, pagination.pageNum, pagination.pageSize, params]);

  return {
    loading,
    templates,
    currentTemplate,
    setCurrentTemplate,
    columns,
    setParams,
    pagination,
    setPagination,
    dataLoading,
    draftData,
    getDraftData,
    selectedRowKeys,
    setSelectedRowKeys,
    batchDelete,
    batchPublish,
  };
}
