import { getTableHeadUtilityClass } from '@mui/material';
import {copy, danxiangdinge_index, renameDingE} from './utils';
import { v4 as uuidv4 } from 'uuid';
class Service{
    
    constructor() {
        this.cache = [];
        this.memory = [];
        this.mem_pointer = -1;
    }
    
    ip() {
        return "http://127.0.0.1"
    }

    processQingdanmingxi(mingxi) {
        this.cache = copy(mingxi);
        for(let i = 0; i < this.cache.length; i++) {
            let zimu = this.cache[i];
            if (!zimu.hasOwnProperty("__children")) {
                zimu["__children"] = [];
            }
            if (!zimu.hasOwnProperty("rcj")) {
                zimu["rcj"] = [["ID", "人材机编码", "名称", "规格型号", "单位", "单价", "产地", 
                "供应厂商", "人材机类别", "甲供标志", "含量", "合价", "暂估价标志", "主要材料标志", "主材标志", "设备标志" ]];
            }

        }
        for(let i = 0; i < this.cache.length; i++) {
            let zimu = this.cache[i];
            for(let j = 0; j < zimu["__children"].length; j++) {
                let de = zimu["__children"][j];
                if (!de.hasOwnProperty("dercj")) {
                    de["dercj"] = [["ID", "人材机编码", "名称", "规格型号", "单位", "单价", "产地", 
                    "供应厂商", "人材机类别", "甲供标志", "含量", "合价", "暂估价标志", "主要材料标志", "主材标志", "设备标志" ]];
                }
            }
        }
        this.cache = this.cache.map(x=>{
            x["children"] = x["__children"];

            x["key"] = x["序号"];
            x["children"] = x["children"].map(y=>{
                if (!y.hasOwnProperty('key')) {
                    y['key'] = uuidv4();
                }
                return y;
            })
            return x;
        });
        this.memory = [];
        this.memory.push(copy(this.cache));
        this.mem_pointer = 0;

    }
    async generateOutline(name) {
        const response = await fetch(this.ip().concat( ":8000/outline"), {
            method : "POST",
            headers: {
                "Content-type": "application/json"
            },
            body : JSON.stringify({
                "name": name
            })
        });
        if (!response.ok) {
            //const error = await response.json();
            console.error('error');
        } else {
            const data = await response.json();
            return data;
        }
    }
    async generateOutline2(name) {
        const response = await fetch(this.ip().concat( ":8000/outline2"), {
            method : "POST",
            headers: {
                "Content-type": "application/json"
            },
            body : JSON.stringify({
                "name": name
            })
        });
        if (!response.ok) {
            //const error = await response.json();
            console.error('error');
        } else {
            const data = await response.json();
            return data;
        }
    }
    async generateDetail(name) {
        const response = await fetch(this.ip().concat(":8000/detail"), {
            method : "POST",
            headers: {
                "Content-type": "application/json"
            },
            body : JSON.stringify({
                "name": name
            })
        });
        if (!response.ok) {
            //const error = await response.json();
            console.error('error');
        } else {
            const data = await response.json();
            return data;
        }
    }

    async generateDetail2(name) {
        const response = await fetch(this.ip().concat(":8000/detail2"), {
            method : "POST",
            headers: {
                "Content-type": "application/json"
            },
            body : JSON.stringify({
                "name": name
            })
        });
        if (!response.ok) {
            //const error = await response.json();
            console.error('error');
        } else {
            const data = await response.json();
            return data;
        }
    }
    async generateBaojiahuizong(name, id) {
        const response = await fetch(this.ip().concat(  ":8000/baojiahuizong/"), {
            method : "POST",
            headers: {
                "Content-type": "application/json"
            }, 
            body: JSON.stringify({
                name: name,
                id : id
            })
        });
        if (!response.ok) {
            //const error = await response.json();
            console.error('error');
        } else {
            const data = await response.json();
            return data;
        }
    }
    async generateBaojiahuizong2(name, id) {
        const response = await fetch(this.ip().concat(  ":8000/baojiahuizong2/"), {
            method : "POST",
            headers: {
                "Content-type": "application/json"
            }, 
            body: JSON.stringify({
                name: name,
                id : id
            })
        });
        if (!response.ok) {
            //const error = await response.json();
            console.error('error');
        } else {
            const data = await response.json();
            return data;
        }
    }
    async generateGuifeishuijin(name, id) {
        const response = await fetch(this.ip().concat( ":8000/guifeishuijin/"), {
            method : "POST",
            headers: {
                "Content-type": "application/json"
            },
            body: JSON.stringify({
                name: name,
                id: id
            })
        });
        if (!response.ok) {
            //const error = await response.json();
            console.error('error');
        } else {
            const data = await response.json();
            return data;
        }
    }
    async generateGuifeishuijin2(name, id) {
        const response = await fetch(this.ip().concat( ":8000/guifeishuijin2/"), {
            method : "POST",
            headers: {
                "Content-type": "application/json"
            },
            body: JSON.stringify({
                name: name,
                id: id
            })
        });
        if (!response.ok) {
            //const error = await response.json();
            console.error('error');
        } else {
            const data = await response.json();
            return data;
        }
    }

