"use strict";
/**
 * 引用字段配置面板
 *
 * 交互流程：
 * 1. 输入字段标题
 * 2. 配置引用关系：选择数据表 → 选择字段
 * 3. 校验并保存配置
 */
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.LookupFieldConfigPanel = LookupFieldConfigPanel;
const react_1 = __importStar(require("react"));
const cn_ui_1 = require("@cainiaofe/cn-ui");
const i18n_1 = __importDefault(require("../../../../../../../locales/i18n.js"));
const services_1 = require("../../../../../../../cn-ai-table/view/services");
const lookup_column_code_1 = require("../../../../../../../cn-ai-table/view/utils/lookup-column-code");
const lookup_field_icon_1 = require("../../../../../../../cn-ai-table/view/constants/lookup-field-icon");
require("./lookup-field-config-panel.scss");
const LOOKUP_FIELD_REF_SEP = '\u001f';
function LookupFieldConfigPanel({ fieldLabel, columnCode: existingColumnCode, initialConfig, isEditStatus, bizRequestConfig, context, onSave, onCancel, }) {
    var _a, _b;
    /** 仅严格 `=== true`；避免低码 JSON 里字符串 `"false"` 被 `Boolean()` 当成 true */
    const hiddenSubTable = ((_a = context === null || context === void 0 ? void 0 : context.lookupFieldConfig) === null || _a === void 0 ? void 0 : _a.hiddenSubTable) === true;
    const subTableUrl = (_b = bizRequestConfig === null || bizRequestConfig === void 0 ? void 0 : bizRequestConfig.subTableConfig) === null || _b === void 0 ? void 0 : _b.url;
    const bizRequestConfigRef = (0, react_1.useRef)(bizRequestConfig);
    bizRequestConfigRef.current = bizRequestConfig;
    const [fieldName, setFieldName] = (0, react_1.useState)((initialConfig === null || initialConfig === void 0 ? void 0 : initialConfig.fieldName) || fieldLabel || '');
    const [sourceTableId, setSourceTableId] = (0, react_1.useState)((initialConfig === null || initialConfig === void 0 ? void 0 : initialConfig.sourceTableId) || '');
    const [targetFieldCode, setTargetFieldCode] = (0, react_1.useState)((initialConfig === null || initialConfig === void 0 ? void 0 : initialConfig.targetFieldCode) || '');
    const [validationError, setValidationError] = (0, react_1.useState)('');
    const [subTables, setSubTables] = (0, react_1.useState)([]);
    const fieldNameInputRef = (0, react_1.useRef)(null);
    (0, react_1.useEffect)(() => {
        const timer = setTimeout(() => {
            var _a, _b;
            if (fieldNameInputRef.current) {
                const inputNode = ((_b = (_a = fieldNameInputRef.current).getInputNode) === null || _b === void 0 ? void 0 : _b.call(_a)) || fieldNameInputRef.current;
                if (inputNode && typeof inputNode.focus === 'function') {
                    inputNode.focus();
                    if (typeof inputNode.select === 'function') {
                        inputNode.select();
                    }
                }
            }
        }, 100);
        return () => clearTimeout(timer);
    }, []);
    const selectedSubTable = subTables.find((item) => item.value === sourceTableId);
    const tableOptions = react_1.default.useMemo(() => {
        const options = subTables.map((item) => ({
            label: item.label,
            value: item.value,
        }));
        const hasCurrent = options.some((item) => item.value === sourceTableId);
        if (!hasCurrent && sourceTableId) {
            options.unshift({
                label: (initialConfig === null || initialConfig === void 0 ? void 0 : initialConfig.sourceTableName) || sourceTableId,
                value: sourceTableId,
            });
        }
        return options;
    }, [initialConfig === null || initialConfig === void 0 ? void 0 : initialConfig.sourceTableName, sourceTableId, subTables]);
    const fieldOptions = react_1.default.useMemo(() => {
        const options = ((selectedSubTable === null || selectedSubTable === void 0 ? void 0 : selectedSubTable.columns) || []).map((item) => ({
            label: item.label,
            value: item.value,
        }));
        const hasCurrent = options.some((item) => item.value === targetFieldCode);
        if (!hasCurrent && targetFieldCode) {
            options.unshift({
                label: (initialConfig === null || initialConfig === void 0 ? void 0 : initialConfig.targetFieldName) || targetFieldCode,
                value: targetFieldCode,
            });
        }
        return options;
    }, [initialConfig === null || initialConfig === void 0 ? void 0 : initialConfig.targetFieldName, selectedSubTable === null || selectedSubTable === void 0 ? void 0 : selectedSubTable.columns, targetFieldCode]);
    const flatFieldOptions = react_1.default.useMemo(() => {
        if (!hiddenSubTable)
            return [];
        return subTables.flatMap((st) => (st.columns || []).map((col) => ({
            label: col.label,
            value: `${st.value}${LOOKUP_FIELD_REF_SEP}${col.value}`,
        })));
    }, [hiddenSubTable, subTables]);
    (0, react_1.useEffect)(() => {
        let cancelled = false;
        const loadSubTableConfig = async () => {
            try {
                const configs = await (0, services_1.querySubTableConfig)(bizRequestConfigRef.current);
                if (!cancelled) {
                    setSubTables(configs || []);
                }
            }
            catch {
                if (!cancelled) {
                    setSubTables([]);
                    cn_ui_1.CnMessage.error(i18n_1.default.get({
                        id: 'FailedToLoadReferenceFieldConfig_146058072',
                        dm: '加载引用字段配置失败，请稍后重试',
                    }));
                }
            }
        };
        loadSubTableConfig();
        return () => {
            cancelled = true;
        };
    }, [subTableUrl]);
    const handleSourceTableChange = (0, react_1.useCallback)((value) => {
        if (isEditStatus)
            return;
        setSourceTableId(value);
        setTargetFieldCode('');
        // TODO: 根据选择的数据表加载字段列表
    }, [isEditStatus]);
    const handleFlatFieldChange = (0, react_1.useCallback)((value) => {
        if (isEditStatus)
            return;
        const i = value.indexOf(LOOKUP_FIELD_REF_SEP);
        if (i === -1) {
            setSourceTableId('');
            setTargetFieldCode('');
            return;
        }
        setSourceTableId(value.slice(0, i));
        setTargetFieldCode(value.slice(i + LOOKUP_FIELD_REF_SEP.length));
    }, [isEditStatus]);
    const flatFieldValue = hiddenSubTable && sourceTableId && targetFieldCode
        ? `${sourceTableId}${LOOKUP_FIELD_REF_SEP}${targetFieldCode}`
        : '';
    const validateForm = () => {
        var _a, _b;
        if (!fieldName.trim()) {
            setValidationError(i18n_1.default.get({ id: 'PleaseEnterAFieldName', dm: '请输入字段名称' }));
            return false;
        }
        if (!sourceTableId) {
            setValidationError(i18n_1.default.get({ id: 'PleaseSelectADataTable', dm: '请选择数据表' }));
            return false;
        }
        if (!targetFieldCode) {
            setValidationError(i18n_1.default.get({ id: 'PleaseSelectAReferenceField', dm: '请选择引用字段' }));
            return false;
        }
        const lookupConfigMap = ((_b = (_a = context === null || context === void 0 ? void 0 : context.dataModel) === null || _a === void 0 ? void 0 : _a.customFields) === null || _b === void 0 ? void 0 : _b.lookupConfig) || {};
        const hasDuplicate = Object.entries(lookupConfigMap).some(([columnCode, item]) => {
            if (existingColumnCode && columnCode === existingColumnCode)
                return false;
            return (item === null || item === void 0 ? void 0 : item.sourceTableId) === sourceTableId && (item === null || item === void 0 ? void 0 : item.targetFieldCode) === targetFieldCode;
        });
        if (hasDuplicate) {
            setValidationError(i18n_1.default.get({ id: 'ThisFieldHasAlreadyBeenAdded', dm: '该字段已经添加' }));
            return false;
        }
        setValidationError('');
        return true;
    };
    const handleSave = () => {
        var _a, _b, _c;
        if (!validateForm())
            return;
        const columnCode = existingColumnCode || (0, lookup_column_code_1.buildLookupColumnCode)(sourceTableId, targetFieldCode);
        const selectedColumn = (_a = selectedSubTable === null || selectedSubTable === void 0 ? void 0 : selectedSubTable.columns) === null || _a === void 0 ? void 0 : _a.find((column) => column.value === targetFieldCode);
        const canSearchRaw = selectedColumn === null || selectedColumn === void 0 ? void 0 : selectedColumn.canSearch;
        const canSearch = canSearchRaw === true ||
            canSearchRaw === 'true' ||
            canSearchRaw === 'TRUE' ||
            canSearchRaw === '1';
        const config = {
            fieldName,
            sourceTableId,
            sourceTableName: (_b = tableOptions.find((t) => t.value === sourceTableId)) === null || _b === void 0 ? void 0 : _b.label,
            targetFieldCode,
            targetFieldName: (_c = fieldOptions.find((f) => f.value === targetFieldCode)) === null || _c === void 0 ? void 0 : _c.label,
            columnCode,
            canSearch,
            model: (selectedColumn === null || selectedColumn === void 0 ? void 0 : selectedColumn.model) || {},
        };
        onSave(config);
    };
    const handleCancel = () => {
        onCancel();
    };
    return (react_1.default.createElement("div", { className: "lookup-field-config-panel" },
        react_1.default.createElement("div", { className: "lookup-field-config-header" },
            react_1.default.createElement("div", { className: "lookup-field-config-header-left" },
                react_1.default.createElement("img", { alt: "", src: lookup_field_icon_1.LOOKUP_FIELD_ICON_URL, width: 16, height: 16, className: "lookup-field-config-header-icon" }),
                react_1.default.createElement("span", { className: "lookup-field-config-title" }, i18n_1.default.get({ id: 'ReferenceField', dm: '引用字段' }))),
            react_1.default.createElement(cn_ui_1.CnIcon, { type: "close", size: "small", onClick: handleCancel, style: { cursor: 'pointer' } })),
        react_1.default.createElement("div", { className: "lookup-field-config-section lookup-field-name-section" },
            react_1.default.createElement(cn_ui_1.CnInput, { ref: fieldNameInputRef, value: fieldName, onChange: setFieldName, placeholder: i18n_1.default.get({ id: 'EnterFieldTitle', dm: '请输入字段标题' }), style: { width: '100%' } })),
        react_1.default.createElement("div", { className: "lookup-field-config-section" },
            react_1.default.createElement("div", { className: "lookup-field-config-label" }, i18n_1.default.get({ id: 'ReferenceFieldConfiguration', dm: '引用字段配置' })),
            react_1.default.createElement("div", { className: "lookup-field-reference-box" },
                react_1.default.createElement("div", { className: "lookup-field-reference-section" },
                    react_1.default.createElement("div", { className: "lookup-field-sub-label" }, i18n_1.default.get({ id: 'FieldToReference', dm: '要引用的字段' })),
                    react_1.default.createElement("div", { className: "lookup-field-reference-selectors" }, hiddenSubTable ? (react_1.default.createElement(cn_ui_1.CnAsyncSelect, { key: `lookup-flat-${subTableUrl !== null && subTableUrl !== void 0 ? subTableUrl : 'none'}-${flatFieldOptions.length}`, showSearch: true, value: flatFieldValue, onChange: handleFlatFieldChange, dataSource: flatFieldOptions, placeholder: i18n_1.default.get({ id: 'SelectField', dm: '选择字段' }), style: { flex: 1 }, hasClear: true, disabled: isEditStatus })) : (react_1.default.createElement(react_1.default.Fragment, null,
                        react_1.default.createElement(cn_ui_1.CnAsyncSelect, { key: `lookup-table-${subTableUrl !== null && subTableUrl !== void 0 ? subTableUrl : 'none'}-${tableOptions.length}`, showSearch: true, value: sourceTableId, onChange: handleSourceTableChange, dataSource: tableOptions, placeholder: i18n_1.default.get({ id: 'SelectDataTable', dm: '选择数据表' }), style: { flex: 1 }, hasClear: true, disabled: isEditStatus }),
                        react_1.default.createElement(cn_ui_1.CnAsyncSelect, { key: `lookup-field-${sourceTableId}-${fieldOptions.length}`, showSearch: true, value: targetFieldCode, onChange: setTargetFieldCode, dataSource: fieldOptions, placeholder: i18n_1.default.get({ id: 'SelectField', dm: '选择字段' }), style: { flex: 1 }, hasClear: true, disabled: !sourceTableId || isEditStatus }))))))),
        validationError && (react_1.default.createElement("div", { className: "lookup-field-config-validation-error" }, validationError)),
        react_1.default.createElement("div", { className: "lookup-field-config-footer" },
            react_1.default.createElement("div", { className: "lookup-field-config-footer-left" }),
            react_1.default.createElement("div", { className: "lookup-field-config-footer-right" },
                react_1.default.createElement(cn_ui_1.CnButton, { onClick: handleCancel }, i18n_1.default.get({ id: 'Cancel', dm: '取消' })),
                react_1.default.createElement(cn_ui_1.CnButton, { type: "primary", onClick: handleSave }, i18n_1.default.get({ id: 'OK', dm: '确定' }))))));
}
