import xml.etree.ElementTree as ET
from subdir import service, util
from bson.objectid import ObjectId
import uuid
from datetime import datetime



###############helper##################

def getDingercj_default(root, bh, bt, qdbm, debm):
    result = [["ID", "人材机编码", "名称", "规格型号", "单位", "单价", "产地", 
    "供应厂商", "人材机类别", "甲供标志", "含量", "合价", "暂估价标志", "主要材料标志", "主材标志", "设备标志" ]]
    #result.append(["ming cheng", "jin e", "zan gu jia", "anquan wenming fei", "guifei"])
    item = None
    for child in root:
    
        if child.tag == "Dxgcxx":
            for child1 in child:
                Dwgcbh = child1.attrib["Dwgcbh"]
                if Dwgcbh == bh:
                    item = child1
                    break
            ##result.append([child.attrib["Dxgcmc"], child.attrib["Je"], child.attrib["Zgj"], child.attrib["Aqwmf"], child.attrib["Gf"]])
    Fywj = None
    for child in item:
        if child.tag == 'Qdxm':
            Fywj= child
            break
    Rcjhz = None
    for child in item:
        if child.tag == 'Rcjhz':
            Rcjhz = child
            break
    kv = {}
    for entry in Rcjhz:
        kv[entry.attrib["RcjId"]]=entry

    container = None
    for child in Fywj:
        ##child is mx
        if child.tag == "Qdmx" and child.attrib["Qdbm"] == qdbm:
            zimu = child
            break
    box = None
    if not zimu:
        return result
    for child in zimu:
        if child.tag == "Qdxdezj":
            box = child
            break
    hlmx_parent = None
    for child in box:
        if child.attrib["Debm"] == debm:
            for grandchild in child:
                if grandchild.tag == "Qdxdercjhl":
                    hlmx_parent = grandchild
    for child in hlmx_parent:
        result.append([child.attrib["RcjId"], 
        kv[child.attrib["RcjId"]].attrib["RcjBm"], 
        kv[child.attrib["RcjId"]].attrib["Mc"], 
        kv[child.attrib["RcjId"]].attrib["Ggxh"], 
        kv[child.attrib["RcjId"]].attrib["Dw"], 
        kv[child.attrib["RcjId"]].attrib["Dj"], 
        kv[child.attrib["RcjId"]].attrib["Cd"], 
        kv[child.attrib["RcjId"]].attrib["Gycs"], 
        kv[child.attrib["RcjId"]].attrib["Rcjlb"], 
        kv[child.attrib["RcjId"]].attrib["Jgbz"], 
        child.attrib["Rcjhl"], child.attrib["Rcjhj"], kv[child.attrib["RcjId"]].attrib["Zgjbz"], 
             kv[child.attrib["RcjId"]].attrib["Zyclbz"], kv[child.attrib["RcjId"]].attrib["Zcbz"], kv[child.attrib["RcjId"]].attrib["Sbbz"]
        ])

    return result
def getDingercj_(root, bh, bt, qdbm, debm):
    if bt == 'Default':
        return getDingercj_default(root, bh, bt, qdbm, debm)
    result = [["ID", "人材机编码", "名称", "规格型号", "单位", "单价", "产地", 
    "供应厂商", "人材机类别", "甲供标志", "含量", "合价", "暂估价标志", "主要材料标志", "主材标志", "设备标志" ]]
    #result.append(["ming cheng", "jin e", "zan gu jia", "anquan wenming fei", "guifei"])
    item = None
    for child in root:
    
        if child.tag == "Dxgcxx":
            for child1 in child:
                Dwgcbh = child1.attrib["Dwgcbh"]
                if Dwgcbh == bh:
                    item = child1
                    break
            ##result.append([child.attrib["Dxgcmc"], child.attrib["Je"], child.attrib["Zgj"], child.attrib["Aqwmf"], child.attrib["Gf"]])
    Fywj = None
    for child in item:
        if child.tag == 'Qdxm':
            Fywj= child
            break
    Rcjhz = None
    for child in item:
        if child.tag == 'Rcjhz':
            Rcjhz = child
            break
    kv = {}
    for entry in Rcjhz:
        kv[entry.attrib["RcjId"]]=entry

    container = None
    for child in Fywj:
        ##child is mx
        if child.tag == "QdBt":
            if child.attrib["Mc"] == bt:
                count = 0
                for grandchild in child:
                    count = count + 1
                if count > 0:
                    container = child
                    break
    if not container:
        container = Fywj
    zimu = None
    for child in container:
        if child.attrib["Qdbm"] == qdbm:
            zimu = child
            break
    box = None
    if not zimu:
        return result
    for child in zimu:
        if child.tag == "Qdxdezj":
            box = child
            break
    hlmx_parent = None
    for child in box:
        if child.attrib["Debm"] == debm:
            for grandchild in child:
                if grandchild.tag == "Qdxdercjhl":
                    hlmx_parent = grandchild
    for child in hlmx_parent:
        result.append([child.attrib["RcjId"], 
        kv[child.attrib["RcjId"]].attrib["RcjBm"], 
        kv[child.attrib["RcjId"]].attrib["Mc"], 
        kv[child.attrib["RcjId"]].attrib["Ggxh"], 
        kv[child.attrib["RcjId"]].attrib["Dw"], 
        kv[child.attrib["RcjId"]].attrib["Dj"], 
        kv[child.attrib["RcjId"]].attrib["Cd"], 
        kv[child.attrib["RcjId"]].attrib["Gycs"], 
        kv[child.attrib["RcjId"]].attrib["Rcjlb"], 
        kv[child.attrib["RcjId"]].attrib["Jgbz"], 
        child.attrib["Rcjhl"], child.attrib["Rcjhj"], kv[child.attrib["RcjId"]].attrib["Zgjbz"], 
             kv[child.attrib["RcjId"]].attrib["Zyclbz"], kv[child.attrib["RcjId"]].attrib["Zcbz"], kv[child.attrib["RcjId"]].attrib["Sbbz"]
        ])

    return result


def getQingdanrcj_default(root, bh, bt, bm):
   
    result = [["ID", "人材机编码", "名称", "规格型号", "单位", "单价", "产地", 
    "供应厂商", "人材机类别", "甲供标志", "含量", "合价", "暂估价标志", "主要材料标志", "主材标志", "设备标志" ]]
    #result.append(["ming cheng", "jin e", "zan gu jia", "anquan wenming fei", "guifei"])
    item = None
    for child in root:
    
        if child.tag == "Dxgcxx":
            for child1 in child:
                Dwgcbh = child1.attrib["Dwgcbh"]
                if Dwgcbh == bh:
                    item = child1
                    break
            ##result.append([child.attrib["Dxgcmc"], child.attrib["Je"], child.attrib["Zgj"], child.attrib["Aqwmf"], child.attrib["Gf"]])
    Fywj = None
    for child in item:
        if child.tag == 'Qdxm':
            Fywj= child
            break
    Rcjhz = None
    for child in item:
        if child.tag == 'Rcjhz':
            Rcjhz = child
            break
    kv = {}
    for entry in Rcjhz:
        kv[entry.attrib["RcjId"]]=entry

    container = None
    for child in Fywj:
        ##child is mx
        if child.tag == "Qdmx" and child.attrib["Qdbm"] == bm:
            zimu = child
            break
    box = None
    if not zimu:
        return result
    for child in zimu:
        if child.tag == "Qdxrcjhl":
            box = child
            break
    for child in box:
        result.append([child.attrib["RcjId"], 
        kv[child.attrib["RcjId"]].attrib["RcjBm"], 
        kv[child.attrib["RcjId"]].attrib["Mc"], 
        kv[child.attrib["RcjId"]].attrib["Ggxh"], 
        kv[child.attrib["RcjId"]].attrib["Dw"], 
        kv[child.attrib["RcjId"]].attrib["Dj"], 
        kv[child.attrib["RcjId"]].attrib["Cd"], 
        kv[child.attrib["RcjId"]].attrib["Gycs"], 
        kv[child.attrib["RcjId"]].attrib["Rcjlb"], 
        kv[child.attrib["RcjId"]].attrib["Jgbz"], 
        child.attrib["Rcjhl"], child.attrib["Rcjhj"], kv[child.attrib["RcjId"]].attrib["Zgjbz"], 
        kv[child.attrib["RcjId"]].attrib["Zyclbz"], kv[child.attrib["RcjId"]].attrib["Zcbz"], kv[child.attrib["RcjId"]].attrib["Sbbz"]
        ])

    return result


def getQingdanrcj_(root, bh, bt, bm):
    if bt == 'Default':
        return getQingdanrcj_default(root, bh, bt, bm)
    
    result = [["ID", "人材机编码", "名称", "规格型号", "单位", "单价", "产地", 
    "供应厂商", "人材机类别", "甲供标志", "含量", "合价", "暂估价标志", "主要材料标志", "主材标志", "设备标志" ]]
    #result.append(["ming cheng", "jin e", "zan gu jia", "anquan wenming fei", "guifei"])
    item = None
    for child in root:
    
        if child.tag == "Dxgcxx":
            for child1 in child:
                Dwgcbh = child1.attrib["Dwgcbh"]
                if Dwgcbh == bh:
                    item = child1
                    break
            ##result.append([child.attrib["Dxgcmc"], child.attrib["Je"], child.attrib["Zgj"], child.attrib["Aqwmf"], child.attrib["Gf"]])
    Fywj = None
    for child in item:
        if child.tag == 'Qdxm':
            Fywj= child
            break
    Rcjhz = None
    for child in item:
        if child.tag == 'Rcjhz':
            Rcjhz = child
            break
    kv = {}
    for entry in Rcjhz:
        kv[entry.attrib["RcjId"]]=entry

    container = None
    for child in Fywj:
        ##child is mx
        if child.tag == "QdBt":
            if child.attrib["Mc"] == bt:
                count = 0
                for grandchild in child:
                    count = count +1
                if count > 0:
                    container = child
                    break
    if  container == None:
        container = Fywj
    zimu = None
    for child in container:
        if child.attrib["Qdbm"] == bm:
            zimu = child
            break
    box = None
    if not zimu:
        return result
    for child in zimu:
        if child.tag == "Qdxrcjhl":
            box = child
            break
    for child in box:
        result.append([child.attrib["RcjId"], 
        kv[child.attrib["RcjId"]].attrib["RcjBm"], 
        kv[child.attrib["RcjId"]].attrib["Mc"], 
        kv[child.attrib["RcjId"]].attrib["Ggxh"], 
        kv[child.attrib["RcjId"]].attrib["Dw"], 
        kv[child.attrib["RcjId"]].attrib["Dj"], 
        kv[child.attrib["RcjId"]].attrib["Cd"], 
        kv[child.attrib["RcjId"]].attrib["Gycs"], 
        kv[child.attrib["RcjId"]].attrib["Rcjlb"], 
        kv[child.attrib["RcjId"]].attrib["Jgbz"], 
        child.attrib["Rcjhl"], child.attrib["Rcjhj"], kv[child.attrib["RcjId"]].attrib["Zgjbz"], 
        kv[child.attrib["RcjId"]].attrib["Zyclbz"], kv[child.attrib["RcjId"]].attrib["Zcbz"], kv[child.attrib["RcjId"]].attrib["Sbbz"]
        ])

    return result