    async generateQitaxiangmu(name, id) {
        const response = await fetch(this.ip().concat( ":8000/qitaxiangmu/"), {
            method : "POST",
            headers: {
                "Content-type": "application/json"
            },
            body: JSON.stringify({
                name: name,
                id : id
            })
        });
        if (!response.ok) {
            //const error = await response.json();
            console.error('error');
        } else {
            const data = await response.json();
            return data;
        }
    }

    async generateQitaxiangmu2(name, id) {
        const response = await fetch(this.ip().concat( ":8000/qitaxiangmu2/"), {
            method : "POST",
            headers: {
                "Content-type": "application/json"
            },
            body: JSON.stringify({
                name: name,
                id : id
            })
        });
        if (!response.ok) {
            //const error = await response.json();
            console.error('error');
        } else {
            const data = await response.json();
            return data;
        }
    }
    async generateZongchengbaofuwufei(name, id) {
        const response = await fetch(this.ip().concat( ":8000/zongchengbaofuwufei/"), {
            method : "POST",
            headers: {
                "Content-type": "application/json"
            },
            body: JSON.stringify({
                name: name,
                id: id
            })
        });
        if (!response.ok) {
            //const error = await response.json();
            console.error('error');
        } else {
            const data = await response.json();
            return data;
        }
    }

    async generateZongchengbaofuwufei2(name, id) {
        const response = await fetch(this.ip().concat( ":8000/zongchengbaofuwufei2/"), {
            method : "POST",
            headers: {
                "Content-type": "application/json"
            },
            body: JSON.stringify({
                name: name,
                id: id
            })
        });
        if (!response.ok) {
            //const error = await response.json();
            console.error('error');
        } else {
            const data = await response.json();
            return data;
        }
    }
    async generateFabaorengongyingcailiao(name, id) {
        const response = await fetch(this.ip().concat( ":8000/fabaorengongyingcailiao/"), {
            method : "POST",
            headers: {
                "Content-type": "application/json"
            },
            body: JSON.stringify({
                name: name,
                id : id
            })
        });
        if (!response.ok) {
            //const error = await response.json();
            console.error('error');
        } else {
            const data = await response.json();
            return data;
        }
    }
    async generateFabaorengongyingcailiao2(name, id) {
        const response = await fetch(this.ip().concat( ":8000/fabaorengongyingcailiao2/"), {
            method : "POST",
            headers: {
                "Content-type": "application/json"
            },
            body: JSON.stringify({
                name: name,
                id : id
            })
        });
        if (!response.ok) {
            //const error = await response.json();
            console.error('error');
        } else {
            const data = await response.json();
            return data;
        }
    }

    async generateRencaijihuizong(name, id) {
        const response = await fetch(this.ip().concat( ":8000/rencaijihuizong/"), {
            method : "POST",
            headers: {
                "Content-type": "application/json"
            },
            body: JSON.stringify({
                name: name,
                id: id
            })
        });
        if (!response.ok) {
            //const error = await response.json();
            console.error('error');
        } else {
            const data = await response.json();
            return data;
        }
    }

