"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.useGroupRowDragEnd = useGroupRowDragEnd;
const React = __importStar(require("react"));
const i18n_1 = __importDefault(require("../../../../../../../../locales/i18n.js"));
const cn_ui_1 = require("@cainiaofe/cn-ui");
const birda_request_1 = require("../../../../../../../../plugins/cn-ai-table-plugin/service/birda-request.js");
const drag_utils_1 = require("../../../drag-utils");
const find_row_group_1 = require("../utils/find-row-group");
const primary_key_1 = require("../../../../../../../../cn-ai-table/view/utils/primary-key");
async function persistCrossGroupMove(props) {
    var _a, _b, _c;
    const { dataModel, activeRow, groupingField, targetGroupValue } = props;
    const pk = dataModel.primaryKey || primary_key_1.DEFAULT_PRIMARY_KEY;
    const rowPk = (0, primary_key_1.getRowKeyStrict)(activeRow.original, pk);
    if (rowPk == null) {
        // if (process.env.NODE_ENV !== 'production') {
        //   // eslint-disable-next-line no-console
        //   console.warn(
        //     '[cn-ai-table] persistCrossGroupMove: activeRow lacks a valid primaryKey value; aborting cross-group move',
        //   );
        // }
        cn_ui_1.CnMessage.error(i18n_1.default.get({ id: 'UpdateFailed', dm: '更新失败' }));
        return;
    }
    const updatedRecord = {
        ...activeRow.original,
        [groupingField]: targetGroupValue,
    };
    const recordConfig = dataModel.recordOperationRequestConfig;
    if (!((_a = recordConfig === null || recordConfig === void 0 ? void 0 : recordConfig.update) === null || _a === void 0 ? void 0 : _a.requestConfig)) {
        cn_ui_1.CnMessage.error(i18n_1.default.get({
            id: 'UpdateRecordInterfaceNotConfigur_1395299626',
            dm: '未配置更新记录接口',
        }));
        return;
    }
    const updateResponse = await (0, birda_request_1.updateRecord)({
        ...recordConfig.update.requestConfig,
        data: updatedRecord,
    });
    if (!updateResponse) {
        cn_ui_1.CnMessage.error(i18n_1.default.get({ id: 'UpdateFailed', dm: '更新失败' }));
        return;
    }
    if ((_b = recordConfig === null || recordConfig === void 0 ? void 0 : recordConfig.getOne) === null || _b === void 0 ? void 0 : _b.requestConfig) {
        const fullRecord = await (0, birda_request_1.queryRecord)({
            configs: recordConfig.getOne.requestConfig,
            id: rowPk,
        });
        const recordData = ((_c = fullRecord === null || fullRecord === void 0 ? void 0 : fullRecord.data) === null || _c === void 0 ? void 0 : _c.data) || (fullRecord === null || fullRecord === void 0 ? void 0 : fullRecord.data) || fullRecord;
        if (recordData) {
            dataModel.updateRow(rowPk, recordData);
            cn_ui_1.CnMessage.success(i18n_1.default.get({ id: 'MoveSuccessfully', dm: '移动成功' }));
        }
    }
    else {
        dataModel.updateRow(rowPk, updatedRecord);
        cn_ui_1.CnMessage.success(i18n_1.default.get({ id: 'MoveSuccessfully', dm: '移动成功' }));
    }
}
/**
 * 分组表行拖拽结束：同组内重排 rawData，跨组则请求更新分组字段。
 */
function useGroupRowDragEnd(props) {
    const { table, dataModel, grouping } = props;
    const pk = dataModel.primaryKey || primary_key_1.DEFAULT_PRIMARY_KEY;
    return React.useCallback(async (activeId, overId) => {
        const activeInfo = (0, find_row_group_1.findRowGroupByPrimaryKey)(table, pk, activeId);
        const overInfo = (0, find_row_group_1.findRowGroupByPrimaryKey)(table, pk, overId);
        if (!activeInfo || !overInfo) {
            return;
        }
        const { row: activeRow, groupRow: activeGroupRow } = activeInfo;
        const { groupRow: overGroupRow } = overInfo;
        const groupingField = grouping[0];
        if (!groupingField) {
            return;
        }
        const isCrossGroupDrag = (activeGroupRow === null || activeGroupRow === void 0 ? void 0 : activeGroupRow.id) !== (overGroupRow === null || overGroupRow === void 0 ? void 0 : overGroupRow.id);
        if (isCrossGroupDrag && overGroupRow) {
            try {
                await persistCrossGroupMove({
                    dataModel,
                    activeRow,
                    groupingField,
                    targetGroupValue: overGroupRow.getValue(groupingField),
                });
            }
            catch {
                cn_ui_1.CnMessage.error(i18n_1.default.get({ id: 'ErrorOccurred', dm: '发生错误' }));
            }
            return;
        }
        const newData = (0, drag_utils_1.handleRowDragSort)(dataModel.rawData, activeId, overId, pk);
        if (newData) {
            dataModel.setRawData(newData);
        }
    }, [table, dataModel, grouping, pk]);
}
