export default {
    bill: null,
    param: null,
    execute: function (bill, param) {
        this.bill = bill
        this.param  = param
        if (GMS && GMS.showDetailAction) {//查看详情，则直接关闭弹出
            GMS.vbus.$emit('closeModal');
            return;
        }
        if (param) {
            bill.setControlsSate(param["_control_name_"], 'enable',false);
            bill.runFormulaCheckData(param.param, function (msg) {
                if (msg.length == 0) {
                    if (param.param && param.param.hasOwnProperty('cacheData') && !param.param.cacheData) {
                        this.saveData(bill, param);
                    } else {
                        let obj = bill.getBuillData();
                        obj.billDefine = param.define;
                        this.execuFormula(obj, param);//点击确定，执行公式
                    }
                } else {
                    GMS.$http.post(`/baseData/data/list`, {
                        pagination: false,
                        tableName: "MD_BILLSTATE_AUDIT",
                        code: '1',
                    }).then((res) => {
                        bill.setControlsSate(param["_control_name_"], 'enable',true);
                        if (res.data.rs.code == 0) {
                            // 给单据赋新的状态值
                            bill.getMasterData().setValue('BILLSTATEAUDIT',res.data.rows[0]);
                        }
                    });
                    GAMS.Common.messagePrompt(msg);
                }
                GMS.$hideContainer.$Spin.hide();
            }.bind(this));
        } else {
            GAMS.Common.messagePrompt('缺少参数');
        }
    },
    saveData(bill, param) {
        let that = this;
        let buidData = bill.getBuillData();
        console.log('buidData:', buidData);
        let controlArr = bill.action.filter(
            (v) => v.execute == "searchBillAction"
        );
        let detailData = [];
        let arrApi1 = [];
        if (controlArr[0].param.field && controlArr[0].param.field.length > 0) {
            let tableList = controlArr[0].param.field.map(v => v.targetTableName);
            tableList = Array.from(new Set(tableList));
            tableList.forEach(v => {
                if (buidData.hasOwnProperty(v)) {
                    for (let i = 0; i < bill.getSubData(v).length; i++) {
                        let rowDataObject = bill.getSubDataRow(v, i);
                        let obj = rowDataObject.getValue("currentRowData");
                        if (obj && obj.BILLDETAILOBJ) {
                            let billId = obj.BILLID;
                            let billName = obj.BILLNAME;
                            let billDefine = billName.replace(/_E/ig, "").replace(/_R/ig, "").replace(/_A/ig, "");
                            arrApi1.push(that.searchBillObj(billDefine, billId, obj.BILLDETAILOBJ));
                        } else {
                            let billId = rowDataObject.getData().BILLID.value;
                            let billName = rowDataObject.getData().BILLNAME.value;
                            let billDefine = billName.replace(/_E/ig, "").replace(/_R/ig, "").replace(/_A/ig, "");
                            arrApi1.push(that.searchBillObj(billDefine, billId));
                        }
                    }
                }
            })
        }
        if (arrApi1.length > 0) {
            Promise.all(arrApi1).then((list) => {
                detailData = list;
                that.saveAsync(buidData, detailData, param, bill);
            })
        } else {
            that.saveAsync(buidData, detailData, param, bill);
        }
    },
    saveAsync(buidData, detailData, param, bill) {
        let postData = {
            data: buidData,
            detailData: detailData
        }
        let url = `/rbc/bill/action/saveExpenceAccount/${param.define}`;
        GMS.$http.post(url, JSON.stringify(postData), {
            headers: {
                post: {
                    "Content-Type": "application/json",
                }
            }
        }).then(
            function (response) {
                bill.setControlsSate(param["_control_name_"], 'enable',true);
                if (response.data.code == 0) {
                    //存储返回回来的创建时间、修改时间
                    bill.getMasterData().setValue('createTime', response.data.content.billData.createTime);
                    bill.getMasterData().setValue('modifyTime', response.data.content.billData.modifyTime);
                    bill.getMasterData().setValue('recver', response.data.content.billData.recver);
                    bill.getMasterData().setValue('billCode', response.data.content.billData.billCode);
                    GMS.vbus.$emit('saveSuccess',buidData,param);
                }else{
                    response.data.msg && GMS.vbus.$Message.error(response.data.msg);
                }
            }
        ).catch()
    },
    searchBillObj(billDefine, billId, BILLDETAILOBJ) {
        return new Promise((resolve, reject) => {
            GMS.$http.get(
                `/gms/bill/${billDefine}/${billId}?withSubs=true`
            ).then((data) => {
                let obj = BILLDETAILOBJ;
                if (data.status == 200 && data.data.code == 0) {
                    if(!BILLDETAILOBJ){
                        obj = data.data.content
                    }
                    obj.recver = data.data.content&&data.data.content.recver;
                }
                obj.billDefine = billDefine;
                resolve(obj);
            }).catch((error) => {
                reject(error)
            })
        })
    },
    execuFormula(buidData, param) {
        let postData = {
            data: buidData
        }
        if (!param.param.actions) {
            return
        }
        let url = `/gms/bill/executed/${param.define}/${param.param.actions}?transmission=total`;
        GMS.$http.post(url, JSON.stringify(postData), {
            headers: {
                post: {
                    "Content-Type": "application/json",
                }
            }
        }).then(response => {
            // bill.setControlsSate(param["_control_name_"], 'enable',true);
            let data = response.data;
            if (data.code == 0) {
                GMS.vbus.$emit('cacheEcho', buidData);//正常情况回去给子表赋值
            }else if(data.code == -1 && data.message){
                let stringOne = data.message.split(':')[1];
                let stringResult = stringOne.split(';')[0]
                let msg = stringResult.split('@');
                // TODO 仍需解决 包含'@'字符的非CheckBudgetControl公示报错msg 以及else分支的按钮状态问题
                if(stringResult.indexOf('@') === -1){
                   GAMS.Common.messagePrompt(stringResult)
                    if (this.bill&&this.param) {
                        this.bill.setControlsSate(this.param["_control_name_"], 'enable',true);
                    }
                }else{
                    if(msg[0]== 1 ){
                       GAMS.Common.messagePrompt(msg[1]);
                    }else{
                        GMS.$hideContainer.$Modal.confirm({
                            title: '信息提示',
                            content: msg[1],
                            onOk: () => {
                                GMS.vbus.$emit('cacheEcho', buidData);//正常情况回去给子表赋值
                            },
                            onCancel: () => {}
                        });
                    }
                }
            }
        }).catch(resp=>{
            // bill.setControlsSate(param["_control_name_"], 'enable',true);
            console.error("cacheSaveAction:接口调用失败 resp:"+ resp)
            GAMS.Common.messagePrompt('单据保存失败..');
        })
    }
}
