import { getTableHeadUtilityClass } from '@mui/material';
import {copy, danxiangdinge_index, danxiangdinge_index_djcs, renameDingE, extractFuzhu, match_target} from './utils';
import { v4 as uuidv4 } from 'uuid';
class Service{
    
    constructor() {
        this.cache = [];
        this.memory = [];
        this.mem_pointer = -1;
        this.cache_djcs = [];
        this.memory_djcs = [];
        this.mem_pointer_djcs = -1;
        this.qufei = [];
        this.qufeiEntry = null;
    }
    
    ip() {
        return "/api"//return "http://127.0.0.1:8000"
    }

    clearCache() {//set qufei will clear cache
        this.cache = [];
        this.memory = [];
        this.mem_pointer = -1;
        this.cache_djcs = [];
        this.memory_djcs = [];
        this.mem_pointer_djcs = -1;
    }

    setQufei(data) {
        let result = [];
        for(let i = 0; i < data[0]['children'].length; i++) {
            let child = data[0]['children'][i];
            for(let j = 0; j < child['children'].length; j++) {
                let grandchild = child['children'][j];
                //console.log(grandchild);
                result.push(grandchild);
            }
        }
        this.qufei = result;
    }

    setQufeiEntry(bh) {
        this.qufeiEntry = this.qufei.filter(x=>x['key'] == bh)[0];

    }


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

        }
        for(let i = 0; i < this.cache_djcs.length; i++) {
            let zimu = this.cache_djcs[i];
            for(let j = 0; j < zimu["_children"].length; j++) {
                let de = zimu["_children"][j];
                if (!de.hasOwnProperty("dercj")) {
                    de["dercj"] = [["ID", "人材机编码", "名称", "规格型号", "单位", "单价", "产地", 
                    "供应厂商", "人材机类别", "甲供标志", "含量", "合价", "暂估价标志", "主要材料标志", "主材标志", "设备标志" ]];
                }
            }
        }
        this.cache_djcs = this.cache_djcs.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_djcs = [];
        this.memory_djcs.push(copy(this.cache_djcs));
        this.mem_pointer_djcs = 0;

    }



    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( "/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 uploadFile(fd) {
        const response = await fetch(this.ip().concat( "/upload/"), {
            method : "POST",
            body : fd
        });
        if (!response.ok) {
            //const error = await response.json();
            console.error('error');
        } else {
            const data = await response.json();
            return data;
        }
    }

    async generateQufei(name) {
        const response = await fetch(this.ip().concat("/qufei/"), {
            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( "/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("/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("/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(  "/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(  "/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( "/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( "/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( "/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( "/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 generateZygczgj(name, id) {
        const response = await fetch(this.ip().concat( "/zygczgj/"), {
            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( "/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( "/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( "/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( "/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( "/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( "/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();
            let result = [];
            for (let i = 1; i < data.length; i++) {
                result.push({
                    'key': uuidv4(),
                    'ID' : data[i][0],
                    '编码' : data[i][1],
                    '名称': data[i][2],
                    '规格型号' : data[i][3],
                    '单位' : data[i][4],
                    '数量' : data[i][5],
                    '单价' : data[i][6],
                    '合价' : data[i][7],
                    '产地' : data[i][8],
                    '供应厂商' : data[i][9],
                    '人材机类别' : data[i][10],
                    '主要材料标志' : data[i][11],
                    '主材标志' : data[i][12],
                    '设备标志' : data[i][13],
                    '甲供标志' : data[i][14],
                    '暂估价标志' : data[i][15]
                });
            }
            this.setQufeiEntry(id);
            return result;
        }
    }
    async generateJirigong(name, id) {
        const response = await fetch(this.ip().concat("/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("/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( "/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( "/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( "/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( "/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;
        }
    }

    async searchDe(zhuanye, text) {
        const response = await fetch(this.ip().concat( "/searchde/"), {
            method : "POST",
            headers: {
                "Content-type": "application/json"
            },
            body: JSON.stringify({
                zhuanye: zhuanye,
                text: text
            })
        });
        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("/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);
            this.setQufeiEntry(bh);
            return copy(this.cache);
        }
        } else {
            return copy(this.cache);
        }
    }


    async generateQingdanrcj(name, bh, bt, bm) {
        if (bt == "Djcs") {
            let qd = this.cache_djcs.filter(x=>x["清单编码"] == bm)[0];
            return copy(qd["rcj"]);
        }
        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') {
            let qd = this.cache_djcs.filter(x=>x["清单编码"] == qdbm)[0];
            let de = qd["_children"].filter(x=>x["清单编码"]==debm)[0];
            return [copy(de["dercj"]), de["fuzhuEnable"]];
        
        }
        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( "/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( "/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) {
        if (this.cache_djcs.length == 0 || this.cache_djcs[0]["biao_id"] != name || this.cache_djcs[0]["Dwgcbh"] != bh) {
        const response = await fetch(this.ip().concat( "/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();
            this.processDjcsmingxi(data);
            this.setQufeiEntry(bh);
            return copy(this.cache_djcs);
        }
        } else {
            return copy(this.cache_djcs);
        }
    }
    async generateFiles() {
        const response = await fetch(this.ip().concat( "/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( "/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 deleteFiles(id) {
        const response = await fetch(this.ip().concat( "/deleteFile/"), {
            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 generatePeibiXilie(id) {
        const response = await fetch(this.ip().concat( "/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( "/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( "/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("/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( "/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( "/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;
        }
    }

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

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

    async download(id) {
        const response = await fetch(this.ip().concat( "/download/").concat(id.toString()));

        if (!response.ok) {
            //const error = await response.json();
            console.error('error');
        } else {
            const data = await response.blob();
            return data;
        }
    }

    async tiaojia(biao_id, bh, bm, mingcheng, danwei, jiage) {
        let glf = "";
        let lr = "";
        let bz = 0;//changgui
        if (this.qufeiEntry['备注'].length == 0) {
            //changuiqufei
            glf = this.qufeiEntry['管理费（%）'] ;
            lr = this.qufeiEntry['利润（%）'];
        } else {
            glf = this.qufeiEntry['管理费（%）'] ;
            lr = this.qufeiEntry['利润（%）'];
            bz = 1;
        }
        const response = await fetch(this.ip().concat( "/tiaojia/"), {
            method : "POST",
            headers: {
                "Content-type": "application/json"
            },
            body: JSON.stringify(
                {
                    "biao_id": biao_id,
                    "bh": bh,
                    "bm": bm,
                    "mingcheng": mingcheng,
                    "danwei" : danwei, 
                    "jiage": jiage,
                    "glf" : glf,
                    "lr" : lr,
                    "bz" : bz
                }
            )
        });
        if (!response.ok) {
            //const error = await response.json();
            console.error('error');
        } else {
            const data = await response.json();
            this.clearCache();
            return data;
        }
    }


    async updateZjcs(biao_id, bh, row) {
      
        const response = await fetch(this.ip().concat( "/updatezjcs/"), {
            method : "POST",
            headers: {
                "Content-type": "application/json"
            },
            body: JSON.stringify(
                {
                    "biao_id": biao_id,
                    "bh": bh,
                    'mc': row['名称'].toString(),
                    'fl': row['费率'].toString()
                    
                }
            )
        });
        if (!response.ok) {
            //const error = await response.json();
            console.error('error');
        } else {
            const data = await response.json();
           
            return data;
        }
    }

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




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


    summarize_one_djcs(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_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));
    }

    summarize_djcs(data) {
        return data.map(x=>this.summarize_one_djcs(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; 
    
       }
    }

    push_op_djcs(newData) {
        if(this.memory_djcs.length == this.mem_pointer_djcs + 1) {
            this.memory_djcs.push(copy(newData));
            this.mem_pointer_djcs = this.mem_pointer_djcs + 1;
       } else{
            this.memory_djcs.splice(this.mem_pointer_djcs + 1);
            this.memory_djcs.push(copy(newData));
            this.mem_pointer_djcs = this.mem_pointer_djcs + 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);
    }

    undo_djcs() {
        if (this.mem_pointer_djcs > 0) {
            
            let newData = this.memory_djcs[this.mem_pointer_djcs - 1];
            this.mem_pointer_djcs = this.mem_pointer_djcs - 1;
            this.cache_djcs = copy(newData);
            return copy(newData);
           
        }

        return copy(this.cache_djcs);
    }
    
    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);
    }

    redo_djcs() {
        if (this.mem_pointer_djcs + 1 != this.memory_djcs.length) {
            let newData = this.memory_djcs[this.mem_pointer_djcs + 1];
            this.mem_pointer_djcs = this.mem_pointer_djcs + 1;
            this.cache_djcs = copy(newData);
            return copy(newData);
            }

        return copy(this.cache_djcs);
    }

    shanchu_djcs(key) {
        if (this.cache_djcs.filter(x=>x['key'] == key).length > 0) {
            ///qd
            let newData = this.cache_djcs.map(x=>{
                if (x["key"] == key) {
                    let y = copy(x);
                    
                    y["_children"] = [];
                    return y;
                } else {
                    return x;
                }
            });
            let summarized = this.summarize_djcs(newData);
            this.push_op_djcs(summarized);
             /////////////////
            this.cache_djcs = copy(summarized);
            return copy(this.cache_djcs);

        } else {
            let qd = this.cache_djcs.filter(x=>x["_children"].filter(y=>y['key'] == key).length > 0)[0];
            let qdbm = qd['清单编码'];
            let newData = this.cache_djcs.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_djcs(newData);
            this.push_op_djcs(summarized);
            /////////////////
            this.cache_djcs = copy(summarized);
            return copy(this.cache_djcs);
        }
        
        


    }

    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);
        }
        
        


    }


    updateDercj_djcs_(row, data, xuhao) {///change 一条定额 inplace, 汇总一条定额的rcj, xuhao is for rename
        console.log("data updated");
        //处理附注
        let huan = false;//换
        let qd = this.cache_djcs.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['rcjdg'][i][2] == data[i][2]) {//更新名称
                    
                } else {
                    huan = true;
                }
            }

            if (de['fuzhuEnable'] && de.hasOwnProperty('fuzhu')) {//没强行改过含量
                
                for(let j = 1; j < de['rcjdg'].length; j++) {
                    let origin = Number(de['rcjdg'][j][10]);
                    for(let i = 0; i < de['fuzhu'].length; i++) {
                        let selected = de['fuzhu'][i];
                        let target = selected[0];
                        
                        
                        if (match_target(de['rcjdg'][j][1], target)) {
                            if (selected[2] == '系数') {
                                origin = origin * Number(selected[3]);

                            } else if (selected[2] == '含量') {
                                origin = Number(selected[3]);
                            } else if (selected[2] == '调整') {
                                origin = origin + Number(selected[3]);
                            } else {
                                throw new Error('无法处理的附注'.concat(selected[2]));
                            }
                            
                        }
                        

                    }
                    de['dercj'][j][2] = data[j][2];//名称
                    de['dercj'][j][1] = data[j][1];//编号
                    de['dercj'][j][5] = de['rcjdg'][j][5];//单价
                    de['dercj'][j][10] =  origin;
                    de['dercj'][j][11] = Number(de['dercj'][j][5]) * origin;
                }

            } else if (de['fuzhuEnable'] && !de.hasOwnProperty('fuzhu')) {
                for(let j = 1; j < de['rcjdg'].length; j++) {
                    let origin = Number(de['rcjdg'][j][10]);
                    
                    de['dercj'][j][2] = data[j][2];//名称
                    de['dercj'][j][1] = data[j][1];//编号

                    de['dercj'][j][5] = de['rcjdg'][j][5];
                    de['dercj'][j][10] =  origin;
                    de['dercj'][j][11] = Number(de['dercj'][j][5]) * origin;
                }
            }

            else {
                //强行改含量
                de['dercj'] = copy(data);
            }
        

            
            data = de['dercj'];
        } else {////单项定额没有底稿，老数据没底搞，无法判断换部换，暂时统一认为不换
            //强行改含量
            de['dercj'] = copy(data);
            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]['辅材费'] = clf_sum;
                qd["_children"][i]['材料费'] = clf_sum;
                qd["_children"][i]['人工费'] = rgf_sum;
                qd["_children"][i]['主材费'] = 0;
                qd["_children"][i]['设备费'] = 0;
                qd["_children"][i]['机械费'] = jxf_sum;
                if (oldname.startsWith("D")) {//单项清单
                    qd["_children"][i]['管理费'] = 0;
                    qd["_children"][i]['利润'] = 0;
                } else {
                    if (this.qufeiEntry['备注'].length == 0) {
                        //changuiqufei
                        qd["_children"][i]['管理费'] = (rgf_sum + jxf_sum) * Number(this.qufeiEntry['管理费（%）']) / Number(100);
                        qd["_children"][i]['利润'] = (rgf_sum + jxf_sum) * Number(this.qufeiEntry['利润（%）']) / Number(100);
                    } else {
                        qd["_children"][i]['管理费'] = (rgf_sum) * Number(this.qufeiEntry['管理费（%）']) / Number(100);
                        qd["_children"][i]['利润'] = (rgf_sum) * Number(this.qufeiEntry['利润（%）']) / Number(100);
                    }
                }
                qd["_children"][i]['综合单价'] = sum + qd["_children"][i]['管理费'] + qd["_children"][i]['利润'];
                qd["_children"][i]['合价'] = (qd["_children"][i]['综合单价'] * shuliang * desl);
                
                
                
                qd["_children"][i]["dercj"] = copy(data);
                qd["_children"][i]['清单编码'] = renameDingE(oldname, xuhao, huan);

            }
        }
    }


    updateDercj_(row, data, xuhao) {///change 一条定额 inplace, 汇总一条定额的rcj, xuhao is for rename
        console.log("data updated");
        //处理附注
        let huan = false;//换
        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['rcjdg'][i][2] == data[i][2]) {//更新名称
                    
                } else {
                    huan = true;
                }
            }

            if (de['fuzhuEnable'] && de.hasOwnProperty('fuzhu')) {//没强行改过含量
                
                for(let j = 1; j < de['rcjdg'].length; j++) {
                    let origin = Number(de['rcjdg'][j][10]);
                    for(let i = 0; i < de['fuzhu'].length; i++) {
                        let selected = de['fuzhu'][i];
                        let target = selected[0];
                        
                        
                        if (match_target(de['rcjdg'][j][1], target)) {
                            if (selected[2] == '系数') {
                                origin = origin * Number(selected[3]);

                            } else if (selected[2] == '含量') {
                                origin = Number(selected[3]);
                            } else if (selected[2] == '调整') {
                                origin = origin + Number(selected[3]);
                            } else {
                                throw new Error('无法处理的附注'.concat(selected[2]));
                            }
                            
                        }
                        

                    }
                    de['dercj'][j][2] = data[j][2];//名称
                    de['dercj'][j][1] = data[j][1];//编号
                    de['dercj'][j][5] = de['rcjdg'][j][5];//单价
                    de['dercj'][j][10] =  origin;
                    de['dercj'][j][11] = Number(de['dercj'][j][5]) * origin;
                }

            } else if (de['fuzhuEnable'] && !de.hasOwnProperty('fuzhu')) {
                for(let j = 1; j < de['rcjdg'].length; j++) {
                    let origin = Number(de['rcjdg'][j][10]);
                    
                    de['dercj'][j][2] = data[j][2];//名称
                    de['dercj'][j][1] = data[j][1];//编号

                    de['dercj'][j][5] = de['rcjdg'][j][5];
                    de['dercj'][j][10] =  origin;
                    de['dercj'][j][11] = Number(de['dercj'][j][5]) * origin;
                }
            }

            else {
                //强行改含量
                de['dercj'] = copy(data);
            }
        

            
            data = de['dercj'];
        } else {////单项定额没有底稿，老数据没底搞，无法判断换部换，暂时统一认为不换
            //强行改含量
            de['dercj'] = copy(data);
            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]['辅材费'] = clf_sum;
                qd["_children"][i]['材料费'] = clf_sum;
                qd["_children"][i]['人工费'] = rgf_sum;
                qd["_children"][i]['主材费'] = 0;
                qd["_children"][i]['设备费'] = 0;
                qd["_children"][i]['机械费'] = jxf_sum;
                if (oldname.startsWith("D")) {//单项清单
                    qd["_children"][i]['管理费'] = 0;
                    qd["_children"][i]['利润'] = 0;
                } else {
                    if (this.qufeiEntry['备注'].length == 0) {
                        //changuiqufei
                        qd["_children"][i]['管理费'] = (rgf_sum + jxf_sum) * Number(this.qufeiEntry['管理费（%）']) / Number(100);
                        qd["_children"][i]['利润'] = (rgf_sum + jxf_sum) * Number(this.qufeiEntry['利润（%）']) / Number(100);
                    } else {
                        qd["_children"][i]['管理费'] = (rgf_sum) * Number(this.qufeiEntry['管理费（%）']) / Number(100);
                        qd["_children"][i]['利润'] = (rgf_sum) * Number(this.qufeiEntry['利润（%）']) / Number(100);
                    }
                }
                qd["_children"][i]['综合单价'] = sum + qd["_children"][i]['管理费'] + qd["_children"][i]['利润'];
                qd["_children"][i]['合价'] = (qd["_children"][i]['综合单价'] * shuliang * desl);
                
                
                
                qd["_children"][i]["dercj"] = copy(data);
                qd["_children"][i]['清单编码'] = renameDingE(oldname, xuhao, huan);

            }
        }
    }

    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 bm = de['清单编码'];
        let alreadyFuzhu = extractFuzhu(bm);//[xuhao]
        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, alreadyFuzhu);
        //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);


    }


    updateDercj_djcs(row, data) {
        //是否手动设置含量
        let qd = this.cache_djcs.filter(x=>x["_children"].filter(y=>y['key']==row).length > 0)[0];
        let de = qd["_children"].filter(x=>x['key'] == row)[0];
        let bm = de['清单编码'];
        let alreadyFuzhu = extractFuzhu(bm);//[xuhao]
        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_djcs_(row, data, alreadyFuzhu);
        //let qd = this.cache.filter(x=>x["children"].filter(y=>y['key']==row).length > 0)[0];

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


    }


    updateBeizhu(row, selected, xuhao) {//xuhao is for rename
        let qd = this.cache.filter(x=>x["_children"].filter(y=>y['key']==row).length > 0)[0];
        if (!qd) return [null, null];
        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'])];

    }


    updateBeizhu_djcs(row, selected, xuhao) {//xuhao is for rename
        let qd = this.cache_djcs.filter(x=>x["_children"].filter(y=>y['key']==row).length > 0)[0];
        if (!qd) return [null, null];
        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_djcs_(row, de['dercj'], xuhao);

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

    }

    huan(old_index, new_bianhao, new_name, new_jia, row) {
        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 rcj = copy(de['dercj']);
        rcj[old_index][1] = new_bianhao;
        rcj[old_index][2] = new_name;
        rcj[old_index][5] = new_jia;

        return this.updateDercj(row, rcj);






    }

    updateShuliang(value, row) {
        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['数量']
        if (Number(origin) - Number(value) < 0.0001 && Number(origin) - Number(value) > -0.0001) {
            return [false, null];
        }
        console.log("shuliang update");
        de['数量'] = value;
        de['合价'] = Number(qd['数量']) * Number(de['综合单价']) * Number(de['数量']);
        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 [true, copy(this.cache)];






    }


    updateShuliang_djcs(value, row) {
        let qd = this.cache_djcs.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['数量']
        if (Number(origin) - Number(value) < 0.0001 && Number(origin) - Number(value) > -0.0001) {
            return [false, null];
        }
        console.log("shuliang update");
        de['数量'] = value;
        de['合价'] = Number(qd['数量']) * Number(de['综合单价']) * Number(de['数量']);
        let newData = this.cache_djcs.map(x=>{
            if (x['key'] == qd['key']) {
                return qd;
            } else {
                return x;
            }
        });
        let summarized = this.summarize_djcs(newData);
        this.push_op_djcs(summarized);
        /////////////////
        this.cache_djcs = copy(summarized);
        return [true, copy(this.cache_djcs)];






    }


    changguidinge_djcs(dingeclick, row) {
        if (this.cache_djcs.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_djcs.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_djcs_(newKey, dercj, []);
                let summarized = this.summarize_djcs(this.cache_djcs);
                this.push_op_djcs(copy(summarized));
                /////////////////
                this.cache_djcs = copy(summarized);
                //return copy(this.cache);
            

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



    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), newKey];
        } else {
            return [false, null, 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 mingcheng = selected['名称'];
            let children = selected["_children"];
            children.push({
                '操作': '',
                '序号': null,
                '清单编码': bh,
                '名称': mingcheng,
                '项目特征': null,
                '计算规则': null,
                '单位': danwei,
                '数量': '1',
                '综合单价': '',
                '合价': '',
                '人工费': '0',
                '主材费': '0',
                '设备费': '0',
                '辅材费': '',
                '材料费': '',
                '机械费': '0',
                '管理费': '0',
                '利润': '0',
                '暂估价': null,
                '综合人工工日': null,
                '备注': null,
                "dercj": [["ID", "人材机编码", "名称", "规格型号", "单位", "单价", "产地", 
                "供应厂商", "人材机类别", "甲供标志", "含量", "合价", "暂估价标志", "主要材料标志", "主材标志", "设备标志" ],
                   ['', bh, mingcheng, '', 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];
        }

    }

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

                
            });
            let summarized = this.summarize_djcs(this.cache_djcs);
            this.push_op_djcs(summarized);
            this.cache_djcs = copy(summarized);
            
            return [true, copy(this.cache_djcs)];
        } else {
            return [false,null];
        }

    }

    
}


export default new Service();