    async generateRencaijihuizong2(name, id) {
        const response = await fetch(this.ip().concat( ":8000/rencaijihuizong2/"), {
            method : "POST",
            headers: {
                "Content-type": "application/json"
            },
            body: JSON.stringify({
                name: name,
                id: id
            })
        });
        if (!response.ok) {
            //const error = await response.json();
            console.error('error');
        } else {
            const data = await response.json();
            return data;
        }
    }
    async generateJirigong(name, id) {
        const response = await fetch(this.ip().concat(":8000/jirigong/"), {
            method : "POST",
            headers: {
                "Content-type": "application/json"
            },
            body: JSON.stringify({
                name: name,
                id: id
            })
        });
        if (!response.ok) {
            //const error = await response.json();
            console.error('error');
        } else {
            const data = await response.json();
            return data;
        }
    }


    async generateJirigong2(name, id) {
        const response = await fetch(this.ip().concat(":8000/jirigong2/"), {
            method : "POST",
            headers: {
                "Content-type": "application/json"
            },
            body: JSON.stringify({
                name: name,
                id: id
            })
        });
        if (!response.ok) {
            //const error = await response.json();
            console.error('error');
        } else {
            const data = await response.json();
            return data;
        }
    }
    async generateZanliejine(name, id) {
        const response = await fetch(this.ip().concat( ":8000/zanliejine/"), {
            method : "POST",
            headers: {
                "Content-type": "application/json"
            },
            body: JSON.stringify({
                name: name,
                id: id
            })
        });
        if (!response.ok) {
            //const error = await response.json();
            console.error('error');
        } else {
            const data = await response.json();
            return data;
        }
    }

    async generateZanliejine2(name, id) {
        const response = await fetch(this.ip().concat( ":8000/zanliejine2/"), {
            method : "POST",
            headers: {
                "Content-type": "application/json"
            },
            body: JSON.stringify({
                name: name,
                id: id
            })
        });
        if (!response.ok) {
            //const error = await response.json();
            console.error('error');
        } else {
            const data = await response.json();
            return data;
        }
    }
    async generateQingdanxiangmu(name, id) {
        const response = await fetch(this.ip().concat( ":8000/qingdanxiangmu/"), {
            method : "POST",
            headers: {
                "Content-type": "application/json"
            },
            body: JSON.stringify({
                name: name,
                id: id
            })
        });
        if (!response.ok) {
            //const error = await response.json();
            console.error('error');
        } else {
            const data = await response.json();
            return data;
        }
    }
    async generateQingdanxiangmu2(name, id) {
        const response = await fetch(this.ip().concat( ":8000/qingdanxiangmu2/"), {
            method : "POST",
            headers: {
                "Content-type": "application/json"
            },
            body: JSON.stringify({
                name: name,
                id: id
            })
        });
        if (!response.ok) {
            //const error = await response.json();
            console.error('error');
        } else {
            const data = await response.json();
            return data;
        }
    }


    /////////////////////////////////////qingdan//////////////////////////////////////

    async generateQingdanmingxi(name, bh, bt) {
        if (this.cache.length == 0 || this.cache[0]["biao_id"] != name || this.cache[0]["Dwgcbh"] != bh ||
        this.cache[0]["bt"] != bt) {
        const response = await fetch(this.ip().concat(":8000/qingdanmingxi/"), {
            method : "POST",
            headers: {
                "Content-type": "application/json"
            },
            body: JSON.stringify(
                {
                    "bh": bh,
                    "bt": bt,
                    "name": name
                }
            )
        });
        if (!response.ok) {
            //const error = await response.json();
            console.error('error');
        } else {
            const data = await response.json();
            this.processQingdanmingxi(data);
            return copy(this.cache);
        }
        } else {
            return copy(this.cache);
        }
    }


