import {copy, danxiangdinge_index, danxiangdinge_index_djcs, renameDingE, extractFuzhu, match_target, azfy, xsazfy, tjazfy, addChildren} from './utils.js';
import { v4 as uuidv4 } from 'uuid';
class Service{
    
    constructor() {
        this.footprint = [];
        this.cache = [];
        //this.token_ = localStorage.getItem('token');
        this.memory = [];
        this.mem_pointer = -1;
        this.cache_djcs = [];
        this.memory_djcs = [];
        this.mem_pointer_djcs = -1;
        this.qufei = [];
        this.qufeiEntry = null;
        this.jiagongcai = [];
        this.mapper={
            '99090513' : ['汽车式起重机 50t', 2838.92],
            '99090509' : ['汽车式起重机 25t', 1174.12],
            '99090111': ['履带式起重机 提升质量50t', 1755.71],
            '99090108': ['履带式起重机 提升质量25t', 904.68],
            '99030306': ['静力压桩机 压力1200kN', 1508.23],
            '99030124': ['轨道式柴油打桩机 冲击质量2.5t', 1143.91],
            '99030106' : ['履带式柴油打桩机 冲击质量7t', 2545.82],
            '10450518' : ['纯铝箔 140×140', 0.35],
            '10450508' : ['纯银箔 93.3×93.3', 4.5],
            '04050101' : ['道碴 40～80mm', 47],
            '04034103' : ['石屑(米砂)', 40]
        };
        
    }
    setToken(token) {
       this.token_ = token;
    }
    
    ip() {
        //return "/api"//return "http://127.0.0.1:8000"
        return "http://www.xiaozaotongxue.com/api"
    }