def getDjcsDingercj_(root, bh, bt, qdbm, debm):
    result = [["ID", "人材机编码", "名称", "规格型号", "单位", "单价", "产地", 
    "供应厂商", "人材机类别", "甲供标志", "含量", "合价", "暂估价标志", "主要材料标志", "主材标志", "设备标志" ]]
    #result.append(["ming cheng", "jin e", "zan gu jia", "anquan wenming fei", "guifei"])
    item = None
    for child in root:
    
        if child.tag == "Dxgcxx":
            for child1 in child:
                Dwgcbh = child1.attrib["Dwgcbh"]
                if Dwgcbh == bh:
                    item = child1
                    break
            ##result.append([child.attrib["Dxgcmc"], child.attrib["Je"], child.attrib["Zgj"], child.attrib["Aqwmf"], child.attrib["Gf"]])
    Fywj = None
    for child in item:
        if child.tag == 'Csxm':
            Fywj= child
            break
    Rcjhz = None
    for child in item:
        if child.tag == 'Rcjhz':
            Rcjhz = child
            break
    kv = {}
    for entry in Rcjhz:
        kv[entry.attrib["RcjId"]]=entry

    container = None
    for child in Fywj:
        if child.tag == "DjCs":
            container = child
            break
    zimu = None
    for child in container:
        if child.attrib["Bm"] == qdbm:
            zimu = child
            break
    box = None
    if not zimu:
        return result
    for child in zimu:
        if child.tag == "Csxdezj":
            box = child
            break
    hlmx_parent = None
    for child in box:
        if child.attrib["Debm"] == debm:
            for grandchild in child:
                if grandchild.tag == "Csxdercjhl":
                    hlmx_parent = grandchild
    for child in hlmx_parent:
        result.append([child.attrib["RcjId"], 
        kv[child.attrib["RcjId"]].attrib["RcjBm"], 
        kv[child.attrib["RcjId"]].attrib["Mc"], 
        kv[child.attrib["RcjId"]].attrib["Ggxh"], 
        kv[child.attrib["RcjId"]].attrib["Dw"], 
        kv[child.attrib["RcjId"]].attrib["Dj"], 
        kv[child.attrib["RcjId"]].attrib["Cd"], 
        kv[child.attrib["RcjId"]].attrib["Gycs"], 
        kv[child.attrib["RcjId"]].attrib["Rcjlb"], 
        kv[child.attrib["RcjId"]].attrib["Jgbz"], 
        child.attrib["Rcjhl"], child.attrib["Rcjhj"], kv[child.attrib["RcjId"]].attrib["Zgjbz"], 
             kv[child.attrib["RcjId"]].attrib["Zyclbz"], kv[child.attrib["RcjId"]].attrib["Zcbz"], 
             kv[child.attrib["RcjId"]].attrib["Sbbz"]
        ])

    return result
def getDjcsQingdanrcj_(root, bh, bt, bm):
    result = [["ID", "人材机编码", "名称", "规格型号", "单位", "单价", "产地", 
    "供应厂商", "人材机类别", "甲供标志", "含量", "合价", "暂估价标志", "主要材料标志", "主材标志", "设备标志" ]]
    #result.append(["ming cheng", "jin e", "zan gu jia", "anquan wenming fei", "guifei"])
    item = None
    for child in root:
    
        if child.tag == "Dxgcxx":
            for child1 in child:
                Dwgcbh = child1.attrib["Dwgcbh"]
                if Dwgcbh == bh:
                    item = child1
                    break
            ##result.append([child.attrib["Dxgcmc"], child.attrib["Je"], child.attrib["Zgj"], child.attrib["Aqwmf"], child.attrib["Gf"]])
    Fywj = None
    for child in item:
        if child.tag == 'Csxm':
            Fywj= child
            break
    hl_parent = None
    for child in Fywj:
        if child.tag == "DjCs":
            hl_parent = child
    Rcjhz = None
    for child in item:
        if child.tag == 'Rcjhz':
            Rcjhz = child
            break
    kv = {}
    for entry in Rcjhz:
        kv[entry.attrib["RcjId"]]=entry

    zimu = None
    for child in hl_parent:
        if child.attrib["Bm"] == bm:
            zimu = child
            break
    box = None
    if not zimu:
        return result
    for child in zimu:
        if child.tag == "Csxrcjhl":
            box = child
            break
    for child in box:
        result.append([child.attrib["RcjId"], 
        kv[child.attrib["RcjId"]].attrib["RcjBm"], 
        kv[child.attrib["RcjId"]].attrib["Mc"], 
        kv[child.attrib["RcjId"]].attrib["Ggxh"], 
        kv[child.attrib["RcjId"]].attrib["Dw"], 
        kv[child.attrib["RcjId"]].attrib["Dj"], 
        kv[child.attrib["RcjId"]].attrib["Cd"], 
        kv[child.attrib["RcjId"]].attrib["Gycs"], 
        kv[child.attrib["RcjId"]].attrib["Rcjlb"], 
        kv[child.attrib["RcjId"]].attrib["Jgbz"], 
        child.attrib["Rcjhl"], child.attrib["Rcjhj"], kv[child.attrib["RcjId"]].attrib["Zgjbz"], 
        kv[child.attrib["RcjId"]].attrib["Zyclbz"], kv[child.attrib["RcjId"]].attrib["Zcbz"], kv[child.attrib["RcjId"]].attrib["Sbbz"]
        ])

    return result

######################end of helper ########################
async def resolve(data, client):
    
    root = ET.fromstring(data)
    print(root)

    Dwgcbh = []
    jingjibiao = {}
    jingjibiao['visible'] = False
    jingjibiao['created'] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    jingjibiao["BiaoDuanNO"] = root.attrib["BiaoDuanNO"]
    jingjibiao["Jsfs"] = root.attrib["Jsfs"]
    jingjibiao["Version"] = root.attrib["Version"]
    jingjibiao["Xmmc"] = root.attrib["Xmmc"]
    jingjibiao["Dxgcxx"] = []
    for child in root:
        if child.tag == "ZhaoBiaoXx":
            jingjibiao["ZhaoBiaoXx"] = {}
            jingjibiao["ZhaoBiaoXx"]["BzTime"] = child.attrib["BzTime"]
            jingjibiao["ZhaoBiaoXx"]["Bzr"] = child.attrib["Bzr"]
            jingjibiao["ZhaoBiaoXx"]["FhTime"] = child.attrib["FhTime"]
            jingjibiao["ZhaoBiaoXx"]["Fhr"] = child.attrib["Fhr"]
            jingjibiao["ZhaoBiaoXx"]["Zbr"] = child.attrib["Zbr"]
            jingjibiao["ZhaoBiaoXx"]["ZbrDb"] = child.attrib["ZbrDb"]
            jingjibiao["ZhaoBiaoXx"]["Zxr"] = child.attrib["Zxr"]
            jingjibiao["ZhaoBiaoXx"]["ZxrDb"] = child.attrib["ZxrDb"]
        elif child.tag == "TouBiaoXx":
            jingjibiao["TouBiaoXx"] = {}
            jingjibiao["TouBiaoXx"]["Zbr"] = child.attrib["Zbr"]
            jingjibiao["TouBiaoXx"]["Tbr"] = child.attrib["Tbr"]
            jingjibiao["TouBiaoXx"]["TbrDb"] = child.attrib["TbrDb"]
            jingjibiao["TouBiaoXx"]["Bzr"] = child.attrib["Bzr"]
            jingjibiao["TouBiaoXx"]["BzTime"] = child.attrib["BzTime"]
            jingjibiao["TouBiaoXx"]["Tbzj"] = child.attrib["Tbzj"]
            jingjibiao["TouBiaoXx"]["Zgj"] = child.attrib["Zgj"]
            jingjibiao["TouBiaoXx"]["Aqwmf"] = child.attrib["Aqwmf"]
            jingjibiao["TouBiaoXx"]["Gf"] = child.attrib["Gf"]
        elif child.tag == "Dxgcxx":
            Dxgcxx = {}
            Dxgcxx["Aqwmf"] = child.attrib["Aqwmf"]
            Dxgcxx["Dxgcbh"] = child.attrib["Dxgcbh"]
            Dxgcxx["Dxgcmc"] = child.attrib["Dxgcmc"]
            Dxgcxx["Gf"] = child.attrib["Gf"]
            Dxgcxx["Je"] = child.attrib["Je"]
            Dxgcxx["Zgj"] = child.attrib["Zgj"]
            Dxgcxx["Dwgc"] = []

            for grandchild in child:
                if grandchild.tag == "Dwgcxx":
                    Dwgcxx = {}
                    Dwgcxx["DogNum"] = grandchild.attrib["DogNum"]
                    Dwgcxx["Dwgcbh"] = grandchild.attrib["Dwgcbh"]
                    Dwgcbh.append({"bh": grandchild.attrib["Dwgcbh"], "num":  grandchild.attrib["DogNum"]})
                    Dwgcxx["Dwgcmc"] = grandchild.attrib["Dwgcmc"]
                    Dwgcxx["MachineKey"] = grandchild.attrib["MachineKey"]
                    Dwgcxx["SoftName"] = grandchild.attrib["SoftName"]
                    Dwgcxx["SoftNum"] = grandchild.attrib["SoftNum"]
                    Dwgcxx["Zylb"] = grandchild.attrib["Zylb"]
                    Dxgcxx["Dwgc"].append(Dwgcxx)
            jingjibiao["Dxgcxx"].append(Dxgcxx)

    if not 'TouBiaoXx' in jingjibiao:
        jingjibiao['TouBiaoXx'] = {'Tbzj' : '', 'Zgj' : '', 'Aqwmf' : '', 'Gf' : '' } 
    db = client["baojia"]
    collection = db["jingjibiao"]
    biao_id = (await collection.insert_one(jingjibiao)).inserted_id
    biao_id = str(biao_id)

    collection = db["Dwgc"]
    for entry in Dwgcbh:
        bjhz = service.getBjhz(root, entry["bh"])###array which contains __children
        gfsj = service.getGfsj(root, entry["bh"])##array which contains __children
        qtxm = service.getQtxm(root, entry["bh"])##array which contains __children
        zlje = service.getZlje(root, entry["bh"])
        jrg = service.getJrg(root, entry["bh"])
        zcbfwf = service.getZcbfwf(root, entry["bh"])
        fbrgycl = service.getFbrgycl(root, entry["bh"])
        rcjhz = service.getRcjhz(root, entry["bh"])
        zjcs = service.getZjcs(root, entry["bh"])
        qdbt = service.getQdxm(root, entry["bh"])
        qdbt_addition = service.getQdxm_addition(root, entry["bh"])
        zygczgj = service.getZygczgj(root, entry["bh"])
        Dwgc = {}
        Dwgc["bjhz"] = bjhz
        Dwgc["gfsj"] = gfsj
        Dwgc["qtxm"] = qtxm
        Dwgc["zlje"] = zlje
        Dwgc["jrg"] = jrg
        Dwgc['zygczgj'] = zygczgj
        Dwgc["zcbfwf"] = zcbfwf
        Dwgc["fbrgycl"] = fbrgycl
        Dwgc["rcjhz"] = rcjhz
        Dwgc["zjcs"] = zjcs
        Dwgc["qdbt"] = qdbt
        Dwgc['qdbt_addition'] = qdbt_addition
        Dwgc["DogNum"] = entry["num"]
        Dwgc["Dwgcbh"] = entry["bh"]
        Dwgc["biao_id"] = biao_id
        await collection.insert_one(Dwgc)

    collection = db["Djcs"]
    for entry in Dwgcbh:
        
        djcs = service.getDjcs(root, entry["bh"])
        for cs in djcs:
            cs["DogNum"] = entry["num"]
            cs["Dwgcbh"] = entry["bh"]
            cs["biao_id"] = biao_id
            rcj = getDjcsQingdanrcj_(root, entry["bh"], "", cs['清单编码'])
            cs["rcj"] = rcj
            if "__children" in cs:
                children = cs["__children"]
                for child in children:
                    dercj = getDjcsDingercj_(root, entry["bh"], "", cs["清单编码"], child["清单编码"])
                    child["dercj"] = dercj
                    child['fuzhuEnable'] = False
                    child['yuban'] = []
            await collection.insert_one(cs)

    collection = db["qdxm"]
    for entry in Dwgcbh:
        
        bts = service.getQdxm(root, entry["bh"])
        for bt in bts:
            if bt == 'Default':
                qdmx = service.getQdmx_default(root, entry["bh"], bt)
            else:
                qdmx = service.getQdmx(root, entry["bh"], bt)
            for qd in qdmx:
                qd["DogNum"] = entry["num"]
                qd["Dwgcbh"] = entry["bh"]
                qd["biao_id"] = biao_id
                qd["bt"] = bt
                rcj = getQingdanrcj_(root, entry["bh"], bt, qd["清单编码"])
                qd["rcj"] = rcj
                if "__children" in qd:
                    children = qd["__children"]
                    for child in children:
                        dercj = getDingercj_(root, entry["bh"], bt, qd["清单编码"], child["清单编码"])
                        child["dercj"] = dercj
                        child['fuzhuEnable'] = False
                        child['yuban'] = []
                        child['rcjbc'] = []
                        if '-F' in child['清单编码']:
                            #######TODO########
                            child['azfytag'] = ['人工费', 10, 100, 0, 0]
                            if '11-F2' in child['清单编码'] or '1-F2' in child['清单编码']:
                                child['azfytag'] = ['人工费+机械费', 10, 100, 0, 0]
                await collection.insert_one(qd)
            

    collection = db["qufei"]
    document = jingjibiao
    dxgc = document['Dxgcxx']
    result = []
    for entry in dxgc:
        newone = {"名称" : entry['Dxgcmc'],  "工程类型":"", "工程类别": "", "管理费（%）": "", "利润（%）": "","备注":"", "key" : str(uuid.uuid4()) }
        children = []
        for dwgc in entry['Dwgc']:
            children.append({"名称" : dwgc['Dwgcmc'], "工程类型":"",  "工程类别": "", "管理费（%）": "", "利润（%）": "","备注":"", "key" : dwgc['Dwgcbh']})
        newone["children"] = children
        result.append(newone)
    await collection.insert_one({"biao_id": biao_id, "qufei": [{
        "名称" : document['Xmmc'], "工程类型":"", "工程类别": "", "管理费（%）": "", "利润（%）": "","备注":"", "key" : str(uuid.uuid4()), "children" : result
    }]})

    collection = db["jingjibiao"]

    await collection.update_one({'_id': ObjectId(biao_id)}, {'$set': {'visible': True}})