    async generateQingdanrcj(name, bh, bt, bm) {
        if (bt == "Djcs") {
            const response = await fetch(this.ip().concat( ":8000/qingdanrcj/"), {
                method : "POST",
                headers: {
                    "Content-type": "application/json"
                },
                body: JSON.stringify(
                    {
                        "bh": bh,
                        "bt": bt,
                        "bm": bm,
                        "name": name
                    }
                )
            });
            if (!response.ok) {
                //const error = await response.json();
                console.error('error');
            } else {
                const data = await response.json();
                return data;
            }
        }
        let qd = this.cache.filter(x=>x["清单编码"] == bm)[0];
        return copy(qd["rcj"]);
        
    }
    async generateDingercj(name, bh, bt, qdbm, debm, danwei) {
        console.log('generateDingercj');
        console.log(debm);
        if (bt == 'Djcs') {
            const response = await fetch(this.ip().concat( ":8000/dingercj/"), {
                method : "POST",
                headers: {
                    "Content-type": "application/json"
                },
                body: JSON.stringify(
                    {
                        "bh": bh,
                        "bt": bt,
                        "qdbm": qdbm,
                        "debm" : debm,
                        "name": name
                    }
                )
            });
            if (!response.ok) {
                //const error = await response.json();
                console.error('error');
            } else {
                const data = await response.json();
                return data;
            }
        }
        let qd = this.cache.filter(x=>x["清单编码"] == qdbm)[0];
        let de = qd["children"].filter(x=>x["清单编码"]==debm)[0];
        return [copy(de["dercj"]), de["fuzhuEnable"]];
        
        
          
          
        
    }


/////////////////////////////end of qingdan////////////////////////////////////

async generateQingdanTuijian(name, bh, bt, bm) {
    const response = await fetch(this.ip().concat( ":8000/qingdantuijian/"), {
        method : "POST",
        headers: {
            "Content-type": "application/json"
        },
        body: JSON.stringify(
            {
                "bh": bh,
                "bt": bt,
                "bm": bm,
                "name": name
            }
        )
    });
    if (!response.ok) {
        //const error = await response.json();
        console.error('error');
    } else {
        const data = await response.json();
        return data;
    }
}
    async generateZjcs(name, bh) {
        const response = await fetch(this.ip().concat( ":8000/zjcs/"), {
            method : "POST",
            headers: {
                "Content-type": "application/json"
            },
            body: JSON.stringify(
                {
                    "bh": bh,
                    "name": name
                }
            )
        });
        if (!response.ok) {
            //const error = await response.json();
            console.error('error');
        } else {
            const data = await response.json();
            return data;
        }
    }
    async generateDjcs(name, bh) {
        const response = await fetch(this.ip().concat( ":8000/djcs/"), {
            method : "POST",
            headers: {
                "Content-type": "application/json"
            },
            body: JSON.stringify(
                {
                    "bh": bh,
                    "name": name
                }
            )
        });
        if (!response.ok) {
            //const error = await response.json();
            console.error('error');
        } else {
            const data = await response.json();
            return data;
        }
    }
    async generateFiles() {
        const response = await fetch(this.ip().concat( ":8000/files/"), {
            method : "POST",
            headers: {
                "Content-type": "application/json"
            }
        });
        if (!response.ok) {
            //const error = await response.json();
            console.error('error');
        } else {
            const data = await response.json();
            return data;
        }
    }

    async generateFiles2() {
        const response = await fetch(this.ip().concat( ":8000/files2/"), {
            method : "POST",
            headers: {
                "Content-type": "application/json"
            }
        });
        if (!response.ok) {
            //const error = await response.json();
            console.error('error');
        } else {
            const data = await response.json();
            return data;
        }
    }
    async generatePeibiXilie(id) {
        const response = await fetch(this.ip().concat( ":8000/pbxl/"), {
            method : "POST",
            headers: {
                "Content-type": "application/json"
            },
            body: JSON.stringify(
                {
                    "name": id
                }
            )
        });
        if (!response.ok) {
            //const error = await response.json();
            console.error('error');
        } else {
            const data = await response.json();
            return data;
        }
    }
    async generatePeibishu(zhuanye) {
        const response = await fetch(this.ip().concat( ":8000/pbs/"), {
            method : "POST",
            headers: {
                "Content-type": "application/json"
            },
            body: JSON.stringify(
                {
                    "value": zhuanye
                }
            )
        });
        if (!response.ok) {
            //const error = await response.json();
            console.error('error');
        } else {
            const data = await response.json();
            return data;
        }
    }
    async generateDingeshu(value) {
        const response = await fetch(this.ip().concat( ":8000/des/"), {
            method : "POST",
            headers: {
                "Content-type": "application/json"
            },
            body: JSON.stringify(
                {
                    "value": value
                }
            )
        });
        if (!response.ok) {
            //const error = await response.json();
            console.error('error');
        } else {
            const data = await response.json();
            return data;
        }
    }
    async generateDingeXilie(value, id) {
        const response = await fetch(this.ip().concat(":8000/dexilie/"), {
            method : "POST",
            headers: {
                "Content-type": "application/json"
            },
            body: JSON.stringify(
                {
                    "value": value,
                    "id": id
                }
            )
        });
        if (!response.ok) {
            //const error = await response.json();
            console.error('error');
        } else {
            const data = await response.json();
            return data;
        }
    }
    async generateSingleDingeXilie(zhuanye, debh) {
        const response = await fetch(this.ip().concat( ":8000/singledexilie/"), {
            method : "POST",
            headers: {
                "Content-type": "application/json"
            },
            body: JSON.stringify(
                {
                    "debh": debh,
                    "zhuanye": zhuanye
                }
            )
        });
        if (!response.ok) {
            //const error = await response.json();
            console.error('error');
        } else {
            const data = await response.json();
            return data;
        }
    }


