import { Subject } from 'rxjs';
import { ViewTool, Util, ModelTool, LogUtil } from '@ibizstudio/runtime';
import { MDControlBase } from './md-control-base';
import { AppMEditViewPanelService } from '../ctrl-service';
/**
 * 多编辑视图面板部件
 *
 */
export class MEditViewPanelControlBase extends MDControlBase {
    constructor() {
        super(...arguments);
        /**
         * 多编辑表单面板样式(默认行记录)
         *
         * @memberof MEditViewPanelControlBase
         */
        this.panelStyle = 'ROW';
        /**
         * 面板状态订阅对象
         *
         * @public
         * @type {Subject<{action: string, data: any}>}
         * @memberof MEditViewPanelControlBase
         */
        this.panelState = new Subject();
        /**
         * 视图参数对象集合
         *
         * @type {any[]}
         * @memberof MEditViewPanelControlBase
         */
        this.items = [];
        /**
         * 计数器
         *
         * @type number
         * @memberof MEditViewPanelControlBase
         */
        this.count = 0;
        /**
         * 关系实体参数对象
         *
         * @public
         * @type {any[]}
         * @memberof MEditViewPanelControlBase
         */
        this.deResParameters = [];
        /**
         * 当前应用视图参数对象
         *
         * @public
         * @type {any[]}
         * @memberof MEditViewPanelControlBase
         */
        this.parameters = [];
        /**
         * 是否显示底部按钮
         *
         * @public
         * @type {any[]}
         * @memberof MEditViewPanelControlBase
         */
        this.showButton = true;
    }
    /**
     * 部件模型数据初始化
     *
     * @memberof MEditViewPanelControlBase
     */
    async ctrlModelInit(args) {
        var _a;
        await super.ctrlModelInit();
        if (!(this.Environment && this.Environment.isPreviewMode)) {
            this.service = new AppMEditViewPanelService(this.controlInstance, this.context);
        }
        // 加载嵌入视图的数据
        await ((_a = this.controlInstance.getEmbeddedPSAppView()) === null || _a === void 0 ? void 0 : _a.fill());
        this.initParameters();
    }
    /**
     * 多编辑视图面板初始化
     *
     * @memberof MEditViewPanelControlBase
     */
    ctrlInit() {
        super.ctrlInit();
    }
    viewStateAction(tag, action, data) {
        if (!Object.is(tag, this.name)) {
            return;
        }
        super.viewStateAction(tag, action, data);
        if (Object.is(action, 'load')) {
            this.load(data);
        }
        if (Object.is(action, 'save')) {
            this.saveData(data);
        }
    }
    /**
     * 初始化嵌入应用视图及实体参数对象
     *
     * @memberof MEditViewPanelControlBase
     */
    initParameters() {
        var _a, _b, _c;
        const emView = this.controlInstance.getEmbeddedPSAppView();
        const emViewEntity = emView === null || emView === void 0 ? void 0 : emView.getPSAppDataEntity();
        const ctrlParams = (_a = this.controlInstance.getPSControlParam()) === null || _a === void 0 ? void 0 : _a.ctrlParams;
        if (ctrlParams && ctrlParams.SHOWBUTTON) {
            this.showButton = Object.is(ctrlParams.SHOWBUTTON, 'false') ? false : true;
        }
        if (emView && emViewEntity) {
            this.deResParameters = Util.formatAppDERSPath(this.context, emView.getPSAppDERSPaths());
            this.parameters = [
                {
                    pathName: Util.srfpluralize(emViewEntity.codeName).toLowerCase(),
                    parameterName: (_b = emViewEntity.codeName) === null || _b === void 0 ? void 0 : _b.toLowerCase(),
                    srfmajortext: (_c = ModelTool.getAppEntityMajorField(emViewEntity).codeName) === null || _c === void 0 ? void 0 : _c.toLowerCase(),
                },
            ];
        }
        else {
            this.deResParameters = [];
            this.parameters = [];
        }
    }
    /**
     * 保存数据
     *
     * @param {*} [data] 数据
     * @memberof MEditViewPanelControlBase
     */
    saveData(data) {
        var _a;
        this.count = 0;
        if (this.items.length > 0) {
            Object.assign(data, { showResultInfo: false });
            this.panelState.next({ tag: ((_a = this.controlInstance.getEmbeddedPSAppView()) === null || _a === void 0 ? void 0 : _a.name) || '', action: 'save', data: data });
        }
        else {
            this.ctrlEvent({ controlname: this.controlInstance.name, action: 'drdatasaved', data: { action: 'drdatasaved' } });
        }
    }
    /**
     * 数据加载
     *
     * @public
     * @param {*} data 额外参数
     * @memberof MEditViewPanelControlBase
     */
    load(data) {
        if (!this.fetchAction) {
            this.$throw(this.$t('app.multieditview.notconfig.fetchaction'), 'load');
            return;
        }
        let arg = {};
        Object.assign(arg, data, { viewparams: this.viewparams });
        // 清空数据
        this.items = [];
        if (this.service) {
            let tempContext = JSON.parse(JSON.stringify(this.context));
            this.onControlRequset('load', tempContext, arg);
            const promice = this.service.get(this.fetchAction, tempContext, arg, this.showBusyIndicator);
            promice
                .then((response) => {
                var _a;
                this.onControlResponse('load', response);
                if (!response.status || response.status !== 200) {
                    this.$throw(response, 'load');
                    return;
                }
                if (((_a = response === null || response === void 0 ? void 0 : response.data) === null || _a === void 0 ? void 0 : _a.length) > 0) {
                    const items = Util.deepCopy(response.data);
                    this.doItems(items);
                }
                this.ctrlEvent({ controlname: this.controlInstance.name, action: 'load', data: this.items });
            })
                .catch((response) => {
                this.onControlResponse('load', response);
                this.$throw(response, 'load');
            });
        }
    }
    /**
     * 增加数据
     *
     * @memberof MEditViewPanelControlBase
     */
    handleAdd() {
        if (this.Environment && this.Environment.isPreviewMode) {
            return;
        }
        if (!this.loaddraftAction) {
            this.$throw(this.$t('app.multieditview.notconfig.loaddraftaction'), 'handleAdd');
            return;
        }
        let tempContext = JSON.parse(JSON.stringify(this.context));
        let viewparams = JSON.parse(JSON.stringify(this.viewparams));
        this.onControlRequset('handleAdd', tempContext, viewparams);
        const promice = this.service.loadDraft(this.loaddraftAction, tempContext, { viewparams: viewparams }, this.showBusyIndicator);
        promice
            .then((response) => {
            this.onControlResponse('handleAdd', response);
            if (!response.status || response.status !== 200) {
                this.$throw(response, 'handleAdd');
                return;
            }
            const data = response.data;
            this.doItems([data]);
        })
            .catch((response) => {
            this.onControlResponse('handleAdd', response);
            this.$throw(response, 'handleAdd');
        });
    }
    /**
     * 视图数据变更事件
     *
     * @param {*} $event 回调对象
     * @return {*}
     * @memberof MEditViewPanelControlBase
     */
    viewDataChange($event) {
        // todo 统一标准后修改
        if (!$event) {
            return;
        }
        try {
            $event = JSON.parse($event);
        }
        catch (error) {
            return;
        }
        if (Object.is($event.action, 'save')) {
            this.count++;
            if (this.items.length === this.count) {
                this.ctrlEvent({ controlname: this.controlInstance.name, action: 'drdatasaved', data: { action: 'save' } });
            }
        }
        if (Object.is($event.action, 'remove')) {
            // todo R7模板都错的，遇到场景在修改吧
            if ($event.data) {
                let resultIndex = this.items.findIndex((value, index, arr) => {
                    return value['viewdata']['orderdetailtestid'] === $event.data['orderdetailtestid'];
                });
                if (resultIndex !== -1) {
                    this.items.splice(resultIndex, 1);
                }
            }
        }
    }
    /**
     * 视图加载完成
     *
     * @param {*} $event 回调对象
     * @memberof MEditViewPanelControlBase
     */
    viewload($event) {
        LogUtil.log(this.$t('components.appformdruipart.loadcomp'));
    }
    /**
     * 刷新
     *
     * @param {*} [args] 额外参数
     * @memberof MEditViewPanelControlBase
     */
    refresh(args) {
        this.load(args);
    }
    /**
     * 处理数据
     *
     * @public
     * @param {any[]} datas 数据集合
     * @memberof MEditViewPanelControlBase
     */
    doItems(datas) {
        // todo 同类数据处理可以抽个工具类
        const [{ pathName, parameterName }] = this.parameters;
        datas.forEach((arg) => {
            let id = arg[parameterName] ? arg[parameterName] : this.$util.createUUID();
            let item = { id: id, viewdata: {}, viewparam: {} };
            Object.assign(item.viewdata, ViewTool.getIndexViewParam());
            Object.assign(item.viewdata, this.context);
            // 关系应用实体参数
            this.deResParameters.forEach(({ pathName, parameterName }) => {
                if (this.context[parameterName] && !Object.is(this.context[parameterName], '')) {
                    Object.assign(item.viewdata, { [parameterName]: this.context[parameterName] });
                }
                else if (arg[parameterName] && !Object.is(arg[parameterName], '')) {
                    Object.assign(item.viewdata, { [parameterName]: arg[parameterName] });
                }
            });
            // 当前视图参数（应用实体视图）
            this.parameters.forEach(({ pathName, parameterName, srfmajortext }) => {
                if (arg[parameterName] && !Object.is(arg[parameterName], '')) {
                    Object.assign(item.viewdata, { [parameterName]: arg[parameterName] });
                }
                // 当前页面实体主信息
                if (arg[srfmajortext] && !Object.is(arg[srfmajortext], '')) {
                    Object.assign(item, { srfmajortext: arg[srfmajortext] });
                }
            });
            //合并视图参数
            Object.assign(item.viewparam, this.viewparams);
            this.items.push(item);
        });
    }
    ctrlDestroyed() {
        super.ctrlDestroyed();
        this.panelState.complete();
    }
}