def dfs(items):
    result = []
    for entry in items:
        result.append([entry['序号'], entry['名称'], entry['金额'], entry['暂估价'], entry['类别']])
        if '__children' in entry:
            result_ = dfs(entry['__children'])
            for r in result_:
                result.append(r)
    return result

def dfs2(items):
    result = []
    for entry in items:
        result.append([entry['序号'], entry['名称'], entry['取费基数'], entry['计算基础'], entry['费率'], entry['金额'], entry['类别']])
        if '__children' in entry:
            result_ = dfs2(entry['__children'])
            for r in result_:
                result.append(r)
    return result

def dfs3(items):
    result = []
    for entry in items:
        result.append([entry['序号'], entry['名称'], entry['金额'], entry['项目类别'], entry['备注']])
        if '__children' in entry:
            result_ = dfs3(entry['__children'])
            for r in result_:
                result.append(r)
    return result

def roundstr(input):
    a = float(input)
    b = round(a, 2)
    return str(b)


def roundstr4(input):
    a = float(input)
    b = round(a, 4)
    return str(b)

async def build(client, root, id):
    db = client["baojia"]
    collection = db["jingjibiao"]
    document = await collection.find_one({'_id': ObjectId(id)})

    root.set('BiaoDuanNO', document['BiaoDuanNO'])
    root.set('Jsfs', document['Jsfs'])
    root.set('Version', document['Version'])
    root.set('Xmmc', document['Xmmc'])

    TouBiaoXx = ET.SubElement(root, 'TouBiaoXx')
    ##{'Tbzj' : '', 'Zgj' : '', 'Aqwmf' : '', 'Gf' : '' } 
    TouBiaoXx.set('Tbzj', roundstr(document['TouBiaoXx']['Tbzj']))
    TouBiaoXx.set('Zgj', roundstr(document['TouBiaoXx']['Zgj']))
    TouBiaoXx.set('Aqwmf', roundstr(document['TouBiaoXx']['Aqwmf']))
    TouBiaoXx.set('Gf', roundstr(document['TouBiaoXx']['Gf']))
    if 'Zbr' in document['TouBiaoXx']:
        TouBiaoXx.set('Zbr', str(document['TouBiaoXx']['Zbr']))
    if 'Tbr' in document['TouBiaoXx']:
        TouBiaoXx.set('Tbr', str(document['TouBiaoXx']['Tbr']))
    if 'TbrDb' in document['TouBiaoXx']:
        TouBiaoXx.set('TbrDb', str(document['TouBiaoXx']['TbrDb']))
    if 'Bzr' in document['TouBiaoXx']:
        TouBiaoXx.set('Bzr', str(document['TouBiaoXx']['Bzr']))
    if 'BzTime' in document['TouBiaoXx']:
        TouBiaoXx.set('BzTime', str(document['TouBiaoXx']['BzTime']))
    for item in document['Dxgcxx']:
        Dxgcxx = ET.SubElement(root, 'Dxgcxx')
        Dxgcxx.set('Dxgcbh', str(item['Dxgcbh']))
        Dxgcxx.set('Dxgcmc', str(item['Dxgcmc']))
        Dxgcxx.set('Je', roundstr(item['Je']))
        Dxgcxx.set('Zgj', roundstr(item['Zgj']))
        Dxgcxx.set('Aqwmf', roundstr(item['Aqwmf']))
        Dxgcxx.set('Gf', roundstr(item['Gf']))
        for entry in item['Dwgc']:
            Dwgcxx = ET.SubElement(Dxgcxx, 'Dwgcxx')
            Dwgcxx.set('Dwgcbh', str(entry['Dwgcbh']))
            Dwgcxx.set('Dwgcmc', str(entry['Dwgcmc']))
            Dwgcxx.set('Zylb', str(entry['Zylb']))
            Dwgcxx.set('SoftName', str(entry['SoftName']))
            Dwgcxx.set('SoftNum', str(entry['SoftNum']))
            Dwgcxx.set('DogNum', str(entry['DogNum']))
            Dwgcxx.set('MachineKey', str(entry['MachineKey']))
            collection = db["Dwgc"]
            Dwgc = await collection.find_one({'biao_id': id, "Dwgcbh": entry['Dwgcbh']})
            bjhz = dfs(Dwgc['bjhz'])
            gfsj = dfs2(Dwgc['gfsj'])
            qtxm = dfs3(Dwgc['qtxm'])
            zlje = Dwgc['zlje']
            zygczgj = Dwgc['zygczgj']
            jrg = Dwgc['jrg']
            zcbfwf = Dwgc['zcbfwf']
            fbrgycl = Dwgc['fbrgycl']
            rcjhz = Dwgc['rcjhz']
            zjcs = Dwgc['zjcs']
            qdbt = Dwgc['qdbt']
            ########################################Fywj##########################
            Fywj = ET.SubElement(Dwgcxx, 'Fywj')
            for bjhz_ in bjhz:
                FywjMx = ET.SubElement(Fywj, 'FywjMx')
                FywjMx.set('Xh', str(bjhz_[0]))
                FywjMx.set('Mc', str(bjhz_[1]))
                FywjMx.set('Je', roundstr(bjhz_[2]))
                FywjMx.set('Zgj', roundstr(bjhz_[3]))
                FywjMx.set('Fyxlb', str(bjhz_[4]))
            ########################################Gfsj##########################
            Gfsj = ET.SubElement(Dwgcxx, 'Gfsj')
            for gfsj_ in gfsj:
                GfsjMx = ET.SubElement(Gfsj, 'GfsjMx')
                GfsjMx.set('Xh', str(gfsj_[0]))
                GfsjMx.set('Mc', str(gfsj_[1]))
                GfsjMx.set('Qfjs', roundstr(gfsj_[2]))
                GfsjMx.set('Jsjc', str(gfsj_[3]))
                GfsjMx.set('Fl', str(gfsj_[4]))
                GfsjMx.set('Je', roundstr(gfsj_[5]))
                GfsjMx.set('Fyxlb', str(gfsj_[6]))
            ########################################Qdxm##########################
            Qdxm = ET.SubElement(Dwgcxx, 'Qdxm')
            if 'Default' in qdbt:
                collection = db["qdxm"]
                before_sort = []
                async for post in collection.find({"biao_id": id, "Dwgcbh": entry['Dwgcbh'], 'bt': 'Default'}):
                    before_sort.append(post)
                after_sort = sorted(before_sort, key=lambda x: int(x['序号']))
                for qdmx in after_sort:
                    Qdmx = ET.SubElement(Qdxm, 'Qdmx')
                    Qdmx.set('Xh', str(qdmx['序号']))
                    Qdmx.set('Qdbm', str(qdmx['清单编码']))
                    Qdmx.set('Mc', str(qdmx['名称']))
                    Qdmx.set('Xmtz', str(qdmx['项目特征']))
                    Qdmx.set('Jsgz', str(qdmx['计算规则']))
                    Qdmx.set('Dw', str(qdmx['单位']))
                    Qdmx.set('Sl', roundstr4(qdmx['数量']))
                    Qdmx.set('Zhdj', roundstr4(qdmx['综合单价']))
                    Qdmx.set('Zhhj', roundstr4(qdmx['合价']))
                    Qdmx.set('Rgf', roundstr4(qdmx['人工费']))
                    Qdmx.set('Zcf', roundstr4(qdmx['主材费']))
                    Qdmx.set('Sbf', roundstr4(qdmx['设备费']))
                    Qdmx.set('Fcf', roundstr4(qdmx['辅材费']))
                    Qdmx.set('Clf', roundstr4(qdmx['材料费']))
                    Qdmx.set('Jxf', roundstr4(qdmx['机械费']))
                    Qdmx.set('Glf', roundstr4(qdmx['管理费']))
                    Qdmx.set('Lr', roundstr4(qdmx['利润']))
                    Qdmx.set('Zgj', roundstr4(qdmx['暂估价']))
                    Qdmx.set('Zgr', roundstr4(qdmx['综合人工工日']))
                    Qdmx.set('Bz', str(qdmx['备注']))
                    Qdxdezj = ET.SubElement(Qdmx, 'Qdxdezj')
                    if '__children' in qdmx:
                        for child in qdmx['__children']:
                            QdxdezjMx = ET.SubElement(Qdxdezj, 'QdxdezjMx')
                            QdxdezjMx.set('Debm', str(child['清单编码']))
                            QdxdezjMx.set('Mc', str(child['名称']))
                            QdxdezjMx.set('Dw', str(child['单位']))
                            QdxdezjMx.set('DwQdSl', roundstr4(child['数量']))
                            QdxdezjMx.set('Dj', roundstr4(child['综合单价']))
                            QdxdezjMx.set('Hj', roundstr4(child['合价']))
                            QdxdezjMx.set('Rgf', roundstr4(child['人工费']))
                            QdxdezjMx.set('Zcf', roundstr4(child['主材费']))
                            QdxdezjMx.set('Sbf', roundstr4(child['设备费']))
                            QdxdezjMx.set('Fcf', roundstr4(child['辅材费']))
                            QdxdezjMx.set('Clf', roundstr4(child['材料费']))
                            QdxdezjMx.set('Jxf', roundstr4(child['机械费']))
                            QdxdezjMx.set('Glf', roundstr4(child['管理费']))
                            QdxdezjMx.set('Lr', roundstr4(child['利润']))
                            Qdxdercjhl = ET.SubElement(QdxdezjMx, 'Qdxdercjhl')
                            for i in range(len(child['dercj'])):
                                if i == 0:
                                    pass
                                else:
                                    QdxdercjhlMx = ET.SubElement(Qdxdercjhl, 'QdxdercjhlMx')
                                    QdxdercjhlMx.set('RcjId', util.indexrcj(rcjhz, child['dercj'][i]))
                                    QdxdercjhlMx.set('Rcjhl', roundstr4(child['dercj'][i][10]))
                                    QdxdercjhlMx.set('Rcjhj', roundstr4(child['dercj'][i][11]))
                    Qdxrcjhl = ET.SubElement(Qdmx, 'Qdxrcjhl')
                    for i in range(len(qdmx['rcj'])):
                        if i == 0:
                            pass
                        else:
                            QdxrcjhlMx = ET.SubElement(Qdxrcjhl, 'QdxrcjhlMx')
                            QdxrcjhlMx.set('RcjId', util.indexrcj(rcjhz, qdmx['rcj'][i]))
                                           ##str(djcs['rcj'][i][0]))
                            QdxrcjhlMx.set('Rcjhl', roundstr4(qdmx['rcj'][i][10]))
                            QdxrcjhlMx.set('Rcjhj', roundstr4(qdmx['rcj'][i][11]))
                            QdxrcjhlMx.set('Zgjbz', str(qdmx['rcj'][i][12]))
                            QdxrcjhlMx.set('Zyclbz', str(qdmx['rcj'][i][13]))
                            QdxrcjhlMx.set('Zcbz', str(qdmx['rcj'][i][14]))
                            QdxrcjhlMx.set('Sbbz', str(qdmx['rcj'][i][15]))
            
            qdbt_addition = Dwgc['qdbt_addition']
            for bt in qdbt_addition:
                QdBt = ET.SubElement(Qdxm, 'QdBt')
                QdBt.set('Xh', bt['Xh'])
                QdBt.set('Mc', bt['Mc'])
                QdBt.set('Je', roundstr(bt['Je']))
                QdBt.set('Zgj', roundstr(bt['Zgj']))
                QdBt.set('Bz', bt['Bz'])
                collection = db["qdxm"]
                before_sort = []
                async for post in collection.find({"biao_id": id, "Dwgcbh": entry['Dwgcbh'], 'bt': bt['Mc']}):
                    before_sort.append(post)
                after_sort = sorted(before_sort, key=lambda x: int(x['序号']))
                for qdmx in after_sort:
                    Qdmx = ET.SubElement(QdBt, 'Qdmx')
                    Qdmx.set('Xh', str(qdmx['序号']))
                    Qdmx.set('Qdbm', str(qdmx['清单编码']))
                    Qdmx.set('Mc', str(qdmx['名称']))
                    Qdmx.set('Xmtz', str(qdmx['项目特征']))
                    Qdmx.set('Jsgz', str(qdmx['计算规则']))
                    Qdmx.set('Dw', str(qdmx['单位']))
                    Qdmx.set('Sl', roundstr4(qdmx['数量']))
                    Qdmx.set('Zhdj', roundstr4(qdmx['综合单价']))
                    Qdmx.set('Zhhj', roundstr4(qdmx['合价']))
                    Qdmx.set('Rgf', roundstr4(qdmx['人工费']))
                    Qdmx.set('Zcf', roundstr4(qdmx['主材费']))
                    Qdmx.set('Sbf', roundstr4(qdmx['设备费']))
                    Qdmx.set('Fcf', roundstr4(qdmx['辅材费']))
                    Qdmx.set('Clf', roundstr4(qdmx['材料费']))
                    Qdmx.set('Jxf', roundstr4(qdmx['机械费']))
                    Qdmx.set('Glf', roundstr4(qdmx['管理费']))
                    Qdmx.set('Lr', roundstr4(qdmx['利润']))
                    Qdmx.set('Zgj', roundstr4(qdmx['暂估价']))
                    Qdmx.set('Zgr', roundstr4(qdmx['综合人工工日']))
                    Qdmx.set('Bz', str(qdmx['备注']))
                    Qdxdezj = ET.SubElement(Qdmx, 'Qdxdezj')
                    if '__children' in qdmx:
                        for child in qdmx['__children']:
                            QdxdezjMx = ET.SubElement(Qdxdezj, 'QdxdezjMx')
                            QdxdezjMx.set('Debm', str(child['清单编码']))
                            QdxdezjMx.set('Mc', str(child['名称']))
                            QdxdezjMx.set('Dw', str(child['单位']))
                            QdxdezjMx.set('DwQdSl', roundstr4(child['数量']))
                            QdxdezjMx.set('Dj', roundstr4(child['综合单价']))
                            QdxdezjMx.set('Hj', roundstr4(child['合价']))
                            QdxdezjMx.set('Rgf', roundstr4(child['人工费']))
                            QdxdezjMx.set('Zcf', roundstr4(child['主材费']))
                            QdxdezjMx.set('Sbf', roundstr4(child['设备费']))
                            QdxdezjMx.set('Fcf', roundstr4(child['辅材费']))
                            QdxdezjMx.set('Clf', roundstr4(child['材料费']))
                            QdxdezjMx.set('Jxf', roundstr4(child['机械费']))
                            QdxdezjMx.set('Glf', roundstr4(child['管理费']))
                            QdxdezjMx.set('Lr', roundstr4(child['利润']))
                            Qdxdercjhl = ET.SubElement(QdxdezjMx, 'Qdxdercjhl')
                            for i in range(len(child['dercj'])):
                                if i == 0:
                                    pass
                                else:
                                    QdxdercjhlMx = ET.SubElement(Qdxdercjhl, 'QdxdercjhlMx')
                                    QdxdercjhlMx.set('RcjId', util.indexrcj(rcjhz, child['dercj'][i]))
                                    QdxdercjhlMx.set('Rcjhl', roundstr4(child['dercj'][i][10]))
                                    QdxdercjhlMx.set('Rcjhj', roundstr4(child['dercj'][i][11]))
                    Qdxrcjhl = ET.SubElement(Qdmx, 'Qdxrcjhl')
                    for i in range(len(qdmx['rcj'])):
                        if i == 0:
                            pass
                        else:
                            QdxrcjhlMx = ET.SubElement(Qdxrcjhl, 'QdxrcjhlMx')
                            QdxrcjhlMx.set('RcjId', util.indexrcj(rcjhz, qdmx['rcj'][i]))
                                       ##str(djcs['rcj'][i][0]))
                            QdxrcjhlMx.set('Rcjhl', roundstr4(qdmx['rcj'][i][10]))
                            QdxrcjhlMx.set('Rcjhj', roundstr4(qdmx['rcj'][i][11]))
                            QdxrcjhlMx.set('Zgjbz', str(qdmx['rcj'][i][12]))
                            QdxrcjhlMx.set('Zyclbz', str(qdmx['rcj'][i][13]))
                            QdxrcjhlMx.set('Zcbz', str(qdmx['rcj'][i][14]))
                            QdxrcjhlMx.set('Sbbz', str(qdmx['rcj'][i][15]))







            ########################################Csxm##########################
            Csxm = ET.SubElement(Dwgcxx, 'Csxm')
            ZjCs = ET.SubElement(Csxm, 'ZjCs')
            for zjcs_ in zjcs:
                ZjCsMx = ET.SubElement(ZjCs, 'ZjCsMx')
                ZjCsMx.set('Xh', str(zjcs_['序号']))
                ZjCsMx.set('Bm', str(zjcs_['清单编码']))
                ZjCsMx.set('Mc', str(zjcs_['名称']))
                ZjCsMx.set('Js', roundstr(zjcs_['计算基数']))
                ZjCsMx.set('Jsjc', str(zjcs_['计算基础']))
                ZjCsMx.set('Fl', str(zjcs_['费率']))
                ZjCsMx.set('Je', roundstr(zjcs_['金额']))
                ZjCsMx.set('Xmlb', str(zjcs_['项目类别']))
                if '__children' in zjcs_:
                    AqwmfMx = ET.SubElement(ZjCsMx, 'AqwmfMx')
                    AqwmfMx.set('Mc', str(zjcs_['__children'][0]['名称']))
                    AqwmfMx.set('Js', roundstr(zjcs_['__children'][0]['计算基数']))
                    AqwmfMx.set('Jsjc', str(zjcs_['__children'][0]['计算基础']))
                    AqwmfMx.set('Fl', str(zjcs_['__children'][0]['费率']))
                    AqwmfMx.set('Je', roundstr(zjcs_['__children'][0]['金额']))
                    AqwmfMx.set('Xmlb', str(zjcs_['__children'][0]['项目类别']))
                    AqwmfMx = ET.SubElement(ZjCsMx, 'AqwmfMx')
                    AqwmfMx.set('Mc', str(zjcs_['__children'][1]['名称']))
                    AqwmfMx.set('Js', roundstr(zjcs_['__children'][1]['计算基数']))
                    AqwmfMx.set('Jsjc', str(zjcs_['__children'][1]['计算基础']))
                    AqwmfMx.set('Fl', str(zjcs_['__children'][1]['费率']))
                    AqwmfMx.set('Je', roundstr(zjcs_['__children'][1]['金额']))
                    AqwmfMx.set('Xmlb', str(zjcs_['__children'][1]['项目类别']))
                    AqwmfMx = ET.SubElement(ZjCsMx, 'AqwmfMx')
                    AqwmfMx.set('Mc', str(zjcs_['__children'][2]['名称']))
                    AqwmfMx.set('Js', roundstr(zjcs_['__children'][2]['计算基数']))
                    AqwmfMx.set('Jsjc', str(zjcs_['__children'][2]['计算基础']))
                    AqwmfMx.set('Fl', str(zjcs_['__children'][2]['费率']))
                    AqwmfMx.set('Je', roundstr(zjcs_['__children'][2]['金额']))
                    AqwmfMx.set('Xmlb', str(zjcs_['__children'][2]['项目类别']))
            DjCs = ET.SubElement(Csxm, 'DjCs')
            collection = db["Djcs"]
            before_sort = []
            async for post in collection.find({"biao_id": id, "Dwgcbh": entry['Dwgcbh']}):
                before_sort.append(post)
            after_sort = sorted(before_sort, key=lambda x: int(x['序号']))
            for djcs in after_sort:
                DjCsMx = ET.SubElement(DjCs, 'DjCsMx')
                DjCsMx.set('Xh', str(djcs['序号']))
                DjCsMx.set('Bm', str(djcs['清单编码']))
                DjCsMx.set('Mc', str(djcs['名称']))
                DjCsMx.set('Xmtz', str(djcs['项目特征']))
                DjCsMx.set('Jsgz', str(djcs['计算规则']))
                DjCsMx.set('Dw', str(djcs['单位']))
                DjCsMx.set('Sl', roundstr4(djcs['数量']))
                DjCsMx.set('Zhdj', roundstr4(djcs['综合单价']))
                DjCsMx.set('Zhhj', roundstr4(djcs['合价']))
                DjCsMx.set('Rgf', roundstr4(djcs['人工费']))
                DjCsMx.set('Zcf', roundstr4(djcs['主材费']))
                DjCsMx.set('Sbf', roundstr4(djcs['设备费']))
                DjCsMx.set('Fcf', roundstr4(djcs['辅材费']))
                DjCsMx.set('Clf', roundstr4(djcs['材料费']))
                DjCsMx.set('Jxf', roundstr4(djcs['机械费']))
                DjCsMx.set('Glf', roundstr4(djcs['管理费']))
                DjCsMx.set('Lr', roundstr4(djcs['利润']))
                DjCsMx.set('Zgj', roundstr4(djcs['暂估价']))
                DjCsMx.set('Zgr', roundstr4(djcs['综合人工工日']))
                Csxdezj = ET.SubElement(DjCsMx, 'Csxdezj')
                if '__children' in djcs:
                    for child in djcs['__children']:
                        CsxdezjMx = ET.SubElement(Csxdezj, 'CsxdezjMx')
                        CsxdezjMx.set('Debm', str(child['清单编码']))
                        CsxdezjMx.set('Mc', str(child['名称']))
                        CsxdezjMx.set('Dw', str(child['单位']))
                        CsxdezjMx.set('DwQdSl', roundstr4(child['数量']))
                        CsxdezjMx.set('Dj', roundstr4(child['综合单价']))
                        CsxdezjMx.set('Hj', roundstr4(child['合价']))
                        CsxdezjMx.set('Rgf', roundstr4(child['人工费']))
                        CsxdezjMx.set('Zcf', roundstr4(child['主材费']))
                        CsxdezjMx.set('Sbf', roundstr4(child['设备费']))
                        CsxdezjMx.set('Fcf', roundstr4(child['辅材费']))
                        CsxdezjMx.set('Clf', roundstr4(child['材料费']))
                        CsxdezjMx.set('Jxf', roundstr4(child['机械费']))
                        CsxdezjMx.set('Glf', roundstr4(child['管理费']))
                        CsxdezjMx.set('Lr', roundstr4(child['利润']))
                        Csxdercjhl = ET.SubElement(CsxdezjMx, 'Csxdercjhl')
                        for i in range(len(child['dercj'])):
                            if i == 0:
                                pass
                            else:
                                CsxdercjhlMx = ET.SubElement(Csxdercjhl, 'CsxdercjhlMx')
                                CsxdercjhlMx.set('RcjId', util.indexrcj(rcjhz, child['dercj'][i]))
                                CsxdercjhlMx.set('Rcjhl', roundstr4(child['dercj'][i][10]))
                                CsxdercjhlMx.set('Rcjhj', roundstr4(child['dercj'][i][11]))
                    Csxrcjhl = ET.SubElement(DjCsMx, 'Csxrcjhl')
                    for i in range(len(djcs['rcj'])):
                        if i == 0:
                            pass
                        else:
                            CsxrcjhlMx = ET.SubElement(Csxrcjhl, 'CsxrcjhlMx')
                            CsxrcjhlMx.set('RcjId', util.indexrcj(rcjhz, djcs['rcj'][i]))
                                           ##str(djcs['rcj'][i][0]))
                            CsxrcjhlMx.set('Rcjhl', roundstr4(djcs['rcj'][i][10]))
                            CsxrcjhlMx.set('Rcjhj', roundstr4(djcs['rcj'][i][11]))
                            CsxrcjhlMx.set('Zgjbz', str(djcs['rcj'][i][12]))
                            CsxrcjhlMx.set('Zyclbz', str(djcs['rcj'][i][13]))
                            CsxrcjhlMx.set('Zcbz', str(djcs['rcj'][i][14]))
                            CsxrcjhlMx.set('Sbbz', str(djcs['rcj'][i][15]))


                                





                        






















            ########################################Qtxm##########################
            Qtxm = ET.SubElement(Dwgcxx, 'Qtxm')
            for qtxm_ in qtxm:
                QtxmMx = ET.SubElement(Qtxm, 'QtxmMx')
                QtxmMx.set('Xh', str(qtxm_[0]))
                QtxmMx.set('Mc', str(qtxm_[1]))
                QtxmMx.set('Je', roundstr(qtxm_[2]))
                QtxmMx.set('Xmlb', str(qtxm_[3]))
                QtxmMx.set('Bz', str(qtxm_[4]))
            Zlje = ET.SubElement(Dwgcxx, 'Zlje')
            for i in range(len(zlje)):
                ZljeMx = ET.SubElement(Zlje, 'ZljeMx')
                ZljeMx.set('Xh', str(zlje[i]['序号']))
                ZljeMx.set('Mc', str(zlje[i]['名称']))
                ZljeMx.set('Dw', str(zlje[i]['单位']))
                ZljeMx.set('Zdje', roundstr(zlje[i]['暂定金额']))
                ZljeMx.set('Bz', str(zlje[i]['备注']))
            Clzg = ET.SubElement(Dwgcxx, 'Clzg')
            Zygczg = ET.SubElement(Dwgcxx, 'Zygczg')
            for zygczgj_ in zygczgj:
                ZygczgMx = ET.SubElement(Zygczg, 'ZygczgMx')
                ZygczgMx.set('Xh', str(zygczgj_['序号']))
                ZygczgMx.set('Mc', str(zygczgj_['名称']))
                ZygczgMx.set('Gcnr', str(zygczgj_['工程内容']))
                ZygczgMx.set('Je', roundstr(zygczgj_['金额']))
                ZygczgMx.set('Bz', str(zygczgj_['备注']))
            Jrg = ET.SubElement(Dwgcxx, 'Jrg')
            for jrg_ in jrg:
                JrgBt = ET.SubElement(Jrg, 'JrgBt')
                JrgBt.set('Xh', str(jrg_['序号']))
                JrgBt.set('Mc', str(jrg_['名称']))
                JrgBt.set('Je', roundstr(jrg_['金额']))
                JrgBt.set('Lb', str(jrg_['类别']))
            Zcbfwf = ET.SubElement(Dwgcxx, 'Zcbfwf')
            for zcbfwf_ in zcbfwf:
                ZcbfwfMx = ET.SubElement(Zcbfwf, 'ZcbfwfMx')
                ZcbfwfMx.set('Xh', str(zcbfwf_['序号']))
                ZcbfwfMx.set('Mc', str(zcbfwf_['名称']))
                ZcbfwfMx.set('Xmjz', roundstr(zcbfwf_['项目价值']))
                ZcbfwfMx.set('Fwnr', str(zcbfwf_['服务内容']))
                ZcbfwfMx.set('Jsjc', str(zcbfwf_['计算基础']))
                ZcbfwfMx.set('Fl', str(zcbfwf_['费率']))
                ZcbfwfMx.set('Je', roundstr(zcbfwf_['金额']))
            Zjxmjdkzffj = ET.SubElement(Dwgcxx, 'Zjxmjdkzffj')
            Fbrgycl = ET.SubElement(Dwgcxx, 'Fbrgycl')
            for fbrgycl_ in fbrgycl:
                FbrgyclMx = ET.SubElement(Fbrgycl, 'FbrgyclMx')
                FbrgyclMx.set('Xh', str(fbrgycl_['序号']))
                FbrgyclMx.set('RcjId', util.indexrcj(rcjhz, [fbrgycl_['序号'], fbrgycl_['材料编号'], fbrgycl_['名称'], fbrgycl_['规格型号'], fbrgycl_['单位']]))
                FbrgyclMx.set('Clbh', str(fbrgycl_['材料编号']))
                FbrgyclMx.set('Mc', str(fbrgycl_['名称']))
                FbrgyclMx.set('Ggxh', str(fbrgycl_['规格型号']))
                FbrgyclMx.set('Dw', str(fbrgycl_['单位']))
                FbrgyclMx.set('Sl', roundstr4(fbrgycl_['数量']))
                FbrgyclMx.set('Dj', roundstr4(fbrgycl_['单价']))
                FbrgyclMx.set('Hj', roundstr4(fbrgycl_['合价']))
                FbrgyclMx.set('Jhfs', str(fbrgycl_['交货方式']))
                FbrgyclMx.set('Sddd', str(fbrgycl_['送达地点']))
                FbrgyclMx.set('Bz', str(fbrgycl_['备注']))
            Cbrgycl = ET.SubElement(Dwgcxx, 'Cbrgycl')
            Rcjhz = ET.SubElement(Dwgcxx, 'Rcjhz')
            for i in range(len(rcjhz)):
                if i == 0:
                    pass 
                else:
                    RcjhzMx = ET.SubElement(Rcjhz, 'RcjhzMx')
                    RcjhzMx.set('RcjId', str(i))
                    RcjhzMx.set('RcjBm', str(rcjhz[i][1]))
                    RcjhzMx.set('Mc', str(rcjhz[i][2]))
                    RcjhzMx.set('Ggxh', str(rcjhz[i][3]))
                    RcjhzMx.set('Dw', str(rcjhz[i][4]))
                    RcjhzMx.set('Sl', roundstr4(rcjhz[i][5]))
                    RcjhzMx.set('Dj', roundstr4(rcjhz[i][6]))
                    RcjhzMx.set('Hj', roundstr4(rcjhz[i][7]))
                    RcjhzMx.set('Cd', str(rcjhz[i][8]))
                    RcjhzMx.set('Gycs', str(rcjhz[i][9]))
                    RcjhzMx.set('Rcjlb', str(rcjhz[i][10]))
                    RcjhzMx.set('Zyclbz', str(rcjhz[i][11]))
                    RcjhzMx.set('Zcbz', str(rcjhz[i][12]))
                    RcjhzMx.set('Sbbz', str(rcjhz[i][13]))
                    RcjhzMx.set('Jgbz', str(rcjhz[i][14]))
                    RcjhzMx.set('Zgjbz', str(rcjhz[i][15]))

