    async save() {
        const response = await fetch(this.ip().concat( ":8000/save/"), {
            method : "POST",
            headers: {
                "Content-type": "application/json"
            },
            body: JSON.stringify(
                {
                    
                    "name": JSON.stringify(this.cache)
                }
            )
        });
        if (!response.ok) {
            //const error = await response.json();
            console.error('error');
        } else {
            const data = await response.json();
            return data;
        }
    }




    ///////////////////////////////////editor//////////////////////////////////


    summarize_one(qd) {///根据定额汇总清单
        let dict = {};
        for(let i = 0; i < qd["children"].length; i++) {
            let de = qd["children"][i];
            let desl = Number(de['数量']);
            let dercj = de['dercj'];
            for (let j = 1; j < dercj.length; j++) {
                let hl = copy(dercj[j]);
                hl[10] = desl * Number(hl[10]);
                hl[11] = desl * Number(hl[11]);
                let a = hl[1];//"人材机编码", 
                let b = a.concat(hl[2]);//"名称", 
                let c = b.concat(hl[4]);// "单位"
                if (dict.hasOwnProperty(c)) {
                    dict[c].push(hl);
                } else {
                    dict[c] = [hl];
                }

            }
        }
        let result = [];
        for(const key in dict) {
            let list = dict[key];
            let sum = 0;
            let danjia = Number(list[0][5]);
            for (let i =0 ;i < list.length; i++) {
                sum += Number(list[i][10]);
            }
            let entry = [list[0][0], list[0][1], list[0][2], list[0][3], list[0][4], danjia,
             list[0][6], list[0][7], list[0][8], list[0][9], sum, sum * danjia, list[0][12],
             list[0][13], list[0][14], list[0][15]
             ];
             result.push(entry);

        }
        let gongri = 0;
        for(let i = 0; i < result.length; i++) {
            if (result[i][4] == '工日') {
                gongri += result[i][10];
            }
        }
        result.sort((a, b) => Number(a[8]) - Number(b[8]));
        qd['rcj'] = [["ID", "人材机编码", "名称", "规格型号", "单位", "单价", "产地", 
        "供应厂商", "人材机类别", "甲供标志", "含量", "合价", "暂估价标志", "主要材料标志", "主材标志", "设备标志" ]].concat(result);
        qd["综合人工工日"] = gongri;
        qd['综合单价'] = 0;
        qd['合价'] = 0;
        qd['人工费'] = 0;
        qd['主材费'] = 0;
        qd['设备费'] = 0;
        qd['辅材费'] = 0;
        qd['材料费'] = 0;
        qd['机械费'] = 0;
        qd['管理费'] = 0;
        qd['利润'] = 0;
        for(let i = 0; i < qd["children"].length; i++) {
            qd['综合单价'] += Number(qd['children'][i]['数量']) * Number(qd['children'][i]['综合单价']);
            qd['合价'] += Number(qd['children'][i]['合价']);
            qd['人工费'] += Number(qd['children'][i]['数量']) * Number(qd['children'][i]['人工费']);
            qd['主材费'] += Number(qd['children'][i]['数量']) * Number(qd['children'][i]['主材费']);
            qd['设备费'] += Number(qd['children'][i]['数量']) * Number(qd['children'][i]['设备费']);
            qd['辅材费'] += Number(qd['children'][i]['数量']) * Number(qd['children'][i]['辅材费']);
            qd['材料费'] += Number(qd['children'][i]['数量']) * Number(qd['children'][i]['材料费']);
            qd['机械费'] += Number(qd['children'][i]['数量']) * Number(qd['children'][i]['机械费']);
            qd['管理费'] += Number(qd['children'][i]['数量']) * Number(qd['children'][i]['管理费']);
            qd['利润'] += Number(qd['children'][i]['数量']) * Number(qd['children'][i]['利润']);   
        }

        return qd;
    }
    summarize(data) {
        return data.map(x=>this.summarize_one(x));
    }

