import * as React from 'react';
import $i18n from '../../../../../../../../locales/i18n.js';
import { CnMessage } from '@cainiaofe/cn-ui';
import { updateRecord, queryRecord } from '../../../../../../../../plugins/cn-ai-table-plugin/service/birda-request.js';
import { handleRowDragSort } from '../../../drag-utils';
import { findRowGroupByPrimaryKey } from '../utils/find-row-group';
import { DEFAULT_PRIMARY_KEY, getRowKeyStrict, } from '../../../../../../../../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 || DEFAULT_PRIMARY_KEY;
    const rowPk = 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',
        //   );
        // }
        CnMessage.error($i18n.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)) {
        CnMessage.error($i18n.get({
            id: 'UpdateRecordInterfaceNotConfigur_1395299626',
            dm: '未配置更新记录接口',
        }));
        return;
    }
    const updateResponse = await updateRecord({
        ...recordConfig.update.requestConfig,
        data: updatedRecord,
    });
    if (!updateResponse) {
        CnMessage.error($i18n.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 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);
            CnMessage.success($i18n.get({ id: 'MoveSuccessfully', dm: '移动成功' }));
        }
    }
    else {
        dataModel.updateRow(rowPk, updatedRecord);
        CnMessage.success($i18n.get({ id: 'MoveSuccessfully', dm: '移动成功' }));
    }
}
/**
 * 分组表行拖拽结束：同组内重排 rawData，跨组则请求更新分组字段。
 */
export function useGroupRowDragEnd(props) {
    const { table, dataModel, grouping } = props;
    const pk = dataModel.primaryKey || DEFAULT_PRIMARY_KEY;
    return React.useCallback(async (activeId, overId) => {
        const activeInfo = findRowGroupByPrimaryKey(table, pk, activeId);
        const overInfo = 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 {
                CnMessage.error($i18n.get({ id: 'ErrorOccurred', dm: '发生错误' }));
            }
            return;
        }
        const newData = handleRowDragSort(dataModel.rawData, activeId, overId, pk);
        if (newData) {
            dataModel.setRawData(newData);
        }
    }, [table, dataModel, grouping, pk]);
}