async def delete_files(client, id):
    db = client["baojia"]
    collection = db["jingjibiao"]
    result = []
    await collection.update_one({'_id': ObjectId(id)}, {'$set': {'visible': False}})
    return result



async def list_files(client):
    db = client["baojia"]
    collection = db["jingjibiao"]
    result = []
    async for post in collection.find({"visible": True}):
        result.append([str(post['_id']), post["Xmmc"], post['created'] if 'created' in post else ""])
    return result

def getDwgc(id, Zylb):
    result = []
    #result.append(["ming cheng", "jin e", "zan gu jia", "anquan wenming fei", "guifei"])
    
    
            ##result.append([child.attrib["Dxgcmc"], child.attrib["Je"], child.attrib["Zgj"], child.attrib["Aqwmf"], child.attrib["Gf"]])
    id = id + "Zylb" + Zylb
    
    
    result.append({"id": id + "bao jia hui zong", "label": "报价汇总表"})
    
    result.append({"id": id + "gui fei shui jin", "label": "规费税金"})
    
    result.append({"id": id + "qing dan xiang mu", "label": "清单项目"})
    
    result.append({"id": id + "cuo shi xiang mu", "label": "措施项目"})
    
    result.append({"id": id +"qi ta xiang mu", "label": "其他项目"})
    
    result.append({"id": id +"zan lie jin e", "label": "暂列金额"})
    
    result.append({"id": id +"cai liao zan gu jia", "label": "材料暂估价"})
    
    result.append({"id": id + "zhuan ye gong cheng zan gu jia", "label": "专业工程暂估价"})
    
    result.append({"id": id + "ji ri gong", "label": "计日工"})
    
    result.append({"id": id + "zong cheng bao fu wu fei", "label": "总承包服务费"})
    
    result.append({"id": id + "zong jia xiang mu jin du kuan zhi fu fen jie", "label": "总价项目进度款支付分解"})
    
    result.append({"id": id + "fa bao ren gong ying cai liao", "label": "发包人供应材料"})
    
    result.append({"id": id + "cheng bao ren gong ying cai liao", "label": "承包人供应材料"})
    
    result.append({"id": id + "ren cai ji hui zong", "label": "人材机汇总"})
    
    return result