    push_op(newData) {
        if(this.memory.length == this.mem_pointer + 1) {
            this.memory.push(copy(newData));
            this.mem_pointer = this.mem_pointer + 1;
       } else{
            this.memory.splice(this.mem_pointer + 1);
            this.memory.push(copy(newData));
            this.mem_pointer = this.mem_pointer + 1; 
    
       }
    }

    undo() {
        if (this.mem_pointer > 0) {
            
            let newData = this.memory[this.mem_pointer - 1];
            this.mem_pointer = this.mem_pointer - 1;
            this.cache = copy(newData);
            return copy(newData);
           
        }

        return copy(this.cache);
    }
    
    redo() {
        if (this.mem_pointer + 1 != this.memory.length) {
            let newData = this.memory[this.mem_pointer + 1];
            this.mem_pointer = this.mem_pointer + 1;
            this.cache = copy(newData);
            return copy(newData);
            }

        return copy(this.cache);
    }

    shanchu(key) {
        if (this.cache.filter(x=>x['key'] == key).length > 0) {
            ///qd
            let newData = this.cache.map(x=>{
                if (x["key"] == key) {
                    let y = copy(x);
                    
                    y["children"] = [];
                    return y;
                } else {
                    return x;
                }
            });
            let summarized = this.summarize(newData);
            this.push_op(summarized);
             /////////////////
             this.cache = copy(summarized);
            return copy(this.cache);

        } else {
            let qd = this.cache.filter(x=>x["children"].filter(y=>y['key'] == key).length > 0)[0];
            let qdbm = qd['清单编码'];
            let newData = this.cache.map(x=>{
                if (x["清单编码"] == qdbm) {
                    let y = copy(x);
                    let origin = y["children"];
                    let trans = origin.filter(z=>z["key"]!=key);
                    y["children"] = trans;
                    return y;
                } else {
                    return x;
                }
            });
            let summarized = this.summarize(newData);
            this.push_op(summarized);
            /////////////////
            this.cache = copy(summarized);
            return copy(this.cache);
        }
        
        


    }

    quanbushanchu(qdbm) {
        let newData = this.cache.map(x=>{
            if (x["清单编码"] == qdbm) {
                let y = copy(x);
                
                y["__children"] = [];
                return y;
            } else {
                return x;
            }
        });
        let summarized = this.summarize(newData);
        this.push_op(summarized);
        /////////////////
        this.cache = copy(summarized);
        return copy(this.cache);


    }

