/**
 * 报表下推参数应用, __push: 数组或单项, 下推类型默认 空(即查询)
 * {
        "__push": {
           "dataset": "dsStock",
            pushType:"add",
            data:[]
        }
    }
 * 
 */
import { $CONST } from "@birt/funclib/ConstUtil";

export default {
    data() {
        return {
            pushData: {}
        };
    },
    computed: {},
    watch: {
        param(val) {
            this._applyPushParam(val);
            this.reRenderDesignSheet();
        }
    },
    methods: {
        // 应用查询面板初始化参数
        _applyQueryModelParam(param = {}) {
            let val = param[$CONST.LOOKUPINPUTKEY];
            if (val) {
                for (let dsId in this.dataset) {
                    let ds = this.dataset[dsId];
                    let recvField = ds && ds.getReceiveLookupInput();
                    if (recvField) {
                        let queryModel = {};
                        queryModel[recvField] = val;
                        ds.setQueryModel(queryModel, recvField)
                    }
                }
            }
        },
        // 应用下推参数,newStores是标记刚创建的数据集，只有在这个列表的才应用下推
        async _applyPushParam(param, newStores) {
            debugger
            if (!param) return;
            let pushCdion = [];
            let recvCdions = [];
            let pushParam = param.__push;
            if (pushParam) {
                // 应用下推条件
                if (Array.isArray(pushParam)) {
                    pushParam.forEach(item => {
                        this._applyPushItem(item, pushCdion, newStores);
                    })
                } else {
                    this._applyPushItem(pushParam, pushCdion, newStores);
                }
            } else {
                // 应用自动接收参数 
                recvCdions = this.getReceiveCdions(param, newStores);
            }
            // 处理批量加载报表数据
            let url = this._getPushUrl(param) || this.loadUrl;
            await this._loadPushDataByCdions(url, pushCdion.concat(recvCdions));
        },
        // 应用单个下推包
        _applyPushItem(item, pushCdion, newStores) {
            if (typeof item == "string") {
                item = JSON.parse(item);
            }
            let pushType = item[$CONST.PUSHTYPE];
            if (pushType == $CONST.PUSHADD) {
                this._applyPushItemAdd(item);
            } else if (pushType == $CONST.PUSHDELETE) {
                this._applyPushItemDelete(item);
            } else if (pushType == $CONST.PUSHCDION) {
                // 下推条件处理
                this._applyPushItemCdion(item, pushCdion);
            } else {
                this._applyPushItemData(item, newStores);
            }
            // 附加__push下推条件
            let recvCdions = this.getReceiveCdions(item, newStores);
            pushCdion.push(...recvCdions);
        },
        // 应用单个下推新增
        _applyPushItemAdd(item) {
            let dsId = this._getPushDatasetId(item);
            if (dsId) {
                let store = this.getStore(dsId);
                if (store) {
                    let pushAddType = item[$CONST.PUSHADDTYPE];
                    let pushData = this._getPushData(item);
                    if (pushData && pushData.length > 0) {
                        if (pushAddType == $CONST.PUSHADDMAP) {
                            // returnFields 映射方式下推新增
                            store.clear();
                            store.add(pushData);
                        } else {
                            // 应用下推数据包，当前数据集自动填充
                            let newRecds = [];
                            pushData.forEach(puRecd => {
                                let newR = store.newRecord(puRecd, item);
                                newRecds.push(newR);
                            })
                            store.add(newRecds);
                        }
                    }
                }
            }
        },
        // 应用单个下推删除
        _applyPushItemDelete(item) {
            let dsId = this._getPushDatasetId(item);
            if (dsId) {
                let store = this.getStore(dsId);
                if (store) {
                    let pushData = this._getPushData(item);
                    if (pushData && pushData.length > 0) {
                        // 加载要删除的数据
                        store.loadData(pushData);
                        store.remove(pushData);
                    }
                }
            }
        },
        // 应用单个下推条件
        _applyPushItemCdion(item, pushCdion) {
            let dsId = this._getPushDatasetId(item);
            let pushParam = this._getPushCdion(item);
            if (dsId && pushParam) {
                let store = this.getStore(dsId);
                if (store) {
                    let queryParam = store.getQueryParam(pushParam);
                    queryParam.dataset = dsId;
                    pushCdion.push(queryParam);
                }
            }
        },
        // 应用单个下推数据包
        _applyPushItemData(item, newStores) {
            let dsId = this._getPushDatasetId(item);
            // 当有标记新创建数据集时，只有新创建数据集应用下推,避免旧数据集重复应用下推
            if (newStores && (newStores.indexOf(dsId) == -1)) return;
            if (dsId) {
                // 根据目标集id,获取下推目标数据集，加上随机数后获取不到，暂时先去掉模板拼接随机数
                let store = this.getStore(dsId);
                if (store) {
                    let pushData = this._getPushData(item);
                    if (pushData && pushData.length > 0) {
                        store.loadData(pushData);
                    }
                }
            }
        },
        // 根据数据集查询条件集合，批量查询下推数据
        async _loadPushDataByCdions(url, cdions) {
            // 当没条件时，可能错失加载所有数据
            if (cdions.length > 0) {
                let param = { __body: JSON.stringify(cdions) };

                // 执行查询
                await this.axios.post(url, param)
                    .then(response => {
                        this._loadStoresPushData(cdions, response);
                    })
                    .catch(error => {
                        console.error(error);
                    });
            }
        },
        // 加载返回的下推数据包
        _loadStoresPushData(cdions, pushData) {
            if (cdions.length === pushData.dataPack.length) {
                debugger
                for (let i = 0, l = cdions.length; i < l; i++) {
                    let cdItem = cdions[i];
                    let dsId = this._getPushDatasetId(cdItem);
                    let ds = this.getStore(dsId);
                    if (ds) {
                        let resi = pushData.dataPack[i];
                        let option = {};
                        if (resi[$CONST.OUTPARAMETER]) {
                            option.recordCount = resi[$CONST.OUTPARAMETER][$CONST.TOTALRECORDCOUNT];
                        }
                        ds.resolveLoadData(resi[$CONST.ROWS], option);
                        let itemData = resi.rows;
                        // ds.loadData(itemData);
                        // 下推删除时，数据打上删除状态 rsDelete
                        if (cdItem[$CONST.PUSHTYPE] == $CONST.PUSHDELETE) {
                            ds.remove(itemData, true);
                        }
                    }
                }
            } else {
                console.log("批量查询返回数据包长度误，无法对应.")
            }
        },
        // 获取下推请求路径url
        _getPushUrl(param) {
            if (Array.isArray(param)) {
                return param[0] && param[0].url;
            } else {
                return param.url;
            }
        },
        // 获取下推项获取数据集id
        _getPushDatasetId(item) {
            let dsId = item.dataset;
            if (!dsId) {
                let dsUrl = this._getPushDatasetUrl(item);
                dsId = dsUrl && dsUrl.substring(dsUrl.lastIndexOf("/") + 1, dsUrl.lastIndexOf("."));
            }
            return dsId;
        },
        // 获取下推数据集模型路径
        _getPushDatasetUrl(item) {
            return item.modelFilePath || (item.target && item.target.storeUrl);
        },
        // 获取下推数据包
        _getPushData(item) {
            return item.data || (item.target && item.target.data);
        },
        // 获取下推数据条件
        _getPushCdion(item) {
            return item.param || (item.target && item.target.ps);
        },
        // 添加下推数据包
        _addPushData(dsId, data) {

        },
        // 获取下推数据包
        getPushData() {

        },
        // 设置页面参数
        async setParam(param) {
            this._applyQueryModelParam(param);
            await this._applyPushParam(param);
            this.reRenderDesignSheet();
        },

    }
}