async def getOutline(client, id):


    db = client["baojia"]
    collection = db["jingjibiao"]
    document = await collection.find_one({'_id': ObjectId(id)})
    result = []
    if 'TouBiaoXx' in document:
        result.append({"id" : "TouBiaoXx", "label" : "投标信息" })
    if 'Dxgcxx' in document:
        Dxgcxx = document["Dxgcxx"]
        for dxgc in Dxgcxx:
            result2 = []
            Dwgc = dxgc["Dwgc"]
            for grandchild in Dwgc:
                result2.append({"id" : grandchild['Dwgcbh'], "Zylb":grandchild['Zylb'],  "label": grandchild["Dwgcmc"], "children" : getDwgc(grandchild['Dwgcbh'], grandchild['Zylb'])})
            result.append({"id" : dxgc['Dxgcbh'], "label" : dxgc['Dxgcmc'], "children" : result2})
    return result
        
async def getDetail(client, id):


    db = client["baojia"]
    collection = db["jingjibiao"]
    document = await collection.find_one({'_id': ObjectId(id)})
    result = []
    ##result.append(["名称", "金额", "暂估价", "安全文明施工费", "规费"])
    if 'TouBiaoXx' in document:
        toubiaoxx = document["TouBiaoXx"]
        result.append({'名称': '投标总价', '金额' : toubiaoxx["Tbzj"], '暂估价': toubiaoxx["Zgj"], '安全文明施工费': toubiaoxx["Aqwmf"], '规费' : toubiaoxx["Gf"], '_children': []})
        
        if 'Dxgcxx' in document:
            Dxgcxx = document["Dxgcxx"]
            for dxgc in Dxgcxx:
            
                result[0]['_children'].append({'名称' :dxgc["Dxgcmc"], '金额' : dxgc["Je"], '暂估价' : dxgc["Zgj"],'安全文明施工费' : dxgc["Aqwmf"], '规费' : dxgc["Gf"]})
        return result
    else:
        if 'Dxgcxx' in document:
            Dxgcxx = document["Dxgcxx"]
            for dxgc in Dxgcxx:
            
                result.append({'名称' :dxgc["Dxgcmc"], '金额' : dxgc["Je"], '暂估价' : dxgc["Zgj"],'安全文明施工费' : dxgc["Aqwmf"], '规费' : dxgc["Gf"]})
        return result