    updateDercj_(row, data, xuhao) {///change 一条定额 inplace, 汇总一条定额的rcj, xuhao is for rename
        console.log("data updated");
        //处理附注
        let qd = this.cache.filter(x=>x["children"].filter(y=>y['key']==row).length > 0)[0];
        let de = qd["children"].filter(x=>x['key'] == row)[0];
        if (de.hasOwnProperty("rcjdg")) {
            for (let i = 1; i < de['rcjdg'].length; i++) {
                de['rcjdg'][i][5] = data[i][5];//更新单价
                /****ToDo 更新其他字段 */
            }

            if (de['fuzhuEnable'] && de.hasOwnProperty('fuzhu')) {
                for(let i = 0; i < de['fuzhu'].length; i++) {
                    let selected = de['fuzhu'][i];
                    //更新底稿含量
                    if (selected[2] == '含量') {
                        let target = selected[0];
                        for(let j = 1; j < de['rcjdg'].length; j++) {
                            if (de['rcjdg'][j][1] == target) {
                                let origin = de['rcjdg'][j][10];
                                for(let k = 1; k < de['dercj'].length; k++) {
                                    if (de['dercj'][k][1] == target) {
                                        de['dercj'][k][5] = de['rcjdg'][j][5];
                                        de['dercj'][k][10] =  selected[3];
                                        de['dercj'][k][11] = Number(de['dercj'][k][5]) * Number(selected[3]);
                                    }
                                }
                            }
                        }

                    }
                }
            } else {
                de['dercj'] = copy(de['rcjdg']);
            }
        

            
            data = de['dercj'];
        }
        //模拟formula计算每一行的合价
        for(let i = 1; i < data.length; i++) {
            data[i][11] = Number(data[i][10]) * Number(data[i][5]);
        }
        let sum = 0;
        let rgf_sum = 0;
        let jxf_sum = 0;
        let clf_sum = 0;
        for(let i = 1; i < data.length; i++) {
            sum += Number(data[i][11]);//11-> hejia
            if (Number(data[i][8]) == 1) {
                rgf_sum += Number(data[i][11]);
            }
            if (Number(data[i][8]) == 2) {
                clf_sum += Number(data[i][11]);
            }
            if (Number(data[i][8]) == 3) {
                jxf_sum += Number(data[i][11]);
            }
        }
        console.log("sum=".concat(sum));
        
        let shuliang = Number(qd['数量']);
        for(let i = 0; i< qd["children"].length; i++) {
            if(qd["children"][i]['key'] == row) {
                let desl = Number(qd["children"][i]['数量']);
                let oldname = qd["children"][i]['清单编码'];
                qd["children"][i]['综合单价'] = sum.toFixed(2);
                qd["children"][i]['合价'] = (sum * shuliang * desl).toFixed(2);
                qd["children"][i]['辅材费'] = clf_sum.toFixed(2);
                qd["children"][i]['材料费'] = clf_sum.toFixed(2);
                qd["children"][i]['人工费'] = rgf_sum.toFixed(2);
                qd["children"][i]['主材费'] = 0;
                qd["children"][i]['设备费'] = 0;
                qd["children"][i]['机械费'] = jxf_sum.toFixed(2);
                qd["children"][i]['管理费'] = 0;
                qd["children"][i]['利润'] = 0;
                qd["children"][i]["dercj"] = copy(data);
                qd["children"][i]['清单编码'] = renameDingE(oldname, xuhao);

            }
        }
    }

    updateDercj(row, data) {
        //是否手动设置含量
        let qd = this.cache.filter(x=>x["children"].filter(y=>y['key']==row).length > 0)[0];
        let de = qd["children"].filter(x=>x['key'] == row)[0];
        let origin = de['dercj'];
        let change = false;
        for(let i = 1; i < data.length; i++) {
            let before = origin[i][10];
            let after = data[i][10];
            if (Number(before) - Number(after) < 0.0001 && Number(before) - Number(after) > -0.0001) {
                //no change
            } else {
                change = true;
                break;
            }
        }
        if (change) {
            de['fuzhuEnable'] = false;
        }

        
        this.updateDercj_(row, data, []);
        //let qd = this.cache.filter(x=>x["children"].filter(y=>y['key']==row).length > 0)[0];

        let newData = this.cache.map(x=>{
            if (x['key'] == qd['key']) {
                return qd;
            } else {
                return x;
            }
        });
        let summarized = this.summarize(newData);
        this.push_op(summarized);
        /////////////////
        this.cache = copy(summarized);
        return copy(this.cache);


    }


    updateBeizhu(row, selected, xuhao) {//xuhao is for rename
        let qd = this.cache.filter(x=>x["children"].filter(y=>y['key']==row).length > 0)[0];
        let de = qd["children"].filter(x=>x['key'] == row)[0];
        if (de.hasOwnProperty("rcjdg")) {//底稿

        } else {
            de['rcjdg'] = copy(de['dercj']);

        }
        de['fuzhu'] = copy(selected);
        this.updateDercj_(row, de['dercj'], xuhao);

        let newData = this.cache.map(x=>{
            if (x['key'] == qd['key']) {
                return qd;
            } else {
                return x;
            }
        });
        let summarized = this.summarize(newData);
        this.push_op(summarized);
        /////////////////
        this.cache = copy(summarized);
        return [copy(this.cache), copy(de['dercj'])];

    }