    clearCache() {//set qufei will clear cache
        this.cache = [];
        this.footprint= [];
        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;
    }
    setJiagongcai(data) {
        
        this.jiagongcai = data;
    }

    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.footprint = [];
        this.memory.push(copy(this.cache));
        this.mem_pointer = 0;

    }
   







    async generateRencaijihuizong2(name, id, navigate) {
        const response = await fetch(this.ip().concat( "/rencaijihuizong2/"), {
            method : "POST",
            headers: {
                "Content-type": "application/json",
                'Authorization': `Bearer ${this.token_}`

            },
            body: JSON.stringify({
                name: name,
                id: id
            })
        });
        if (!response.ok) {
            if (response.status == 401) {
                 navigate("/editor/signin");
            }
        } 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;
        }
    }






   


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

    async generateQingdanmingxi(name, bh, bt) {
        if (bt == 'ALL') {
            const response = await fetch(this.ip().concat("/qingdanmingxi/"), {
                method : "POST",
                headers: {
                    "Content-type": "application/json",
                    'Authorization': `Bearer ${this.token_}`
                },
                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();
                
                
                return data;
            }

        } else {
        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",
                'Authorization': `Bearer ${this.token_}`
            },
            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, key) {
        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 && x['key'] == key)[0];
            return [copy(de["dercj"]), de["fuzhuEnable"]];
        
        }
        let qd = this.cache.filter(x=>x["清单编码"] == qdbm)[0];
        let de = qd["_children"].filter(x=>x["清单编码"]==debm && x['key'] == key)[0];
        return [copy(de["dercj"]), de["fuzhuEnable"], de['yuban'], de['rcjbc']];
        
        
          
          
        
    }


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

    async generateDjcs(name, bh, navigate) {
        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",
                'Authorization': `Bearer ${this.token_}`
            },
            body: JSON.stringify(
                {
                    "bh": bh,
                    "name": name
                }
            )
        });
        if (!response.ok) {
            if (response.status == 401) {
               navigate("/editor/signin");
            }
        } else {
            const data = await response.json();
            this.processDjcsmingxi(data);
            this.setQufeiEntry(bh);
            return copy(this.cache_djcs);
        }
        } else {
            return copy(this.cache_djcs);
        }
    }




    async save() {
        const response = await fetch(this.ip().concat( "/save/"), {
            method : "POST",
            headers: {
                "Content-type": "application/json",
                'Authorization': `Bearer ${this.token_}`
            },
            body: JSON.stringify(
                {
                    
                    "name": JSON.stringify(this.cache.filter(x=>this.footprint.includes(x['key'])))
                }
            )
        });
        if (!response.ok) {
            //const error = await response.json();
            console.error('error');
        } else {
            const data = await response.json();
            this.footprint = [];
            return data;
        }
    }

    async save_djcs() {
        const response = await fetch(this.ip().concat( "/savedjcs/"), {
            method : "POST",
            headers: {
                "Content-type": "application/json",
                'Authorization': `Bearer ${this.token_}`
            },
            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 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",
                'Authorization': `Bearer ${this.token_}`
            },
            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;
        }
    }







    ///////////////////////////////////editor_code//////////////////////////////////


    summarize_one_djcs(qd) {///根据定额汇总清单
        let dict = {};
        let left = [];
        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]);
                if (hl[1] == '00EXP001' && hl[4] == '%') {
                    left.push(hl);
                    continue;
                }
                if (hl[1] == '99EXP007' && hl[4] == '%') {
                    left.push(hl);
                    continue;
                }
                if (hl[1] == '99EXP022' && hl[4] == '%') {
                    left.push(hl);
                    continue;
                }
                if (hl[1] == '31130104' && hl[4] == '%') {
                    left.push(hl);
                    continue;
                }
                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);

        }
        for (let i = 0; i < left.length; i++) {
            result.push(left[i]);
        }
        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) {///根据定额汇总清单
        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++) {
            if (qd["_children"][i]['azfytag'].length > 0)continue;
            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]['利润']);   
        }
        //处理安装费用
        //console.log(qd["_children"].length);
        for(let i = 0; i < qd["_children"].length; i++) {
            //console.log(i);
            if (qd["_children"][i]['azfytag'].length > 0){
                let tag = qd["_children"][i]['azfytag'];
                if (tag[0] == '人工费') {
                   let current_rgf = qd['人工费'];
                   let added = Number(current_rgf) * Number(tag[1]) / Number(100);
                   let added_rgf = added * Number(tag[2]) / Number(100);
                   let added_clf = added * Number(tag[3]) / Number(100);
                   let added_jxf = added * Number(tag[4]) / Number(100);
                   qd["_children"][i]['人工费'] = added_rgf;
                   qd["_children"][i]['辅材费'] = added_clf;
                   qd["_children"][i]['材料费'] = added_clf;
                   qd["_children"][i]['机械费'] = added_jxf;
                   if (this.qufeiEntry['备注'].length == 0) {
                       //changuiqufei
                       qd["_children"][i]['管理费'] = (added_rgf + added_jxf) * Number(this.qufeiEntry['管理费（%）']) / Number(100);
                       qd["_children"][i]['利润'] = (added_rgf + added_jxf) * Number(this.qufeiEntry['利润（%）']) / Number(100);
                   } else {
                       qd["_children"][i]['管理费'] = (added_rgf) * Number(this.qufeiEntry['管理费（%）']) / Number(100);
                       qd["_children"][i]['利润'] = (added_rgf) * Number(this.qufeiEntry['利润（%）']) / Number(100);
                   }
                   
                   qd["_children"][i]['综合单价'] = qd["_children"][i]['人工费'] + qd["_children"][i]['材料费'] + qd["_children"][i]['机械费'] + qd["_children"][i]['管理费'] +  qd["_children"][i]['利润'];
                   qd["_children"][i]['合价'] = qd["_children"][i]['综合单价'] * Number(qd["_children"][i]['数量']) * Number(qd['数量']);
                   let dercj = qd["_children"][i]['dercj'];
                   for (let j = 1; j < dercj.length; j++) {
                       dercj[j][11] = Number(added) * Number(dercj[j][10]) / Number(100);
                   }
                }
                if (tag[0] == '人工费+机械费') {
                   let current_rgf = qd['人工费'] + qd['机械费'];
                   let added = Number(current_rgf) * Number(tag[1]) / Number(100);
                   let added_rgf = added * Number(tag[2]) / Number(100);
                   let added_clf = added * Number(tag[3]) / Number(100);
                   let added_jxf = added * Number(tag[4]) / Number(100);
                   qd["_children"][i]['人工费'] = added_rgf;
                   qd["_children"][i]['辅材费'] = added_clf;
                   qd["_children"][i]['材料费'] = added_clf;
                   qd["_children"][i]['机械费'] = added_jxf;
                   if (this.qufeiEntry['备注'].length == 0) {
                       //changuiqufei
                       qd["_children"][i]['管理费'] = (added_rgf + added_jxf) * Number(this.qufeiEntry['管理费（%）']) / Number(100);
                       qd["_children"][i]['利润'] = (added_rgf + added_jxf) * Number(this.qufeiEntry['利润（%）']) / Number(100);
                   } else {
                       qd["_children"][i]['管理费'] = (added_rgf) * Number(this.qufeiEntry['管理费（%）']) / Number(100);
                       qd["_children"][i]['利润'] = (added_rgf) * Number(this.qufeiEntry['利润（%）']) / Number(100);
                   }
                   
                   qd["_children"][i]['综合单价'] = qd["_children"][i]['人工费'] + qd["_children"][i]['材料费'] + qd["_children"][i]['机械费'] + qd["_children"][i]['管理费'] +  qd["_children"][i]['利润'];
                   qd["_children"][i]['合价'] = qd["_children"][i]['综合单价'] * Number(qd["_children"][i]['数量']) * Number(qd["数量"]);
                   let dercj = qd["_children"][i]['dercj'];
                   for (let j = 1; j < dercj.length; j++) {
                       
                       dercj[j][11] = Number(added) * Number(dercj[j][10]) / Number(100);
                       
                   }
                }
            }
        }
        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]['利润']);   
        }
        let dict = {};
        let left = [];
        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]);
                if (hl[1].includes('000FE') && hl[4] == '%') {
                    left.push(hl);
                    continue;
                }
                if (hl[1] == '00EXP001' && hl[4] == '%') {
                    left.push(hl);
                    continue;
                }
                if (hl[1] == '99EXP007' && hl[4] == '%') {
                    left.push(hl);
                    continue;
                }
                if (hl[1] == '99EXP022' && hl[4] == '%') {
                    left.push(hl);
                    continue;
                }
                if (hl[1] == '31130104' && hl[4] == '%') {
                    left.push(hl);
                    continue;
                }
                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);

        }
        for (let i = 0; i < left.length; i++) {
            result.push(left[i]);
        }
        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;
        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);
        }
        
        


    }
    updateFootprint(key) {
        if (this.footprint.includes(key)) {

        } else {
            this.footprint.push(key);
        }
    }

    shanchu(key) {
        if (this.cache.filter(x=>x['key'] == key).length > 0) {
            this.updateFootprint(key);
            ///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];
            this.updateFootprint(qd['key']);
            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, mode=0/**0->update by view; 1-> config change */) {///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")) {//新数据
            de['dercj'] = copy(de['rcjdg']);

            if (de.hasOwnProperty('fuzhu')) {//
                
                for(let j = 1; j < de['rcjdg'].length; j++) {
                    let origin = Number(de['rcjdg'][j][10]);
                    let bianhao_huan = '';
                    let name_huan = '';
                    let new_jia = 0;
                    for(let i = 0; i < de['fuzhu'].length; i++) {
                        let selected = de['fuzhu'][i];//selected is 结构化的处理信息
                        let target = selected[0];
                        
                        
                        if (match_target(de['rcjdg'][j][1], de['rcjdg'][j][2], target, selected[1])) {
                            if (selected[2] == '系数' || selected[2] == '商品砼系数' || selected[2] == '除此机械外') {
                                origin = origin * (Number(selected[3]) ** Number(selected[5]));

                            } else if (selected[2] == '含量' || selected[2] == '商品砼含量') {
                                origin = Number(selected[3]);
                            } else if (selected[2] == '调整' || selected[2] == '商品砼调整') {
                                origin = origin + Number(selected[3]) * Number(selected[5]);
                            } else if (selected[2] == '调比') {
                                origin = origin + Number(selected[3]) * Number(selected[5]) / Number(100);
                            } else if (selected[2] == '次方') {
                                origin = origin * (Number(selected[3]) ** Number(selected[5]));
                            } else if (selected[2] == '叠加备注') {

                            } else if (selected[2] == '换机械系数') {
                                bianhao_huan = selected[4];
                                name_huan = this.mapper[bianhao_huan][0];
                                new_jia = this.mapper[bianhao_huan][1];
                                origin = origin * (Number(selected[3]) ** Number(selected[5]));
                            } else if (selected[2] == '换材料系数') {
                                bianhao_huan = selected[4];
                                name_huan = this.mapper[bianhao_huan][0];
                                new_jia = this.mapper[bianhao_huan][1];
                                origin = origin * (Number(selected[3]) ** Number(selected[5]));
                            } else if (selected[2] == '使用泵送') {
                                if (de['rcjdg'][j][2].includes('C20')) {
                                    bianhao_huan = '80212103';
                                    name_huan = '(C20泵送商品砼)';
                                    new_jia = 342;
                                }
                                if (de['rcjdg'][j][2].includes('C30')) {
                                    bianhao_huan = '80212105';
                                    name_huan = '(C30泵送商品砼)';
                                    new_jia = 362;
                                }

                            } else if (selected[2] == '使用非泵送') {
                                if (de['rcjdg'][j][2].includes('C20')) {
                                    bianhao_huan = '80212115';
                                    name_huan = '(C20非泵送商品砼)';
                                    new_jia = 333;
                                }
                                if (de['rcjdg'][j][2].includes('C30')) {
                                    bianhao_huan = '80212117';
                                    name_huan = '(C30非泵送商品砼)';
                                    new_jia = 353;
                                }
                            }
                            else {
                                throw new Error('无法处理的附注'.concat(selected[2]));
                            }
                            
                        }
                        

                    }
                            
                    if (bianhao_huan == '') {
                                
                    } else {
                                de['dercj'][j][1] = bianhao_huan;//编号
                                de['dercj'][j][2] = name_huan;//mc
                                de['dercj'][j][5] = new_jia;//jiage
                    }
                                        
                    de['dercj'][j][10] =  origin;
                    de['dercj'][j][11] = Number(de['dercj'][j][5]) * origin;
                }

            }
            
            
            for(let j = 1; j < de['dercj'].length; j++) {
                    for (let k = 0; k < data.length; k++) {
                        if (data[k][16] == de['dercj'][j][16]) {
                            if (de['dercj'][j][2] == data[k][2]) {//名称
                                
                            } else {
                                huan = true;
                            }
                            
                        }
                    }        
            }
            

            if (mode == 1) {
                data = de['dercj'];
                huan = false;
            } 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]);
        }
        //if (data[0].length > 18)
        //data = data.filter(x=>x[18]!='true').map(x=>[x[0], x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11], x[12], x[13], x[14], x[15], x[16]]);
              
        let sum = 0;
        let rgf_sum = 0;
        let jxf_sum = 0;
        let clf_sum = 0;
        let zcf_sum = 0;
        for(let i = 1; i < data.length; i++) {
            if (data[i][1]=='00EXP001' && data[i][4] == '%'){//回程费占人工费
                continue;    
            }
            if (data[i][1]=='99EXP007' && data[i][4] == '%'){//回程费占机械费
                continue;    
            }
            if (data[i][1]=='99EXP022' && data[i][4] == '%'){//回程费占机械费
                continue;    
            }
            if (data[i][1]=='31130104' && data[i][4] == '%'){//回程费占材料费
                continue;    
            }
            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 (data[i][14] == 'true') {
                    zcf_sum += Number(data[i][11]);
                }
            }
            if (Number(data[i][8]) == 3) {
                jxf_sum += Number(data[i][11]);
            }
        }
        console.log("sum=".concat(sum));
        //处理百分比费用
        for(let i = 1; i < data.length; i++) {
            if (data[i][1]=='00EXP001' && data[i][4] == '%'){//回程费占人工费
                data[i][11] = Number(data[i][10]) * rgf_sum / Number(100);   
            }
            if (data[i][1]=='99EXP007' && data[i][4] == '%'){//回程费占机械费
                data[i][11] = Number(data[i][10]) * jxf_sum / Number(100);    
            }
            if (data[i][1]=='99EXP022' && data[i][4] == '%'){//回程费占机械费
                data[i][11] = Number(data[i][10]) * jxf_sum / Number(100);    
            }
            if (data[i][1]=='31130104' && data[i][4] == '%'){//回程费占材料费
                data[i][11] = Number(data[i][10]) * clf_sum / Number(100);    
            }

        }
        sum = 0;
        rgf_sum = 0;
        jxf_sum = 0;
        clf_sum = 0;
        zcf_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 (data[i][14] == 'true') {
                    zcf_sum += Number(data[i][11]);
                }
            }
            if (Number(data[i][8]) == 3) {
                jxf_sum += Number(data[i][11]);
            }
        }

        
        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 - zcf_sum;
                qd["_children"][i]['材料费'] = clf_sum;
                qd["_children"][i]['人工费'] = rgf_sum;
                qd["_children"][i]['主材费'] = zcf_sum;
                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"] = this.handleJGC(copy(data));
                qd["_children"][i]['清单编码'] = renameDingE(oldname, xuhao, huan);

            }
        }
    }


    updateDercj_(row, data, xuhao, yuban, rcjbc, mode=0) {///change 一条定额 inplace, 汇总一条定额的rcj, xuhao is for rename, yuban is 预拌砂浆
        console.log("data updated");
        //处理附注
        let huan = false;//换
        let data_normal = [["ID", "人材机编码", "名称", "规格型号", "单位", "单价", "产地", 
        "供应厂商", "人材机类别", "甲供标志", "含量", "合价", "暂估价标志", "主要材料标志", "主材标志", "设备标志", 'key', 'bc' ]];//正常部分，不包括补充
        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")) {//新数据
            de['dercj'] = copy(de['rcjdg']);
            if (de.hasOwnProperty('fuzhu')) {//没强行改过含量
                for(let j = 1; j < de['rcjdg'].length; j++) {
                    let origin = Number(de['rcjdg'][j][10]);
                    let bianhao_huan = '';
                    let name_huan = '';
                    let new_jia = 0;
                    for(let i = 0; i < de['fuzhu'].length; i++) {
                        let selected = de['fuzhu'][i];//selected is 结构化的处理信息
                        let target = selected[0];
                        if (match_target(de['rcjdg'][j][1], de['rcjdg'][j][2], target, selected[1])) {
				console.log('match fuzhu')
                            if (selected[2] == '系数' || selected[2] == '商品砼系数' || selected[2] == '除此机械外') {
                                origin = origin * (Number(selected[3]) ** Number(selected[5]));

                            } else if (selected[2] == '含量' || selected[2] == '商品砼含量') {
                                origin = Number(selected[3]);
                            } else if (selected[2] == '调整' || selected[2] == '商品砼调整') {
                                origin = origin + Number(selected[3]) * Number(selected[5]);
                            } else if (selected[2] == '调比') {
                                origin = origin + Number(selected[3]) * Number(selected[5]) / Number(100);
                            } else if (selected[2] == '次方') {
                                origin = origin * (Number(selected[3]) ** Number(selected[5]));
                            } else if (selected[2] == '叠加备注') {

                            } else if (selected[2] == '换机械系数') {
                                bianhao_huan = selected[4];
                                name_huan = this.mapper[bianhao_huan][0];
                                new_jia = this.mapper[bianhao_huan][1];
                                origin = origin * (Number(selected[3]) ** Number(selected[5]));
                            } else if (selected[2] == '换材料系数') {
                                bianhao_huan = selected[4];
                                name_huan = this.mapper[bianhao_huan][0];
                                new_jia = this.mapper[bianhao_huan][1];
                                origin = origin * (Number(selected[3]) ** Number(selected[5]));
                            } else if (selected[2] == '使用泵送') {
                                if (de['rcjdg'][j][2].includes('C20')) {
                                    bianhao_huan = '80212103';
                                    name_huan = '(C20泵送商品砼)';
                                    new_jia = 342;
                                }
                                if (de['rcjdg'][j][2].includes('C30')) {
                                    bianhao_huan = '80212105';
                                    name_huan = '(C30泵送商品砼)';
                                    new_jia = 362;
                                }

                            } else if (selected[2] == '使用非泵送') {
                                if (de['rcjdg'][j][2].includes('C20')) {
                                    bianhao_huan = '80212115';
                                    name_huan = '(C20非泵送商品砼)';
                                    new_jia = 333;
                                }
                                if (de['rcjdg'][j][2].includes('C30')) {
                                    bianhao_huan = '80212117';
                                    name_huan = '(C30非泵送商品砼)';
                                    new_jia = 353;
                                }
                            }
                            else {
                                throw new Error('无法处理的附注'.concat(selected[2]));
                            }    
                        }
                    }       
                    if (bianhao_huan == '') {
                                
                    } else {
                                de['dercj'][j][1] = bianhao_huan;//编号
                                de['dercj'][j][2] = name_huan;//mc
                                de['dercj'][j][5] = new_jia;//jiage
                    }                  
                    de['dercj'][j][10] =  origin;
                    de['dercj'][j][11] = Number(de['dercj'][j][5]) * origin;
                }
            }
            //基于底稿判断换
            for(let j = 1; j < de['dercj'].length; j++) {
                for (let k = 0; k < data.length; k++) {
                    if (data[k][16] == de['dercj'][j][16]) {
                        let datak2 = data[k][2];
                        if (datak2.includes('（湿拌砂浆）')) {
                            datak2 = datak2.replace('（湿拌砂浆）', '');
                        }
                        if (datak2.includes('（干拌（混）砂浆）')) {
                            datak2 = datak2.replace('（干拌（混）砂浆）', '');
                        }
                        if (de['dercj'][j][2] == datak2) {//名称
                            
                        } else {
                            huan = true;
                        }    
                    }
                }        
            }
            if (mode == 1) {
                data_normal = de['dercj'];
                huan = false;
            } else {
                data_normal = copy(data.filter(x=>x[17] != 'true'));
            }
        } else {////单项定额没有底稿，老数据没底搞，无法判断换部换，暂时统一认为不换
            //强行改含量
            data_normal = copy(data.filter(x=>x[17] != 'true'));
            //data = de['dercj'];
        }

        //处理补充
        for(let i = 0; i < rcjbc.length; i++) {
            data_normal.push(['', rcjbc[i]['人材机编码'], rcjbc[i]['名称'], rcjbc[i]['规格型号'], rcjbc[i]['单位'], rcjbc[i]['单价'], rcjbc[i]['产地'], rcjbc[i]['供应厂商'], rcjbc[i]['人材机类别'], rcjbc[i]['甲供标志'], rcjbc[i]['含量'], '', rcjbc[i]['暂估价标志'],rcjbc[i]['主要材料标志'],rcjbc[i]['主材标志'],rcjbc[i]['设备标志'], rcjbc[i]['id'], 'true']);
            for (let k = 0; k < data.length; k++) {
                if (data[k][16] == rcjbc[i]['id']) {
                    let datak2 = data[k][2];
                    if (datak2.includes('（湿拌砂浆）')) {
                        datak2 = datak2.replace('（湿拌砂浆）', '');
                    }
                    if (datak2.includes('（干拌（混）砂浆）')) {
                        datak2 = datak2.replace('（干拌（混）砂浆）', '');
                    }
                    if (rcjbc[i]['名称'] == datak2) {//名称
                        
                    } else {
                        if (mode == 2) {
            
                        } else {
                            huan = true;
                        }
                    }    
                }
            }  
        }

        if (yuban.length > 0) {//处理预拌砂浆
            if (yuban.includes('1')) {//与换无关
                for(let i = 1; i < data_normal.length; i++) {
                    if (data_normal[i][4]=='工日') {
                        data_normal[i][10] = Number(data_normal[i][10]) - 0.45;
                    }
                    if (data_normal[i][2].includes('搅拌机')) {
                        data_normal[i][10] = 0;
                    }
                    if (data_normal[i][2].includes('砂浆') && !data_normal[i][2].includes('搅拌机')) {
                        data_normal[i][2] = data_normal[i][2].concat('（湿拌砂浆）')
                    }
                }
                if (mode == 0) {
                    data_normal  = copy(data);
                } else if (mode == 1) {
                    //data_normal = data_normal.filter(x=>x[17]!='true');
                    //data_normal = data_normal.concat(data.filter(x=> x[17] == 'true'));
                } else if (mode == 2) {
                    let data_normal_2 = copy(data_normal);
                    data_normal = data.filter(x=>x[17]!='true');
                    data_normal = data_normal.concat(data_normal_2.filter(x=> x[17] == 'true'));
                }

            } else if (yuban.includes('2')) {//与换无关
                
                let added = [];
                for(let i = 1; i < data_normal.length; i++) {
                  let origin = 0;
                  if (data_normal[i][4]=='工日') {
                    data_normal[i][10] = Number(data_normal[i][10]) - 0.3;
                  }
                  if (data_normal[i][2].includes('搅拌机')) {
                    data_normal[i][10] = 0;
                  }
                  if (data_normal[i][2].includes('砂浆') && !data_normal[i][2].includes('搅拌机')) {
                    data_normal[i][2] = data_normal[i][2].concat('（干拌（混）砂浆）');
                    origin = Number(data_normal[i][10]); 
                    data_normal[i][10] = origin * 1.75;
                    added.push(['', 'S00001', '水', '', 't', '4.70', '', '', '2', 'false', (origin * 0.29).toString(), ''/**hj */, ''/**zgj */,''/**zycl */,''/**zc */,''/**sb */,'',data_normal[i][17]]);
                    added.push(['', 'JD0001', '其他机械费（电）', '', '度', '0.65', '', '', '3', 'false', (origin * 2.15).toString(), ''/**hj */, ''/**zgj */,''/**zycl */,''/**zc */,''/**sb */, '',data_normal[i][17]]);
    
                  }

                }
                data_normal = data_normal.concat(added);
                if (mode == 0) {
                    data_normal  = copy(data);
                } else if (mode == 1) {
                    //data_normal = data_normal.filter(x=>x[17]!='true');
                    //data_normal = data_normal.concat(data.filter(x=> x[17] == 'true'));
                } else if (mode == 2) {
                    let data_normal_2 = copy(data_normal);
                    data_normal = data.filter(x=>x[17]!='true');
                    data_normal = data_normal.concat(data_normal_2.filter(x=> x[17] == 'true'));
                }


            } else if (yuban.includes('3')) {//与换无关
                let added = [];
                for(let i = 1; i < data_normal.length; i++) {
                  let origin = 0;
                  if (data_normal[i][4]=='工日') {
                    data_normal[i][10] = Number(data_normal[i][10]) - 0.2;
                  } 
                  if (data_normal[i][2].includes('砂浆') && !data_normal[i][2].includes('搅拌机')) {
                    data_normal[i][2] = data_normal[i][2].concat('（干拌（混）砂浆）');
                    origin = Number(data_normal[i][10]); 
                    data_normal[i][10] = origin * 1.75;
                    added.push(['', 'S00001', '水', '', 't', '4.70', '', '', '2', 'false', (origin * 0.29).toString(), '', '','','','','',data_normal[i][17]]);

                  }
                }
                data_normal = data_normal.concat(added);
                if (mode == 0) {
                    data_normal  = copy(data);
                } else if (mode == 1) {
                    //data_normal = data_normal.filter(x=>x[17]!='true');
                    //data_normal = data_normal.concat(data.filter(x=> x[17] == 'true'));
                } else if (mode == 2) {
                    let data_normal_2 = copy(data_normal);
                    data_normal = data.filter(x=>x[17]!='true');
                    data_normal = data_normal.concat(data_normal_2.filter(x=> x[17] == 'true'));
                }


            } else {
                let data_normal_2 = [["ID", "人材机编码", "名称", "规格型号", "单位", "单价", "产地", 
            "供应厂商", "人材机类别", "甲供标志", "含量", "合价", "暂估价标志", "主要材料标志", "主材标志", "设备标志", 'key', 'bc' ]];
                for(let i = 1; i < data_normal.length; i++) {
                    let bc = data_normal[i][17];
                    let child = addChildren(10, data_normal[i][1], data_normal[i][10], data_normal[i][17], data_normal[i][16]);
                    if (child.length > 0) {

                    } else {
                        child = addChildren(40, data_normal[i][1], data_normal[i][10], data_normal[i][17], data_normal[i][16]);
                        if (child.length > 0) {

                        } else {
                            child = addChildren(50, data_normal[i][1], data_normal[i][10], data_normal[i][17], data_normal[i][16]);
                        }
                    }
                    if (child.length > 0) {//拆分
                        for(let j = 0; j < child.length; j++) {
                            data_normal_2.push(child[j]);
                            if (bc == 'true') {
                                for (let k = 0; k < data.length; k++) {
                                    if (data[k][16] == child[j][16]) {
                                        let datak2 = data[k][2];
                                    
                                        if (child[j][2] == datak2) {//名称
                                        
                                        } else {
                                            if (mode > 0) {

                                            } else {
                                                huan = true;
                                            }
                                        }
                                    
                                    }
                                }  
                            } else if (mode != 1){
                                for (let k = 0; k < data.length; k++) {
                                    if (data[k][16] == child[j][16]) {
                                        let datak2 = data[k][2];
                                    
                                        if (child[j][2] == datak2) {//名称
                                        
                                        } else {
                                            huan = true;
                                        }
                                    
                                    }
                                }  
                            }
                        }


                    } else {
                        data_normal_2.push(data_normal[i]);
                    }
                }
                if (mode == 0) {
                    data_normal = copy(data);
                } else if (mode == 2) {
                    data_normal = data.filter(x=>x[17]!='true');
                    data_normal = data_normal.concat(data_normal_2.filter(x=> x[17] == 'true'));
                } else if (mode == 1) {
                    data_normal = data_normal_2;
                    //data_normal = data_normal.concat(data.filter(x=> x[17] == 'true'));
                }
            }
            
        } else {//没有预拌
            let data_normal_2 = [["ID", "人材机编码", "名称", "规格型号", "单位", "单价", "产地", 
            "供应厂商", "人材机类别", "甲供标志", "含量", "合价", "暂估价标志", "主要材料标志", "主材标志", "设备标志", 'key', 'bc' ]];
            for(let i = 1; i < data_normal.length; i++) {
                let bc = data_normal[i][17];
                let child = addChildren(10, data_normal[i][1], data_normal[i][10], data_normal[i][17], data_normal[i][16]);
                if (child.length > 0) {

                } else {
                    child = addChildren(40, data_normal[i][1], data_normal[i][10], data_normal[i][17], data_normal[i][16]);
                    if (child.length > 0) {

                    } else {
                        child = addChildren(50, data_normal[i][1], data_normal[i][10], data_normal[i][17], data_normal[i][16]);
                    }
                }
                if (child.length > 0) {//拆分
                    for(let j = 0; j < child.length; j++) {
                        data_normal_2.push(child[j]);
                        if (bc == 'true') {
                            for (let k = 0; k < data.length; k++) {
                                if (data[k][16] == child[j][16]) {
                                    let datak2 = data[k][2];
                                    
                                    if (child[j][2] == datak2) {//名称
                                        
                                    } else {
                                        if (mode > 0) {

                                        } else {
                                            huan = true;
                                        }
                                    }
                                    
                                }
                            }  
                        } else if (mode != 1){
                            for (let k = 0; k < data.length; k++) {
                                if (data[k][16] == child[j][16]) {
                                    let datak2 = data[k][2];
                                    
                                    if (child[j][2] == datak2) {//名称
                                        
                                    } else {
                                        huan = true;
                                    }
                                    
                                }
                            }  
                        }
                    }


                } else {
                    data_normal_2.push(data_normal[i]);
                }

            }

            if (mode == 0) {
                data_normal = copy(data);
            } else if (mode == 2) {
                data_normal = data.filter(x=>x[17]!='true');
                data_normal = data_normal.concat(data_normal_2.filter(x=> x[17] == 'true'));
            } else if (mode == 1) {
                data_normal = data_normal_2;
                //data_normal = data_normal.concat(data.filter(x=> x[17] == 'true'));
            }

        }        
     
        data = copy(data_normal);

        //模拟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;
        let zcf_sum = 0;
        for(let i = 1; i < data.length; i++) {
            console.log(data[i][1]);
	    if (data[i][1].includes('000FE') && data[i][4] == '%')continue;//azfy
            if (data[i][1]=='00EXP001' && data[i][4] == '%'){//回程费占人工费
                continue;    
            }
            if (data[i][1]=='99EXP007' && data[i][4] == '%'){//回程费占机械费
                continue;    
            }
            if (data[i][1]=='99EXP022' && data[i][4] == '%'){//回程费占机械费
                continue;    
            }
            if (data[i][1]=='31130104' && data[i][4] == '%'){//回程费占材料费
                continue;    
            }
            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 (data[i][14] == 'true') {
                    zcf_sum += Number(data[i][11]);
                }
            }
            if (Number(data[i][8]) == 3) {
                jxf_sum += Number(data[i][11]);
            }
        }
        console.log("sum=".concat(sum));
        //处理百分比费用
        for(let i = 1; i < data.length; i++) {
            if (data[i][1]=='00EXP001' && data[i][4] == '%'){//回程费占人工费
                data[i][11] = Number(data[i][10]) * rgf_sum / Number(100);   
            }
            if (data[i][1]=='99EXP007' && data[i][4] == '%'){//回程费占机械费
                data[i][11] = Number(data[i][10]) * jxf_sum / Number(100);    
            }
            if (data[i][1]=='99EXP022' && data[i][4] == '%'){//回程费占机械费
                data[i][11] = Number(data[i][10]) * jxf_sum / Number(100);    
            }
            if (data[i][1]=='31130104' && data[i][4] == '%'){//回程费占材料费
                data[i][11] = Number(data[i][10]) * clf_sum / Number(100);    
            }

        }
        sum = 0;
        rgf_sum = 0;
        jxf_sum = 0;
        clf_sum = 0;
        zcf_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 (data[i][14] == 'true') {
                    zcf_sum += Number(data[i][11]);
                }
            }
            if (Number(data[i][8]) == 3) {
                jxf_sum += Number(data[i][11]);
            }
        }
        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 - zcf_sum;
                qd["_children"][i]['材料费'] = clf_sum;
                qd["_children"][i]['人工费'] = rgf_sum;
                qd["_children"][i]['主材费'] = zcf_sum;
                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"] = this.handleJGC(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];
        this.updateFootprint(qd['key']);
        let bm = de['清单编码'];
        let alreadyFuzhu = extractFuzhu(bm);//[xuhao]
        


        
        this.updateDercj_(row, data, alreadyFuzhu, de['yuban'], de['rcjbc']);
        //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]
        


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


    }

    //xuhao=['1*1','3*1']
    updateBeizhu(row, selected, xuhao) {//xuhao is for rename, selected is 结构化的处理信息
        let qd = this.cache.filter(x=>x["_children"].filter(y=>y['key']==row).length > 0)[0];
        if (!qd) return [null, null];
        this.updateFootprint(qd['key']);
        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, de['yuban'], de['rcjbc'], 1);

        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, 1);

        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, zhuanye, row) {
        let qd = this.cache.filter(x=>x["_children"].filter(y=>y['key']==row).length > 0)[0];
        this.updateFootprint(qd['key']);
        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];
        this.updateFootprint(qd['key']);
        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, copy(this.cache)];
        }
        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)];






    }


    updateDeMingcheng(value, row) {
        let qd = this.cache.filter(x=>x["_children"].filter(y=>y['key']==row).length > 0)[0];
        this.updateFootprint(qd['key']);
        let de = qd["_children"].filter(x=>x['key'] == row)[0];
        de['名称'] = value;

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






    }


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






    }

    azfy_djcs_eligible(selectedRow) {
        if (this.cache_djcs.filter(x=>x['key'] == selectedRow).length > 0) {
            return true;
        } else {
            return false;
        }

    }

    azfy_mock(row, dinge, selected) {
        let res = JSON.parse(dinge);
        let keys = Object.keys(res['DEBH']);
        let key = keys[0];
        let tips = null;
        if (res['actual_zhuanye'] == 30) {
            tips = azfy(res['DEBH'][key], res['GCLMC'][key]);
        }
        if (res['actual_zhuanye'] == 60) {
            tips = xsazfy(res['DEBH'][key], res['GCLMC'][key]);
        }
        if (res['actual_zhuanye'] == 10) {
            tips = tjazfy(res['DEBH'][key], res['GCLMC'][key]);
        }


        if (tips != null) {
            res['rgde'] = tips['rgde'];
            res['clde'] = tips['clde'];
            res['jxde'] = tips['jxde'];
            res['azfytag'] = tips['azfytag'];
        }
        let qd = this.cache.filter(x=>x['key'] == row)[0];
        let dercj = [["ID", "人材机编码", "名称", "规格型号", "单位", "单价", "产地", 
                "供应厂商", "人材机类别", "甲供标志", "含量", "合价", "暂估价标志", "主要材料标志", "主材标志", "设备标志", 'key', 'bc' ]];
        for(let i = 0; i < selected.length; i++) {
            let rgf = selected[i]['人工费'];
            let clf = selected[i]['材料费'];
            let jxf = selected[i]['机械费'];
            let sl = selected[i]['数量'];
            if (res['azfytag'][0] == '人工费') {
                let sum = Number(sl) * Number(rgf) * Number(res['azfytag'][1]) / Number(100);
                dercj.push(['', res['rgde'][0]['CLBH'], res['rgde'][0]['CLMC'], '', '元', 
                    '1', '', '', '1', '', Number(sum) * Number(res['azfytag'][2]) / Number(100), Number(sum) * Number(res['azfytag'][2]) / Number(100),
                    '', '', '', '', uuidv4(), '' ]);
                dercj.push(['', res['clde'][0]['CLBH'], res['clde'][0]['CLMC'], '', '元', 
                    '1', '', '', '2', '', Number(sum) * Number(res['azfytag'][3]) / Number(100), Number(sum) * Number(res['azfytag'][3]) / Number(100),
                    '', '', '', '', uuidv4(), '' ]);
                dercj.push(['', res['jxde'][0]['jxbh'], res['jxde'][0]['jxmc'], '', '元', 
                    '1', '', '', '3', '', Number(sum) * Number(res['azfytag'][4]) / Number(100), Number(sum) * Number(res['azfytag'][4]) / Number(100),
                    '', '', '', '', uuidv4(), '' ]);
            } else if (res['azfytag'][0] == '人工费+机械费') {
                let sum = Number(sl) * (Number(jxf) + Number(rgf)) * Number(res['azfytag'][1]) / Number(100);
                dercj.push(['', res['rgde'][0]['CLBH'], res['rgde'][0]['CLMC'], '', '元', 
                    '1', '', '', '1', '', Number(sum) * Number(res['azfytag'][2]) / Number(100), Number(sum) * Number(res['azfytag'][2]) / Number(100),
                    '', '', '', '', uuidv4(), '' ]);
                dercj.push(['', res['clde'][0]['CLBH'], res['clde'][0]['CLMC'], '', '元', 
                    '1', '', '', '2', '', Number(sum) * Number(res['azfytag'][3]) / Number(100), Number(sum) * Number(res['azfytag'][3]) / Number(100),
                    '', '', '', '', uuidv4(), '' ]);
                dercj.push(['', res['jxde'][0]['jxbh'], res['jxde'][0]['jxmc'], '', '元', 
                    '1', '', '', '3', '', Number(sum) * Number(res['azfytag'][4]) / Number(100), Number(sum) * Number(res['azfytag'][4]) / Number(100),
                    '', '', '', '', uuidv4(), '' ]);

            }
        }

        let newKey = uuidv4();
        if (!qd.hasOwnProperty('_children')) {
            qd["_children"] = [];
        }
        qd["_children"].push({
                    '操作': '',
                    '序号': null,
                    '清单编码': res['DEBH'][key],
                    '名称': res['GCLMC'][key],
                    '项目特征': null,
                    '计算规则': tips != null ? tips['sm'] : '',
                    '单位': res['DW'][key],
                    '数量': '1',
                    '综合单价': '0',
                    '合价': '0',
                    '人工费': '0',
                    '主材费': '0',
                    '设备费': '0',
                    '辅材费': '0',
                    '材料费': '0',
                    '机械费': '0',
                    '管理费': '0',
                    '利润': '0',
                    '暂估价': null,
                    '综合人工工日': null,
                    '备注': null,
                    "dercj": dercj,
                    'rcjdg': dercj.map(x=>[x[0], x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11], x[12], x[13], x[14], x[15], x[16], x[17]]),
                    'key' :   newKey,
                    "fuzhuEnable": false,
                    'yuban': [],
                    'rcjbc': [],
                    'azfytag': []
    
                    
        });

        this.updateDercj_(newKey, dercj, [], [], [], 1);
        //this.updateDercj_(newKey, dercj, []);
        let summarized = this.summarize(this.cache);
        this.push_op(copy(summarized));
        this.cache = copy(summarized);
                
        return [true, copy(this.cache), newKey];

    }
    azfy_djcs(row, dinge, selected) {
        let res = JSON.parse(dinge);
        let keys = Object.keys(res['DEBH']);
        let key = keys[0];
        let tips = null;
        if (res['actual_zhuanye'] == 30) {
            tips = azfy(res['DEBH'][key], res['GCLMC'][key]);
        }
        if (res['actual_zhuanye'] == 60) {
            tips = xsazfy(res['DEBH'][key], res['GCLMC'][key]);
        }
        if (res['actual_zhuanye'] == 10) {
            tips = tjazfy(res['DEBH'][key], res['GCLMC'][key]);
        }


        if (tips != null) {
            res['rgde'] = tips['rgde'];
            res['clde'] = tips['clde'];
            res['jxde'] = tips['jxde'];
            res['azfytag'] = tips['azfytag'];
        }
        let qd = this.cache_djcs.filter(x=>x['key'] == row)[0];
        let dercj = [["ID", "人材机编码", "名称", "规格型号", "单位", "单价", "产地", 
                "供应厂商", "人材机类别", "甲供标志", "含量", "合价", "暂估价标志", "主要材料标志", "主材标志", "设备标志", 'key', 'bc' ]];
        for(let i = 0; i < selected.length; i++) {
            let rgf = selected[i]['人工费'];
            let clf = selected[i]['材料费'];
            let jxf = selected[i]['机械费'];
            let sl = selected[i]['数量'];
            if (res['azfytag'][0] == '人工费') {
                let sum = Number(sl) * Number(rgf) * Number(res['azfytag'][1]) / Number(100);
                dercj.push(['', res['rgde'][0]['CLBH'], res['rgde'][0]['CLMC'], '', '元', 
                    '1', '', '', '1', '', Number(sum) * Number(res['azfytag'][2]) / Number(100), Number(sum) * Number(res['azfytag'][2]) / Number(100),
                    '', '', '', '', uuidv4(), '' ]);
                dercj.push(['', res['clde'][0]['CLBH'], res['clde'][0]['CLMC'], '', '元', 
                    '1', '', '', '2', '', Number(sum) * Number(res['azfytag'][3]) / Number(100), Number(sum) * Number(res['azfytag'][3]) / Number(100),
                    '', '', '', '', uuidv4(), '' ]);
                dercj.push(['', res['jxde'][0]['jxbh'], res['jxde'][0]['jxmc'], '', '元', 
                    '1', '', '', '3', '', Number(sum) * Number(res['azfytag'][4]) / Number(100), Number(sum) * Number(res['azfytag'][4]) / Number(100),
                    '', '', '', '', uuidv4(), '' ]);
            } else if (res['azfytag'][0] == '人工费+机械费') {
                let sum = Number(sl) * (Number(jxf) + Number(rgf)) * Number(res['azfytag'][1]) / Number(100);
                dercj.push(['', res['rgde'][0]['CLBH'], res['rgde'][0]['CLMC'], '', '元', 
                    '1', '', '', '1', '', Number(sum) * Number(res['azfytag'][2]) / Number(100), Number(sum) * Number(res['azfytag'][2]) / Number(100),
                    '', '', '', '', uuidv4(), '' ]);
                dercj.push(['', res['clde'][0]['CLBH'], res['clde'][0]['CLMC'], '', '元', 
                    '1', '', '', '2', '', Number(sum) * Number(res['azfytag'][3]) / Number(100), Number(sum) * Number(res['azfytag'][3]) / Number(100),
                    '', '', '', '', uuidv4(), '' ]);
                dercj.push(['', res['jxde'][0]['jxbh'], res['jxde'][0]['jxmc'], '', '元', 
                    '1', '', '', '3', '', Number(sum) * Number(res['azfytag'][4]) / Number(100), Number(sum) * Number(res['azfytag'][4]) / Number(100),
                    '', '', '', '', uuidv4(), '' ]);

            }
        }

        let newKey = uuidv4();
        if (!qd.hasOwnProperty('_children')) {
            qd["_children"] = [];
        }
        qd["_children"].push({
                    '操作': '',
                    '序号': null,
                    '清单编码': res['DEBH'][key],
                    '名称': res['GCLMC'][key],
                    '项目特征': null,
                    '计算规则': tips != null ? tips['sm'] : '',
                    '单位': res['DW'][key],
                    '数量': '1',
                    '综合单价': '0',
                    '合价': '0',
                    '人工费': '0',
                    '主材费': '0',
                    '设备费': '0',
                    '辅材费': '0',
                    '材料费': '0',
                    '机械费': '0',
                    '管理费': '0',
                    '利润': '0',
                    '暂估价': null,
                    '综合人工工日': null,
                    '备注': null,
                    "dercj": dercj,
                    'rcjdg': dercj.map(x=>[x[0], x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11], x[12], x[13], x[14], x[15], x[16], x[17]]),
                    'key' :   newKey,
                    "fuzhuEnable": false,
                    'yuban': [],
                    'rcjbc': [],
                    'azfytag': []
    
                    
        });

        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 [true, copy(this.cache_djcs), newKey];

    }


    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", "人材机编码", "名称", "规格型号", "单位", "单价", "产地", 
                "供应厂商", "人材机类别", "甲供标志", "含量", "合价", "暂估价标志", "主要材料标志", "主材标志", "设备标志", "key", 'bc']];
                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'],
                    '', '', '', '', uuidv4(), "false" ]);
                }
                for(let i = 0; i < res['clde'].length; i++) {
                    let hit = false;
                    let jg = null;
                    let bh = res['clde'][i]['CLBH'];
                    for(let j = 0; j < this.jiagongcai.length; j++) {
                        if (this.jiagongcai[j]['材料编号'] == bh) {
                            hit = true;
                            jg = this.jiagongcai[j]['单价'];
                        }
                    }
                    if (hit) {
                        dercj.push(['', res['clde'][i]['CLBH'], res['clde'][i]['CLMC'], '', res['clde'][i]['JLDW'], 
                    jg, '', '', '2', 'true', res['clde'][i]['SL'], res['clde'][i]['HJ'],
                    '', '', '', '', uuidv4(), 'false' ]);
                    } else {
                       /* if (res['clde'][i].hasOwnProperty('children')) {
                            let parent = uuidv4();
                            let children = [];
                            let child_data = res['clde'][i]['children'];
                            for(let j = 0; j < child_data.length; j++) {
                                let id = uuidv4();
                                children.push(id);
                                dercj.push(['', child_data[j]['CLBH'], child_data[j]['CLMC'], '', child_data[j]['JLDW'], 
                                   child_data[j]['YSJG'], '', '', '2', 'false', child_data[j]['SL'], child_data[j]['HJ'],
                                   '', '', '', '', id, 'false','false', [parent], [] ]);
                            }
                            dercj.push(['', res['clde'][i]['CLBH'], res['clde'][i]['CLMC'], '', res['clde'][i]['JLDW'], 
                                res['clde'][i]['YSJG'], '', '', '2', 'false', res['clde'][i]['SL'], res['clde'][i]['HJ'],
                                '', '', '', '', parent, 'false','true', [], children ]);

                        } else {*/
                             dercj.push(['', res['clde'][i]['CLBH'], res['clde'][i]['CLMC'], '', res['clde'][i]['JLDW'], 
                              res['clde'][i]['YSJG'], '', '', '2', 'false', res['clde'][i]['SL'], res['clde'][i]['HJ'],
                              '', '', '', '', uuidv4(), 'false' ]);
                        
                    }
                    
                }
                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'],
                    '', '', '', '',uuidv4(), 'false' ]);
                }
                let newKey = uuidv4();
                if (!qd.hasOwnProperty('_children')) {
                    qd["_children"] = [];
                }
                let newdercj = copy(dercj).map(x=>[x[0], x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11], x[12], x[13], x[14], x[15], x[16], x[17]]);
                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": newdercj,
                    'rcjdg': dercj,
                    'key' :   newKey,
                    "fuzhuEnable": true
    
                    
                });
                this.updateDercj_djcs_(newKey, newdercj, []);
                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) {
            this.updateFootprint(row);
            
                let res = copy(dingeclick);
                let keys = Object.keys(res['DEBH']);
                let key = keys[0];
                let tips = null;
                if (res['actual_zhuanye'] == 30) {
                    tips = azfy(res['DEBH'][key], res['GCLMC'][key]);
                }
                
                if (res['actual_zhuanye'] == 60) {
                    tips = xsazfy(res['DEBH'][key], res['GCLMC'][key]);
                }
                if (res['actual_zhuanye'] == 10) {
                    tips = tjazfy(res['DEBH'][key], res['GCLMC'][key]);
                }
                if (tips != null) {
                      res['rgde'] = tips['rgde'];
                      res['clde'] = tips['clde'];
                      res['jxde'] = tips['jxde'];
                }
                let qd = this.cache.filter(x=>x['key'] == row)[0];
                let dercj = [["ID", "人材机编码", "名称", "规格型号", "单位", "单价", "产地", 
                "供应厂商", "人材机类别", "甲供标志", "含量", "合价", "暂估价标志", "主要材料标志", "主材标志", "设备标志", 'key', 'bc' ]];
                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'],
                    '', '', '', '', uuidv4(), 'false' ]);
                }
                for(let i = 0; i < res['clde'].length; i++) {
                    let hit = false;
                    let jg = null;
                    let bh = res['clde'][i]['CLBH'];
                    for(let j = 0; j < this.jiagongcai.length; j++) {
                        if (this.jiagongcai[j]['材料编号'] == bh) {
                            hit = true;
                            jg = this.jiagongcai[j]['单价'];
                        }
                    }
                    if (hit) {
                        dercj.push(['', res['clde'][i]['CLBH'], res['clde'][i]['CLMC'], '', res['clde'][i]['JLDW'], 
                           jg, '', '', '2', 'true', res['clde'][i]['SL'], res['clde'][i]['HJ'],
                           '', '', '', '', uuidv4(), 'false' ]);
                    } else {
                        /*if (res['clde'][i].hasOwnProperty('children') && res['clde'][i]['CLMC'].includes('砂浆')) {
                            let parent = uuidv4();
                            let children = [];
                            let child_data = res['clde'][i]['children'];
                            for(let j = 0; j < child_data.length; j++) {
                                let id = uuidv4();
                                children.push(id);
                                dercj.push(['', child_data[j]['CLBH'], child_data[j]['CLMC'], '', child_data[j]['JLDW'], 
                    child_data[j]['YSJG'], '', '', '2', 'false', child_data[j]['SL'], child_data[j]['HJ'],
                    '', '', '', '', id, 'false','false', [parent], [] ]);
                            }
                            dercj.push(['', res['clde'][i]['CLBH'].toString(), res['clde'][i]['CLMC'], '', res['clde'][i]['JLDW'], 
                    res['clde'][i]['YSJG'], '', '', '2', 'false', res['clde'][i]['SL'], res['clde'][i]['HJ'],
                    '', '', '', '', parent, 'false','true', [], children ]);

                        } else {*/
                            dercj.push(['', res['clde'][i]['CLBH'].toString(), res['clde'][i]['CLMC'], '', res['clde'][i]['JLDW'], 
                                res['clde'][i]['YSJG'], '', '', '2', 'false', res['clde'][i]['SL'], res['clde'][i]['HJ'],
                                '', '', '', '', uuidv4(), 'false' ]);
                        
                        
                    }
                    
                }
                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'],
                    '', '', '', '', uuidv4(), 'false']);
                }
                let newKey = uuidv4();
                if (!qd.hasOwnProperty('_children')) {
                    qd["_children"] = [];
                }
                let newdercj = copy(dercj).map(x=>[x[0], x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11], x[12], x[13], x[14], x[15], x[16], x[17]]);
                qd["_children"].push({
                    '操作': '',
                    '序号': null,
                    '清单编码': res['DEBH'][key],
                    '名称': res['GCLMC'][key],
                    '项目特征': null,
                    '计算规则': tips != null ? tips['sm'] : '',
                    '单位': res['DW'][key],
                    '数量': '1',
                    '综合单价': '0',
                    '合价': '0',
                    '人工费': '0',
                    '主材费': '0',
                    '设备费': '0',
                    '辅材费': '0',
                    '材料费': '0',
                    '机械费': '0',
                    '管理费': '0',
                    '利润': '0',
                    '暂估价': null,
                    '综合人工工日': null,
                    '备注': null,
                    "dercj": newdercj,
                    'rcjdg': (dercj),
                    'key' :   newKey,
                    "fuzhuEnable": true,
                    'yuban': [],
                    'rcjbc': [],
                    'azfytag': tips != null ? tips['azfytag'] : []
    
                    
                });
                this.updateDercj_(newKey, dercj, [], [], [], 1);
                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, maxN, extra) {
        //let bh = danxiangdinge_index(this.cache);
	     let result =  (maxN + 1).toString();
        result = result.padStart(5, '0');
        let bh= "D".concat(result);
        
        if (this.cache.filter(x=>x['key'] == row).length > 0) {
            this.updateFootprint(row);
            let selected = this.cache.filter(x=>x['key'] == row)[0];
            let danwei = selected["单位"];
            let mingcheng = extra;//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", "人材机编码", "名称", "规格型号", "单位", "单价", "产地", 
                "供应厂商", "人材机类别", "甲供标志", "含量", "合价", "暂估价标志", "主要材料标志", "主材标志", "设备标志", 'key', 'bc' ],
                   ['', bh, mingcheng, '', danwei, '', '', '', '2', '', '1', '', '',  '', '', '', uuidv4(), '' ]
                      ],
                'key' :   uuidv4(),
                "fuzhuEnable": false,
                'yuban': [],
                'rcjbc' : [],
                'azfytag': []

                
            });
            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", "人材机编码", "名称", "规格型号", "单位", "单价", "产地", 
                "供应厂商", "人材机类别", "甲供标志", "含量", "合价", "暂估价标志", "主要材料标志", "主材标志", "设备标志", "key" , "bc" ],
                   ['', bh, mingcheng, '', danwei, '', '', '', '2', '', '1', '', '',  '', '', '', uuidv4(), "" ]
                      ],
                '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];
        }

    }

    handleYuban(row, selected) {
        let qd = this.cache.filter(x=>x["_children"].filter(y=>y['key']==row).length > 0)[0];
        if (!qd) return [null, null];
        this.updateFootprint(qd['key']);
        let de = qd["_children"].filter(x=>x['key'] == row)[0];
        let bm = de['清单编码'];
        let alreadyFuzhu = extractFuzhu(bm);//[xuhao]
        if (de.hasOwnProperty("rcjdg")) {//底稿

        } else {///老数据不能有底稿，附注功能也不使能，预拌也不能使
            //de['rcjdg'] = copy(de['dercj']);

        }
        de['yuban'] = copy(selected);
        this.updateDercj_(row, de['dercj'], alreadyFuzhu, selected, de['rcjbc'], 1);

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

    handleRcjbc(row, rcjbc) {
        let qd = this.cache.filter(x=>x["_children"].filter(y=>y['key']==row).length > 0)[0];
        if (!qd) return [null, null];
        this.updateFootprint(qd['key']);
        let de = qd["_children"].filter(x=>x['key'] == row)[0];
        let bm = de['清单编码'];
        let alreadyFuzhu = extractFuzhu(bm);//[xuhao]
        if (de.hasOwnProperty("rcjdg")) {//底稿
    
        } else {///老数据不能有底稿，附注功能也不使能，预拌也不能使
            //de['rcjdg'] = copy(de['dercj']);
    
        }
        de['rcjbc'] = copy(rcjbc);
        this.updateDercj_(row, de['dercj'], alreadyFuzhu, de['yuban'], rcjbc, 2);
    
        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'])];
    }

    handleJGC(input) {
        for (let i = 0;i < input.length; i++) {
            let bh = input[i][1];
            let hit = false;
            let jg = 0;
            for(let j = 0; j < this.jiagongcai.length; j++) {
                if (this.jiagongcai[j]['材料编号'] == bh) {
                    hit = true;
                    //jg = this.jiagongcai[j]['单价'];
                }
            }
            if (hit) {
                input[i][9] = 'true';
            }
        }
        return input;
    }

    current(){
      return copy(this.cache)
    }   
}







export default new Service();