async def getBjhz(client, objectid, id):
    db = client["baojia"]


    collection = db["Dwgc"]
    document = await collection.find_one({ "Dwgcbh": id, "biao_id": objectid})


    return document['bjhz']




async def getGfsj(client, objectid, id):
    db = client["baojia"]


    collection = db["Dwgc"]
    document = await collection.find_one({ "Dwgcbh": id, "biao_id": objectid})


    return document['gfsj']


async def getQtxm(client, objectid, id):
    db = client["baojia"]


    collection = db["Dwgc"]
    document = await collection.find_one({ "Dwgcbh": id, "biao_id": objectid})


    return document['qtxm']

async def getZygczgj(client, objectid, id):
    db = client["baojia"]


    collection = db["Dwgc"]
    document = await collection.find_one({ "Dwgcbh": id, "biao_id": objectid})


    return document['zygczgj']

async def getZlje(client, objectid, id):
    db = client["baojia"]


    collection = db["Dwgc"]
    document = await collection.find_one({ "Dwgcbh": id, "biao_id": objectid})


    return document['zlje']

async def getJrg(client, objectid, id):
    db = client["baojia"]


    collection = db["Dwgc"]
    document = await collection.find_one({ "Dwgcbh": id, "biao_id": objectid})

    return document['jrg']

async def getZcbfwf(client, objectid, id):
    db = client["baojia"]


    collection = db["Dwgc"]
    document = await collection.find_one({"Dwgcbh": id, "biao_id": objectid})


    return document['zcbfwf']
    

async def getFbrgycl(client, objectid, id):
    db = client["baojia"]


    collection = db["Dwgc"]
    document = await collection.find_one({ "Dwgcbh": id, "biao_id": objectid})


    return document['fbrgycl']

async def getRcjhz(client, objectid, id):
    db = client["baojia"]


    collection = db["Dwgc"]
    document = await collection.find_one({ "Dwgcbh": id, "biao_id": objectid})

    return document['rcjhz']

async def getZjcs(client, objectid, id):
    db = client["baojia"]


    collection = db["Dwgc"]
    document = await collection.find_one({ "Dwgcbh": id, "biao_id": objectid})

    return document['zjcs']

async def getDjcs(client, objectid, id):
    db = client["baojia"]


    collection = db["Djcs"]
    result = []
    async for post in collection.find({"Dwgcbh": id, "biao_id": objectid}):
        ##post["ID"] = post["_id"]
        del post["_id"]
        ##print( post["rcj"])
       ## del post["DogNum"]
        result.append(post)


    return result

async def getDjcsQingdanrcj(client, name, bh, bt, bm):
    db = client["baojia"]
   

    collection = db["Djcs"]
    document = await collection.find_one({ "Dwgcbh": bh, "清单编码": bm, "biao_id": name})
    result = document["rcj"]
    return result


async def getDjcsDingercj(client, name, bh, bt, qdbm, debm):
    db = client["baojia"]
    

    collection = db["Djcs"]
    document = await collection.find_one({"Dwgcbh": bh, "清单编码": qdbm, "biao_id": name})
    children = document["__children"]
    result = []
    for child in children:
        if child["清单编码"] == debm:
            result = child["dercj"]
    return result


async def getQdxm(client, name, bh):
    db = client["baojia"]
    collection = db["Dwgc"]
    document = await collection.find_one({'biao_id': name, "Dwgcbh": bh})
    if document:
        return  document['qdbt']
    else:
        return []
    
async def getQdmx(client, name, bh, bt):
    db = client["baojia"]
    collection = db["qdxm"]
    result = []
    async for post in collection.find({'biao_id': name, "Dwgcbh": bh, "bt": bt}):
        ##post["ID"] = post["_id"]
        del post["_id"]
        #del post["rcj"]
        #del post["DogNum"]
        result.append(post)
    return result



async def getQingdanrcj(client, name, bh, bt, bm):
    db = client["baojia"]
    collection = db["qdxm"]


    document = await collection.find_one({ "Dwgcbh": bh, "清单编码": bm, "biao_id": name, "bt": bt})
    result = document["rcj"]
    return result


async def getDingercj(client, name, bh, bt, qdbm, debm):
    db = client["baojia"]
    

    collection = db["qdxm"]
    document = await collection.find_one({"Dwgcbh": bh, "清单编码": qdbm, "biao_id": name, "bt": bt})
    result = []
    if "__children" in document:
        children = document["__children"]
        
        for child in children:
            if child["清单编码"] == debm:
                result = child["dercj"]
    return result



async def getQufei(client, id):
    db = client["baojia"]
    collection = db["qufei"]
    document = await collection.find_one({'biao_id': id})
    return document['qufei']

async def searchde(client, zhuanye, text):
    db = client["dinge"]
    collection = db["de-collection"]
    result = []
    async for post in  collection.find({'$text': {"$search": "\"" + text + "\""}, "zhuanye": zhuanye}):
        result.append(post["DEBH"] + " " + post['GCLMC'] )
        if len(result) > 10:
            break
    return result






##################################editor##########################


async def updatezjcs(client, id, bh, mc, fl):
    db = client["baojia"]
    collection = db["Dwgc"]
    
    document =  await collection.find_one({'biao_id': id, 'Dwgcbh': bh}, {'rcjhz': 0})
    zjcs = document['zjcs']
    for entry in zjcs:
        if entry['名称'] == mc:
            entry['费率'] = fl
            entry['金额'] = str(float(entry['计算基数']) * float(fl) / float(100))

    await collection.update_one({'biao_id': id, "Dwgcbh": bh}, {'$set': {'zjcs': zjcs}})
    
        



async def save(client, data):
    db = client["baojia"]
    collection = db["qdxm"]
    biao_id = None
    bh = None
    for entry in data:
        entry["__children"] = entry["_children"]
        del entry["_children"]
        biao_id = entry['biao_id']
        bh = entry['Dwgcbh']
        await collection.replace_one({"biao_id": entry["biao_id"], "Dwgcbh": entry["Dwgcbh"], "bt": entry["bt"], "清单编码": entry["清单编码"]}, entry)
    if not biao_id:
        return {"result" : "ok"}
    rcjhz = []
    async for post in collection.find({'biao_id': biao_id, "Dwgcbh": bh}, {'__children': 0}):
        qdrcj = post['rcj'][1:]
        for entry in qdrcj:
            entry[10] = float(entry[10]) * float(post['数量'])
        rcjhz = rcjhz + qdrcj
    collection = db["Djcs"]
    async for post in collection.find({'biao_id': biao_id, "Dwgcbh": bh}, {'__children': 0}):
        
        qdrcj = post['rcj'][1:]
        for entry in qdrcj:
            entry[10] = float(entry[10]) * float(post['数量'])
        rcjhz = rcjhz + qdrcj
    newHuizong = util.huizongrcj(rcjhz)
    collection = db["Dwgc"]
    await collection.update_one({'biao_id': biao_id, 'Dwgcbh': bh}, {'$set': {'rcjhz' : newHuizong}})
    await zongjiaDwgc(client, biao_id, bh)
    await tbxx(client, biao_id)
    return {"result": "ok"}

async def savedjcs(client, data):
    db = client["baojia"]
    collection = db["Djcs"]
    biao_id = None
    bh = None
    for entry in data:
        entry["__children"] = entry["_children"]
        del entry["_children"]
        biao_id = entry['biao_id']
        bh = entry['Dwgcbh']
        await collection.replace_one({"biao_id": entry["biao_id"], "Dwgcbh": entry["Dwgcbh"],  "清单编码": entry["清单编码"]}, entry)

    if not biao_id:
        return {"result" : "ok"}
    rcjhz = []
    collection = db["qdxm"]
    async for post in collection.find({'biao_id': biao_id, "Dwgcbh": bh}, {'__children': 0}):
        qdrcj = post['rcj'][1:]
        for entry in qdrcj:
            entry[10] = float(entry[10]) * float(post['数量'])
        rcjhz = rcjhz + qdrcj
    collection = db["Djcs"]
    async for post in collection.find({'biao_id': biao_id, "Dwgcbh": bh}, {'__children': 0}):
        qdrcj = post['rcj'][1:]
        for entry in qdrcj:
            entry[10] = float(entry[10]) * float(post['数量'])
        rcjhz = rcjhz + qdrcj
    newHuizong = util.huizongrcj(rcjhz)
    collection = db["Dwgc"]
    await collection.update_one({'biao_id': biao_id, 'Dwgcbh': bh}, {'$set': {'rcjhz' : newHuizong}})
    await zongjiaDwgc(client, biao_id, bh)
    await tbxx(client, biao_id)
    return {"result": "ok"}