    changguidinge(dingeclick, row) {
        if (this.cache.filter(x=>x['key'] == row).length > 0) {
            
                let res =dingeclick;
                let keys = Object.keys(res['DEBH']);
                let key = keys[0];
                //console.log(res);
                let qd = this.cache.filter(x=>x['key'] == row)[0];
                let dercj = [["ID", "人材机编码", "名称", "规格型号", "单位", "单价", "产地", 
                "供应厂商", "人材机类别", "甲供标志", "含量", "合价", "暂估价标志", "主要材料标志", "主材标志", "设备标志" ]];
                for(let i = 0; i < res['rgde'].length; i++) {
                    dercj.push(['', res['rgde'][i]['CLBH'], res['rgde'][i]['CLMC'], '', res['rgde'][i]['JLDW'], 
                    res['rgde'][i]['YSJG'], '', '', '1', '', res['rgde'][i]['gr'], res['rgde'][i]['gf'],
                    '', '', '', '' ]);
                }
                for(let i = 0; i < res['clde'].length; i++) {
                    dercj.push(['', res['clde'][i]['CLBH'], res['clde'][i]['CLMC'], '', res['clde'][i]['JLDW'], 
                    res['clde'][i]['YSJG'], '', '', '2', '', res['clde'][i]['SL'], res['clde'][i]['HJ'],
                    '', '', '', '' ]);
                }
                for(let i = 0; i < res['jxde'].length; i++) {
                    dercj.push(['', res['jxde'][i]['jxbh'], res['jxde'][i]['jxmc'], '', res['jxde'][i]['DW'], 
                    res['jxde'][i]['tbdj'], '', '', '3', '', res['jxde'][i]['sl'], res['jxde'][i]['hj'],
                    '', '', '', '' ]);
                }
                let newKey = uuidv4();
                qd["children"].push({
                    '操作': '',
                    '序号': null,
                    '清单编码': res['DEBH'][key],
                    '名称': res['GCLMC'][key],
                    '项目特征': null,
                    '计算规则': null,
                    '单位': res['DW'][key],
                    '数量': '1',
                    '综合单价': '0',
                    '合价': '0',
                    '人工费': '0',
                    '主材费': '0',
                    '设备费': '0',
                    '辅材费': '0',
                    '材料费': '0',
                    '机械费': '0',
                    '管理费': '0',
                    '利润': '0',
                    '暂估价': null,
                    '综合人工工日': null,
                    '备注': null,
                    "dercj": dercj,
                    'rcjdg': copy(dercj),
                    'key' :   newKey,
                    "fuzhuEnable": true
    
                    
                });
                this.updateDercj_(newKey, dercj, []);
                let summarized = this.summarize(this.cache);
                this.push_op(copy(summarized));
                /////////////////
                this.cache = copy(summarized);
                //return copy(this.cache);
            

            return [true, copy(this.cache)];
        } else {
            return [false, null];
        }
    }

    danxiangdinge(row) {
        let bh = danxiangdinge_index(this.cache);
        
        if (this.cache.filter(x=>x['key'] == row).length > 0) {
            let selected = this.cache.filter(x=>x['key'] == row)[0];
            let danwei = selected["单位"];
            let children = selected["children"];
            children.push({
                '操作': '',
                '序号': null,
                '清单编码': bh,
                '名称': '',
                '项目特征': null,
                '计算规则': null,
                '单位': danwei,
                '数量': '1',
                '综合单价': '',
                '合价': '',
                '人工费': '0',
                '主材费': '0',
                '设备费': '0',
                '辅材费': '',
                '材料费': '',
                '机械费': '0',
                '管理费': '0',
                '利润': '0',
                '暂估价': null,
                '综合人工工日': null,
                '备注': null,
                "dercj": [["ID", "人材机编码", "名称", "规格型号", "单位", "单价", "产地", 
                "供应厂商", "人材机类别", "甲供标志", "含量", "合价", "暂估价标志", "主要材料标志", "主材标志", "设备标志" ],
                   ['', bh, '', '', danwei, '', '', '', '2', '', '1', '', '',  '', '', '' ]
                      ],
                'key' :   uuidv4(),
                "fuzhuEnable": false

                
            });
            let summarized = this.summarize(this.cache);
            this.push_op(summarized);
            this.cache = copy(summarized);
            
            return [true, copy(this.cache)];
        } else {
            return [false,null];
        }

    }

    
}


export default new Service();