async def applyFL(client, id, data):
    db = client["baojia"]
    collection = db["qufei"]
    
    await collection.replace_one({"biao_id": id}, {"biao_id": id, "qufei": data})
    collection = db['qdxm']
    xm = data[0]
    for dxgc in xm["children"]:
        for dwgc in dxgc["children"]:
            bh = dwgc['key']
            glf = float(dwgc['管理费（%）'])
            lr = float(dwgc['利润（%）'])
            bz = dwgc['备注']
            ##print(bh+glf+lr+bz)
            async for post in collection.find({'biao_id': id, "Dwgcbh": bh}):
                rgfs = float(post['人工费'])
                clfs = float(post['材料费'])
                jxfs = float(post['机械费'])
                sl = float(post['数量'])
                if rgfs < 0.0001 and clfs < 0.0001 and jxfs < 0.0001:
                    continue
                ##danxiang = False
                
                for child in post['__children']:##一条定额
                    bm = child['清单编码']
                    if bm.startswith("D"):
                        ##danxiang = True
                        continue
                    rgf = float(child['人工费'])
                    clf = float(child['材料费'])
                    jxf = float(child['机械费'])
                    zhdj = float(child['综合单价'])
                    sl_ = float(child['数量'])
                    if len(bz) == 0:
                        ##常规计算
                        child['管理费'] = (rgf + jxf) * glf / float(100)
                        child['利润'] = (rgf + jxf) * lr / float(100)
                        child['综合单价'] = rgf + clf + jxf + child['管理费'] + child['利润']
                        child['合价'] = sl * sl_ * child['综合单价'] 

                    else:
                        child['管理费'] = (rgf) * glf / float(100)
                        child['利润'] = (rgf) * lr / float(100)
                        child['综合单价'] = rgf + clf + jxf + child['管理费'] + child['利润']
                        child['合价'] = sl * sl_ * child['综合单价'] 
                if True:
                    post['管理费'] = 0
                    post['利润'] = 0
                    for entry in post['__children']:
                        post['管理费'] = post['管理费'] + float(entry['管理费']) * float(entry['数量'])
                        post['利润'] = post['利润'] + float(entry['利润']) * float(entry['数量'])
                    post['管理费'] =  str(post['管理费'])
                    post['利润'] = str(post['利润'])
                    post['综合单价'] = str(float(post['人工费']) + float(post['材料费']) + float(post['机械费']) + float(post['管理费']) + float(post['利润']))
                    post['合价'] = str(float(post['综合单价']) * float(post['数量']))
                    
                

                await collection.replace_one({'_id': post['_id']}, post )
    collection = db['Djcs']
    
    for dxgc in xm["children"]:
        for dwgc in dxgc["children"]:
            bh = dwgc['key']
            glf = float(dwgc['管理费（%）'])
            lr = float(dwgc['利润（%）'])
            bz = dwgc['备注']
            ##print(bh+glf+lr+bz)
            async for post in collection.find({'biao_id': id, "Dwgcbh": bh}):
                rgfs = float(post['人工费'])
                clfs = float(post['材料费'])
                jxfs = float(post['机械费'])
                sl = float(post['数量'])
                if rgfs < 0.0001 and clfs < 0.0001 and jxfs < 0.0001:
                    continue
                ##danxiang = False##一般有单项定额的，清单就一条定额，就是这个单项定额
                
                for child in post['__children']:
                    bm = child['清单编码']
                    if bm.startswith("D"):
                        ##danxiang = True
                        continue
                    rgf = float(child['人工费'])
                    clf = float(child['材料费'])
                    jxf = float(child['机械费'])
                    zhdj = float(child['综合单价'])
                    sl_ = float(child['数量'])
                    if len(bz) == 0:
                        ##常规计算
                        child['管理费'] = (rgf + jxf) * glf / float(100)
                        child['利润'] = (rgf + jxf) * lr / float(100)
                        child['综合单价'] = rgf + clf + jxf + child['管理费'] + child['利润']
                        child['合价'] = sl * sl_ * child['综合单价'] 

                    else:
                        child['管理费'] = (rgf) * glf / float(100)
                        child['利润'] = (rgf) * lr / float(100)
                        child['综合单价'] = rgf + clf + jxf + child['管理费'] + child['利润']
                        child['合价'] = sl * sl_ * child['综合单价'] 
                if True:
                    post['管理费'] = 0
                    post['利润'] = 0
                    for entry in post['__children']:
                        post['管理费'] = post['管理费'] + float(entry['管理费']) * float(entry['数量'])
                        post['利润'] = post['利润'] + float(entry['利润']) * float(entry['数量'])
                    post['管理费'] =  str(post['管理费'])
                    post['利润'] = str(post['利润'])
                    post['综合单价'] = str(float(post['人工费']) + float(post['材料费']) + float(post['机械费']) + float(post['管理费']) + float(post['利润']))
                    post['合价'] = str(float(post['综合单价']) * float(post['数量']))
                    

                await collection.replace_one({'_id': post['_id']}, post )


    for dxgc in xm["children"]:
        for dwgc in dxgc["children"]:
            bh = dwgc['key']
            await zongjiaDwgc(client, id, bh)
    await tbxx(client, id)
    return {"result": "ok"}



async def tiaojia(client, biao_id, bh, bm, mingcheng, danwei, jiage, glf, lr, bz):
    db = client["baojia"]
    collection = db["qdxm"]
    async for post in collection.find({'biao_id': biao_id, "Dwgcbh": bh}):
        if "__children" not in post:
            ##print(post)
            continue
        children = post["__children"]
        qdsl = post['数量']
        hit = False
        for entry in children:###对一条定额，调价
            hitde = False
            dercj = entry["dercj"]
            dergf = 0
            declf = 0
            dezcf = 0
            dejxf = 0
            for i in range(1, len(dercj)):
                rcj = dercj[i]
                if rcj[1] == bm and rcj[2] == mingcheng and rcj[4] == danwei:
                    hit = True
                    hitde = True
                    rcj[5] = jiage
                    hanliang = rcj[10]
                    rcj[11] = str(float(jiage) * float(hanliang))
                if int(rcj[8]) == 1:
                    dergf = dergf + float(rcj[11])
                elif int(rcj[8]) == 2:
                    declf = declf + float(rcj[11])
                    if rcj[14] == 'true' :
                        dezcf = dezcf + float(rcj[11])
                elif int(rcj[8]) == 3:
                    dejxf = dejxf + float(rcj[11])
                if hitde:
                    entry['人工费'] = str(dergf)
                    entry['辅材费'] = str(declf - dezcf)
                    entry['主材费'] = str(dezcf)
                    entry['材料费'] = str(declf)
                    entry['机械费'] = str(dejxf)
                    if bm.startswith("D"):
                        entry['管理费'] = '0'
                        entry['利润'] = '0'
                    elif bz == 0:
                        entry['管理费'] = str((dergf + dejxf) * float(glf) / float(100))
                        entry['利润'] =   str((dergf + dejxf) * float(lr) / float(100))
                    else:
                        entry['管理费'] = str((dergf) * float(glf) / float(100))
                        entry['利润'] =   str((dergf) * float(lr) / float(100))
                    entry['综合单价'] = str(float(entry['人工费']) + float(entry['材料费']) + float(entry['机械费']) + float(entry['管理费']) + float(entry['利润']))
                    entry['合价'] = str(float(entry['综合单价']) * float(entry['数量']) * float(qdsl))
        if hit:
            ##调整清单
            qdrcj = post['rcj']
            qdrgf = 0
            qdclf = 0
            qdzcf = 0
            qdjxf = 0
            for i in range(1, len(qdrcj)):
                entry = qdrcj[i]
                if entry[1] == bm and entry[2] == mingcheng and entry[4] == danwei:
                    entry[5] = jiage
                    hanliang = entry[10]
                    entry[11] = str(float(jiage) * float(hanliang))
                if int(entry[8]) == 1:
                    qdrgf = qdrgf + float(entry[11])
                elif int(entry[8]) == 2:
                    qdclf = qdclf + float(entry[11])
                    if entry[14] == 'true':
                        qdzcf = qdzcf + float(entry[11])
                elif int(entry[8]) == 3:
                    qdjxf = qdjxf + float(entry[11])
            post['人工费'] = str(qdrgf)
            post['辅材费'] = str(qdclf - qdzcf)
            post['主材费'] = str(qdzcf)
            post['材料费'] = str(qdclf)
            post['机械费'] = str(qdjxf)
            post['管理费'] = 0
            post['利润'] = 0
            for entry in children:
                post['管理费'] = post['管理费'] + float(entry['管理费']) * float(entry['数量'])
                post['利润'] = post['利润'] + float(entry['利润']) * float(entry['数量'])
            post['管理费'] =  str(post['管理费'])
            post['利润'] = str(post['利润'])

            post['综合单价'] = str(float(post['人工费']) + float(post['材料费']) + float(post['机械费']) + float(post['管理费']) + float(post['利润']))
            post['合价'] = str(float(post['综合单价']) * float(qdsl))
            ##print(post)
            await collection.replace_one({'_id': post['_id']}, post )
    collection = db["Djcs"]
    async for post in collection.find({'biao_id': biao_id, "Dwgcbh": bh}):
        children = post["__children"]
        qdsl = post['数量']
        hit = False
        for entry in children:###对一条定额，调价
            hitde = False
            dercj = entry["dercj"]
            dergf = 0
            declf = 0
            dejxf = 0
            for i in range(1, len(dercj)):
                rcj = dercj[i]
                if rcj[1] == bm and rcj[2] == mingcheng and rcj[4] == danwei:
                    hit = True
                    hitde = True
                    rcj[5] = jiage
                    hanliang = rcj[10]
                    rcj[11] = str(float(jiage) * float(hanliang))
                if int(rcj[8]) == 1:
                    dergf = dergf + float(rcj[11])
                elif int(rcj[8]) == 2:
                    declf = declf + float(rcj[11])
                elif int(rcj[8]) == 3:
                    dejxf = dejxf + float(rcj[11])
                if hitde:
                    entry['人工费'] = str(dergf)
                    entry['辅材费'] = str(declf)
                    entry['材料费'] = str(declf)
                    entry['机械费'] = str(dejxf)
                    if bm.startswith("D"):
                        entry['管理费'] = '0'
                        entry['利润'] = '0'  
                    elif bz == 0:
                        entry['管理费'] = str((dergf + dejxf) * float(glf) / float(100))
                        entry['利润'] =   str((dergf + dejxf) * float(lr) / float(100))
                    else:
                        entry['管理费'] = str((dergf) * float(glf) / float(100))
                        entry['利润'] =   str((dergf) * float(lr) / float(100))
                    entry['综合单价'] = str(float(entry['人工费']) + float(entry['材料费']) + float(entry['机械费']) + float(entry['管理费']) + float(entry['利润']))
                    entry['合价'] = str(float(entry['综合单价']) * float(entry['数量']) * float(qdsl))
        if hit:
            ##调整清单
            qdrcj = post['rcj']
            qdrgf = 0
            qdclf = 0
            qdjxf = 0
            for i in range(1, len(qdrcj)):
                entry = qdrcj[i]
                if entry[1] == bm and entry[2] == mingcheng and entry[4] == danwei:
                    entry[5] = jiage
                    hanliang = entry[10]
                    entry[11] = str(float(jiage) * float(hanliang))
                if int(entry[8]) == 1:
                    qdrgf = qdrgf + float(entry[11])
                elif int(entry[8]) == 2:
                    qdclf = qdclf + float(entry[11])
                elif int(entry[8]) == 3:
                    qdjxf = qdjxf + float(entry[11])
            post['人工费'] = str(qdrgf)
            post['辅材费'] = str(qdclf)
            post['材料费'] = str(qdclf)
            post['机械费'] = str(qdjxf)
            post['管理费'] = 0
            post['利润'] = 0
            for entry in children:
                post['管理费'] = post['管理费'] + float(entry['管理费']) * float(entry['数量'])
                post['利润'] = post['利润'] + float(entry['利润']) * float(entry['数量'])
            post['管理费'] =  str(post['管理费'])
            post['利润'] = str(post['利润'])

            post['综合单价'] = str(float(post['人工费']) + float(post['材料费']) + float(post['机械费']) + float(post['管理费']) + float(post['利润']))
            post['合价'] = str(float(post['综合单价']) * float(qdsl))
            await collection.replace_one({'_id': post['_id']}, post )
    collection = db["Dwgc"]
    document = await collection.find_one({'biao_id': biao_id, "Dwgcbh": bh})
    hz = document['rcjhz']
    for entry in hz:
        if entry[1] == bm and entry[2] == mingcheng and entry[4] == danwei:
            entry[6] = jiage
            entry[7] = float(jiage) * float(entry[5])
    await collection.update_one({'biao_id': biao_id, "Dwgcbh": bh}, {'$set': {'rcjhz': hz}})
    await zongjiaDwgc(client, biao_id, bh)
    await tbxx(client, biao_id)



def bjhz_template():
    result = []
    result.append({'序号': '1', '名称': '分部分项工程', '金额': '0', '暂估价': '0', '类别' : '1', '__children': [
        {'序号': '1.1', '名称': '人工费', '金额': '0', '暂估价': '0', '类别' : '1.1'},
        {'序号': '1.2', '名称': '材料费', '金额': '0', '暂估价': '0', '类别' : '1.2'},
        {'序号': '1.3', '名称': '施工机具使用费', '金额': '0', '暂估价': '0', '类别' : '1.3'},
        {'序号': '1.4', '名称': '企业管理费', '金额': '0', '暂估价': '0', '类别' : '1.4'},
        {'序号': '1.5', '名称': '利润', '金额': '0', '暂估价': '0', '类别' : '1.5'}
    ]})
    result.append({'序号': '2', '名称': '措施项目', '金额': '0', '暂估价': '0', '类别' : '2', '__children': [
        {'序号': '2.1', '名称': '单价措施项目费', '金额': '0', '暂估价': '0', '类别' : '2.1'},
        {'序号': '2.2', '名称': '总价措施项目费', '金额': '0', '暂估价': '0', '类别' : '2.2', '__children' : [
        {'序号': '2.2.1', '名称': '其中：安全文明施工措施费', '金额': '0', '暂估价': '0', '类别' : '2.2.1'},]
        }
       
    ]})
    result.append({'序号': '3', '名称': '其他项目', '金额': '0', '暂估价': '0', '类别' : '3', '__children': [
        {'序号': '3.1', '名称': '其中：暂列金额', '金额': '0', '暂估价': '0', '类别' : '3.1'},
        {'序号': '3.2', '名称': '其中：专业工程暂估价', '金额': '0', '暂估价': '0', '类别' : '3.2'},
        {'序号': '3.3', '名称': '其中：计日工', '金额': '0', '暂估价': '0', '类别' : '3.3'},
        {'序号': '3.4', '名称': '其中：总承包服务费', '金额': '0', '暂估价': '0', '类别' : '3.4'},
        
    ]})
    result.append({'序号': '4', '名称': '规费', '金额': '0', '暂估价': '0', '类别' : '4', })
    result.append({'序号': '5', '名称': '税金', '金额': '0', '暂估价': '0', '类别' : '5', })
    result.append({'序号': '6', '名称': '工程造价', '金额': '0', '暂估价': '0', '类别' : '6', })

    return result



async def tbxx(client, biao_id):
    db = client["baojia"]
    collection = db["jingjibiao"]
    document = await collection.find_one({'_id': ObjectId(biao_id)})
    dxgcxx = document['Dxgcxx']
    tbxx = document['TouBiaoXx']
    tbxx['Tbzj'] = '0'
    tbxx['Zgj'] = '0'
    tbxx['Aqwmf'] = '0'
    tbxx['Gf'] = '0'
    
    dwdx = {}##单位工程映射单项工程
    for dxgc in dxgcxx:
        dxgc['Aqwmf'] = '0'
        dxgc['Gf'] = '0'
        dxgc['Je'] = '0'
        dxgc['Zgj'] = '0'
        mc = dxgc['Dxgcmc']
        Dwgc = dxgc['Dwgc']
        for dwgc in Dwgc:
            Dwgcbh = dwgc['Dwgcbh']
            dwdx[Dwgcbh] = dxgc
    collection = db['Dwgc']
    async for post in collection.find({'biao_id': biao_id}):
        bh = post['Dwgcbh']
        dx = dwdx[bh]
        bjhz = post['bjhz']
        print('######################################################')
        print(bjhz)
        if len(bjhz) == 0:
            pass
        else:
            qtxm = post['qtxm']
            dx['Aqwmf'] = str(float(dx['Aqwmf']) + float(bjhz[1]['__children'][1]['__children'][0]['金额']))
            dx['Gf'] = str(float(dx['Gf']) + float(bjhz[3]['金额']))
            dx['Je'] = str(float(dx['Je']) + float(bjhz[5]['金额']))
            dx['Zgj']= str(float(dx['Zgj']) + float(qtxm[1]['金额']))
    for dxgc in dxgcxx:
        tbxx['Tbzj'] = str(float(tbxx['Tbzj']) + float(dxgc['Je']))
        tbxx['Zgj'] = str(float(tbxx['Zgj']) + float(dxgc['Zgj']))
        tbxx['Aqwmf'] = str(float(tbxx['Aqwmf']) + float(dxgc['Aqwmf']))
        tbxx['Gf'] = str(float(tbxx['Gf']) + float(dxgc['Gf']))
    collection = db["jingjibiao"]


    await collection.update_one({'_id': ObjectId(biao_id)}, {'$set': {'Dxgcxx': dxgcxx, 'TouBiaoXx' : tbxx}})





        


    
        

    


async def zongjiaDwgc(client, biao_id, bh):
    db = client["baojia"]
    djcs_sum = 0
    collection = db["Djcs"]
    async for post in collection.find({'biao_id': biao_id, "Dwgcbh": bh}, {'__children': 0}):
        djcs_sum = djcs_sum + float(post['合价'])
    
    collection = db['Dwgc']
    document = await collection.find_one({'biao_id': biao_id, "Dwgcbh": bh}, {'rcjhz': 0})
    qdbt = document['qdbt']
    qdbt_addition = document['qdbt_addition']
    bts = {}
    distinguish = True
    
    for item in qdbt_addition:
        bts[item['Mc']] = 0
    
    collection = db["qdxm"]
    qd_sum = 0
    rgf_sum = 0
    clf_sum = 0
    jxf_sum = 0
    glf_sum = 0
    lr_sum = 0
    fbrgycl_sum = 0
    async for post in collection.find({'biao_id': biao_id, "Dwgcbh": bh}, {'__children': 0}):
        qd_sum = qd_sum + float(post['合价'])
        rgf_sum = rgf_sum + float(post['数量']) * float(post['人工费'])
        clf_sum = clf_sum + float(post['数量']) * float(post['材料费'])
        jxf_sum = jxf_sum + float(post['数量']) * float(post['机械费'])
        glf_sum = glf_sum + float(post['数量']) * float(post['管理费'])
        lr_sum = lr_sum + float(post['数量']) * float(post['利润'])
        if distinguish and post['bt'] in bts:
            bts[post['bt']] = bts[post['bt']] + float(post['合价'])




    sum = qd_sum + djcs_sum




    fbrgycl = document['fbrgycl']
    for entry in fbrgycl:
        fbrgycl_sum = fbrgycl_sum + float(entry['合价'])
    zjcs = document['zjcs']
    def process(n):
        n['计算基数'] = str(sum)
        n['金额'] = float(sum) * float(n['费率']) / float(100)
        if "__children" in n:
            for entry in n['__children']:
                entry['计算基数'] = str(sum)
                entry['金额'] = float(sum) * float(entry['费率']) / float(100)
        return n


    result = [process(item) for item in zjcs]
    for entry in result:
        if '安全文明施工' in entry['名称']:
            sum_ = 0
            for child in entry['__children']:
                sum_ = sum_ + float(child['金额'])
            entry['金额'] = str(sum_)
            entry['计算基数'] = str(sum_)
    zjcs_sum = 0
    for entry in result:
        zjcs_sum = zjcs_sum + float(entry['金额'])
    qtxm = document['qtxm']##dwgc qtxm
    qtxm_sum = 0
    for entry in qtxm:
        qtxm_sum = qtxm_sum + float(entry['金额'])
    gfsj = document['gfsj']
    gf_sum = 0
    sj_sum = 0
    for item in gfsj:
        if item['名称'] == '规费':
            child = item['__children']
            for children in child:
                children['取费基数'] = str(sum + zjcs_sum + qtxm_sum)
                children['金额'] = str(float(sum + zjcs_sum + qtxm_sum) * float(children['费率']) / float(100))
                gf_sum = gf_sum + float(children['金额'])
    for item in gfsj:
        if item['名称'] == '规费':
            item['取费基数'] = str(gf_sum)
            item['金额'] = str(gf_sum)
    for item in gfsj:
        if item['名称'] == '税金':
            item['取费基数'] = str(sum + zjcs_sum + qtxm_sum + gf_sum - fbrgycl_sum / float(1.01))
            item['金额'] = float(item['取费基数']) * float(item['费率']) / float(100)
            sj_sum = float(item['金额'])
    for item in gfsj:
        if item['名称'] == '合计':
            item['取费基数'] = str(sj_sum + gf_sum)
            item['金额'] = item['取费基数']

    qtxm = document['qtxm']
    zlje = 0
    zygczgj = 0
    jrg = 0
    zcbfwf = 0
    clzgj = 0
    for entry in qtxm:
        if entry['序号'] == '1':
            zlje = entry['金额']
        if entry['序号'] == '3':
            jrg = entry['金额']
        if entry['序号'] == '4':
            zcbfwf = entry['金额']
        if entry['序号'] == '2':
            for child in entry['__children']:
                if child['序号'] == '2.2':
                    zygczgj = child['金额']
                if child['序号'] == '2.1':
                    clzgj = child['金额']
    qtxm_sum = float(zlje) + float(zygczgj) + float(jrg) + float(zcbfwf) + float(clzgj)
                





    bjhz = bjhz_template()
    for entry in bjhz:
        if entry['序号'] == '1':
            entry['金额'] = qd_sum
            for child in entry['__children']:
                if child['序号'] == '1.1':
                    child['金额'] = str(rgf_sum)
                if child['序号'] == '1.2':
                    child['金额'] = str(clf_sum)
                if child['序号'] == '1.3':
                    child['金额'] = str(jxf_sum)
                if child['序号'] == '1.4':
                    child['金额'] = str(glf_sum)
                if child['序号'] == '1.5':
                    child['金额'] = str(lr_sum)
        if entry['序号'] == '2':
            entry['金额'] = str(djcs_sum + zjcs_sum)
            for child in entry['__children']:
                if child['序号'] == '2.1':
                    child['金额'] = str(djcs_sum)
                if child['序号'] == '2.2':
                    child['金额'] = str(zjcs_sum)
                    for grandchild in child['__children']:
                        if grandchild['序号'] == '2.2.1':
                            grandchild['金额'] = str(sum_)
        if entry['序号'] == '3':
            entry['金额'] = str(qtxm_sum)
        if entry['序号'] == '4':
            entry['金额'] = str(gf_sum)
        if entry['序号'] == '5':
            entry['金额'] = str(sj_sum)
        if entry['序号'] == '6':
            entry['金额'] = str(float(qd_sum) + float(djcs_sum) + float(zjcs_sum) + float(qtxm_sum) + float(gf_sum) + float(sj_sum))
        



    
    collection = db['Dwgc']
    if distinguish:
        for entry in qdbt_addition:
            entry['Je'] = str(bts[entry['Mc']])


    
    await collection.update_one({'biao_id': biao_id, "Dwgcbh": bh}, {'$set': {'zjcs': result, 'gfsj' : gfsj, 'bjhz': bjhz, 'qdbt_addition' : qdbt_addition}})
    



    
    
    



            
                    






