import os
from docx.shared import Pt
import math
import Levenshtein
import json

#采购文件有 pdf、doc、docx

aaa = [['条款号', None, '评审因素', '评审标准', None],
['2.1.\n1', '形式评\n审标准', '报价人名称', '与营业执照、资质证书一致', None],
[None, None, '报价函签字盖章', '有法定代表人或其委托代理人签字或加盖单位章', None],
[None, None, '报价文件格式', '符合五章“报价文件格式”的要求', None],
[None, None, '报价唯一', '只能有一个有效报价', None],
['2.1.\n2', '资格评\n审标准', '营业执照', '具备有效的营业执照', None],
[None, None, '资质等级', '符合报价邀请函第3项规定', None],
[None, None, '项目经理', '符合报价邀请函第3项规定', None],
[None, None, '财务要求', '符合报价邀请函第3项规定', None],
[None, None, '业绩要求', '符合报价邀请函第3项规定', None],
[None, None, '其他要求', '符合报价邀请函第3项规定', None],
[None, None, '评标价基准值计算方法', '以所有通过初步评审的投标人评标价算术平均值×0.97作为本次评审的评标价基准值B。并应满足计算规则：\n（1）当参与计算的投标人超过5家时去掉一个最高评标价和一个最低评标价；\n（2）当同一企业集团多家所属企业（单位）参与本项目投标时，取其中最低评标价参与评标价基准值计算，无论', None],
[None, None, '', '该价格是否在步骤（1）中被筛选掉；\n（3）依据（1）、（2）规则计算B值后，如参与计算的投标人不少于3名，去掉评标价高于B值×130%（含）的评标价，重新按本步骤计算一轮B值。\n投标人评标价：指各投标人经算术错误修正后的投标报价（含增值税）。', None],
['2.1.\n3', '响应性\n评审\n标准', '报价', '符合采购文件规定', None],
[None, None, '报价内容', '符合采购文件规定', None],
[None, None, '服务期', '符合采购文件规定', None],
[None, None, '报价有效期', '符合采购文件规定', None],
[None, None, '报价保证金', '符合采购文件规定', None],
[None, None, '权利义务', '符合第三章“合同条款及格式”规定', None],
[None, None, '已标价的报价表', '符合采购文件规定', None],
[None, None, '服务标准和要求', '符合采购文件规定', None],
['条款号', None, '条款内容', '编列内容', None],
['2.2.1', None, '评分权重构成（100%）', '商务部分：20%\n报价部分：30%\n技术部分：50%', None],
['2.2.2', None, '评审基准价计算方法', '所有初步评审合格的报价人中最低报价作为评审基\n准价。税率不一致时以不含税价作为报 价人评审价。', None],
['2.2.3', None, '报价的偏差率\n计算公式', '偏差率（Di）=100% ×（不含税报价−评审基准价）/\n评审基准价', None],
['条款号', None, '评分因素', '评分标准', '权重'],
['2.2.\n4(1)', '商务部\n分评分', '报价文件的完整性', '检查报价文件在内容与项目上的完整性，针\n对报价人提出的非实质性商务偏差，评价其', '3%'],
['', '标准\n(20%)', '', '是否合理，是否会损害采购人的利益和未来\n的合同执行。评分结果分为A～D四个档次。', ''],
[None, None, '信用评价', '根据三峡集团公司最新发布的年度供应商\n信用评价结果进行统一评分，A、B、C三个\n等级信用得分分别 为100、85、70分。如报\n价人初次进入三峡集团公司报价，由评审小\n组根据其以往业绩及在其他单位的合同履\n约情况合理确定本次 评审信用等级。', '3%'],
[None, None, '财务状况', '评价报价人财务状况。评分结果分为A～D\n四个档次。', '1%'],
[None, None, '业绩', '结合本项目的要求对投标人提供的历史业\n绩进行评价（相似度\\可借鉴性\\维护作业经\n验\\业绩数量）。评分结果分为A～D四个\n档次', '10%'],
[None, None, '报价的合理性', '对主要报价进行合理性评审。评分结果分为\nA～D四个档次。', '3%'],
['2.2.\n4(2)', '报价评\n分标准\n(30%)', '价格得分', '满足谈判文件要求且最终报价最低的供应\n商的价格为评审基准价，其价格 分为满分。\n其他供应商的价格分统一按照下列公式计\n算：\n报价得分=（评审基准价÷最后报价）×价\n格权值×100', '30%'],
['2.2.\n4(3)', '技术部\n分评分\n标准\n(50%)', '资源配置', '1、管理人员配置；\n2、专业技术人员配置；\n3、其它资源配置。\n评分结果分为A～D四个档次。', '25%'],
[None, None, '实施方案', '1、整体施工方案及对本项目的重难点分析；\n2、施工程序及进度保障措施；\n3、质量保障措施；\n4、安全文明施工计划。\n评分结果分为A～D四个档次。', '20%'],
[None, None, '应急保障能力', '1、列明项目实施中可能出现的突发事件及\n相应的应急措施；\n2、应急响应时效及相应的保障措施。\n评分结果分为A～D四个档次。', '5%']]

keys = ['形式评', '资格评', '响应性', '商务部', '报价评', '技术部']

#评审因素


index_list = []

_aaa = []

for i in range(len(aaa)):
    a = aaa[i]
    if a[1] and a[1].split('\n')[0] in keys:
        index_list.append(i)
    if a[0] == '条款号':
        continue
    if a[-1] and a[-1] and i < len(aaa) - 1 and aaa[i+1][-1] == '': #not a[3][-2:] in ['规定', '档次', '次。'] and len(index_list) > 2:
        #print(a, aaa[i+1])
        for j in range(len(a)):
            try:
                aaa[i][j] = aaa[i][j] + aaa[i+1][j]
                aaa[i+1][j] = ''
            except:
                pass
    if a[2] and a[2] and i < len(aaa) - 1 and aaa[i+1][2] == '':
        for j in range(len(a)):
            try:
                aaa[i][j] = aaa[i][j] + aaa[i+1][j]
                aaa[i+1][j] = ''
            except:
                pass

for i in range(len(aaa)):
    falg = 0
    for j in range(len(aaa[i])):
        if aaa[i][j]:
            falg = 1
            break
    if falg == 0:
        continue
    print(aaa[i])
print(index_list)

#采购文件
#跨页表格合并
#1、上下内容合并
#2、缺失项合并
# 第3列、第5列 重新为空的，但是上一行不为空的大概率需要做2行合并操作



#采购文件-报价模板
#技术规范
#工作量区域定位
#技术规范 的工作量清单数据抽取
#表头信息？
#报价功能项 结构化数据抽取
#
#工作量表头需要固定死  ["序号","项目名称","工作内容","单位","数量","规格"]
aaa = [["水轮发电机组11", None, None, None, None, None],
    ["序号","项目名称","工作内容","单位","数量","备 注"],
["水轮发电机组", None, None, None, None, None],
["1","水轮发电机组并网监测及同期过程状态评价理论体系和算法研究","内容包括：1）水轮发电机组开机过程动态性能评估体系及算法研究，提交报告1份；2）水轮发电机组同期过程状态评价体系及算法研究，提交报告1份；3）水轮发电机组在网监测体系及算法研究，提交报告1份；具体要求详见6.2.1。","项","1"],
["2","硬件装置制作","硬件装置为定制设备，安装在盘柜内，嵌入式安装；硬件装置主要由信号采集单元、主控制器单元、人机接口单元和应用接口单元组成；具体要求见6.2.2。","项","1",""],
["3","工程师站采购","笔记本式工作站，工程师站承担硬件装置开发应用和高级应用两个功能。具体要求见6.2.3。","项","1",""],
["4","嵌入式软件开发及测试","嵌入式软件是在硬件装置上独立运行，包括数据采集处理、存储、显示、传输等功能；具体要求见6.2.2。","项","1",""],
["5","高级应用开发及测试","高级应用软件应包含硬件装置的全部数据存储和显示功能以及相应工况的高级应用分析报表功能；相应工况的高级应用分析报表功能包括但不限于水轮发电机组开机过程动态性能分析及报表功能、水轮发电机组同期过程状态评价及报表功能、水轮发电机组在网性能监测分析及报表功能；具体要求见6.2.3。","项","1", '']]
aaa1 = [["序号","项目名称","对应表格","产品价格","含税价"],
["1","电源电站直流系统（共1套）","表1.1","",""],
["2","右岸电站机组直流系统（共4套）","表1.2×4","",""],
["3","右岸电站公用直流系统（共1套）","表1.3","",""],
["4","右岸电站光纤接口设备直流系统（共1套）","表1.4","",""],
["5","地下电站GIS直流配电柜（共1套）","表1.5","",""],
["6","地下电站公用直流配电及UPS柜（共1套）","表1.6","",""],
["7","蓄电池组","表1.7","",""],
["8","其他项目","表1.8","",""],
["","总结", None,"", ""]]
#备注列向左新增2列，分别为费用综合单价、合计
#新增一行  合计，
# 报价清单生成
def quotation_table(workload_table, project_name):
    if workload_table:
        for i in range(1, len(workload_table)):
            _flag_length = len(workload_table[i])
            for j in range(_flag_length, len(workload_table[0])):
                if workload_table[i][-1] == None:
                    workload_table[i].append(None)
                else:
                    workload_table[i].append('')
        # print(len(workload_table))
        beg = -1
        for i in range(len(workload_table)):
            if '序号' in workload_table[i]:
                beg = i
                break
        if beg == -1:
            return [], []
        if '备注' in workload_table[beg]:
            _index = workload_table[beg].index('备注')
        else:
            _index = len(workload_table[beg]) - 1
        sub_total_flag = 0
        unit_price_flag = 0
        for i in range(len(workload_table[beg])):
            if '合价' in workload_table[beg][i] or '含税价' in workload_table[beg][i] :
                sub_total_flag = 1      
                _index = i  
                break
        if sub_total_flag == 0:
            workload_table[beg].insert(_index, '含税合价（元）')
            # print(_index)
            for j in range(beg+1, len(workload_table)):
                # print(workload_table[j])
                # print(j, workload_table[j][_index], workload_table[j][_index-1])
                if workload_table[j][_index] == None or (workload_table[j][_index] == workload_table[j][_index-1] and workload_table[j][_index]):
                    workload_table[j].insert(_index, workload_table[j][_index])
                else:
                    workload_table[j].insert(_index, '')
            for j in range(0, beg):
                # print(workload_table[j])
                # print(j, workload_table[j][_index], workload_table[j][_index-1])
                if workload_table[j][_index] == None or (workload_table[j][_index] == workload_table[j][_index-1] and workload_table[j][_index]):
                    workload_table[j].insert(_index, workload_table[j][_index])
                else:
                    workload_table[j].insert(_index, '')

        for i in range(len(workload_table[beg])):
            if '单价' in workload_table[beg][i] or '产品价格' in workload_table[beg][i]:
                unit_price_flag = i
                _index = i
                break
        if unit_price_flag == 0:
            workload_table[beg].insert(_index, '含税单价（元）')
            for j in range(beg+1, len(workload_table)):
                if workload_table[j][_index] == None or (workload_table[j][_index] == workload_table[j][_index-1] and workload_table[j][_index]):
                    workload_table[j].insert(_index, workload_table[j][_index])
                else:
                    workload_table[j].insert(_index, '')
            for j in range(0, beg):
                if workload_table[j][_index] == None or (workload_table[j][_index] == workload_table[j][_index-1] and workload_table[j][_index]):
                    workload_table[j].insert(_index, workload_table[j][_index])
                else:
                    workload_table[j].insert(_index, '')
            unit_price_flag = workload_table[beg].index('含税单价（元）')
        # print(_index, workload_table[0])
        total_array = ["合计："]
        for i in range(beg+1, unit_price_flag):
            total_array.append(None)
        total_array.append("")
        for i in range(unit_price_flag+1, len(aaa[0])):
            total_array.append(None)
        
        workload_table.append(total_array)
    else:
        workload_table = []
        table_head = ["序号","项目名称","工作内容","单位","数量", '含税单价（元）', '含税合价（元）',"备注"]
        unit_price_flag = table_head.index('含税单价（元）')
        workload_table.append(table_head)
        for i in range(1,6):
            table_rows = [str(i)]
            for j in range(1,len(table_head)):
                table_rows.append('')
            workload_table.append(table_rows)
        
        total_array = ["合计："]
        for i in range(1, unit_price_flag):
            total_array.append(None)
        total_array.append("")
        # print(unit_price_flag)
        for i in range(unit_price_flag+1, len(table_head[0])):
            total_array.append(None)
        workload_table.append(total_array)
    # print(aaa)

    table_1 = [["序号","项目名称","不含税合价（元）","税率（%）","增值税额（元）","含税总价（元）","备注"],["1", project_name, "", "", "", "", ""],["总报价：",None,None,None,None,"",""]]
    return table_1, workload_table

#
# 表标题或者表格前标题：工程量清单、材料清单、工作量清单、报价明细表、主要配置（含备品备件、专用工器具）
# 表头：费用、单价、价格、含税价、单价、合价、估算工程量、单位

table_1, workload_table = quotation_table(aaa, '水轮发电机组维修')

print(table_1, workload_table)

from docx import Document

# 加载现有的Word文档
doc = Document()


# 添加一个表格，3行4列
r = len(table_1)
c = len(table_1[0])
doc.add_heading('表1 报价汇总表',level=3)
table = doc.add_table(rows=r, cols=c)

# 设置表格样式（可选）
table.style = 'Table Grid'

# 填充表格数据
data = table_1

# 将数据填入表格
for row_idx, row_data in enumerate(data):
    row = table.rows[row_idx]
    y = 0
    for col_idx, cell_data in enumerate(row_data):        
        
        if row_data[col_idx] == None:
            table.cell(row_idx, y).merge(table.cell(row_idx, col_idx))            
        else:
            cell = row.cells[col_idx]
            cell.text = cell_data
            y = col_idx

# 添加一个表格，3行4列
r = len(workload_table)
c = len(workload_table[0])
doc.add_paragraph("\n")
doc.add_heading('表2 分项报价表',level=3)
table = doc.add_table(rows=r, cols=c)

# 设置表格样式（可选）
table.style = 'Table Grid'

# 填充表格数据
data = workload_table

# 遍历每个cell，设置宽度
for row_idx in range(r):
    for col_idx in range(c):
        if col_idx in [1, 2, 3]:
            row = table.rows[row_idx]
            cell = row.cells[col_idx]
            cell.width = Pt(100)  # 设置宽度为100磅
        if col_idx in [0]:
            row = table.rows[row_idx]
            cell = row.cells[col_idx]
            cell.width = Pt(20)  # 设置宽度为20磅

# 将数据填入表格
for row_idx, row_data in enumerate(data):
    row = table.rows[row_idx]
    y = 0
    for col_idx, cell_data in enumerate(row_data):
        
        if row_data[col_idx] == None:
            table.cell(row_idx, y).merge(table.cell(row_idx, col_idx))            
        else:
            cell = row.cells[col_idx]            
            cell.text = cell_data
            y = col_idx
        

# 保存文档
doc.save('example.docx')


import openpyxl

#分项工程和单价
#分部分项工程和单价措施项目清单与计价表
#本页小计、分部小计、合计
#全费用综合单价分析表
#小计、未计价材料费、清单全费用综合单价

#详细评审
# 商务部分
# 报价抽取 # 报价信息
# 业绩定位及抽取  # 近年类似项目业绩
# 财务状况定位及抽取 # 近年财务状况表
# 业绩 
# 报价的合理性
# 技术部分
# 

#报价得分计算
#demo
aaa = """
当0<Di≤3%时，每高1%扣1分；
当3%<Di≤6%时，每高1%扣1.5分；
当6%<Di，每高1%扣2分；
当-3%<Di≤0时，不扣分；
当-6%<Di≤-3%时，每低1%扣0.5分；
当-9%<Di≤-6%时，每低1%扣1分；
当Di≤-9%时，每低1%扣1.5分；
满分为100分，最低得60分。
"""
aaa = """
报价得分=（评审基准价÷最终报价）×100
"""
import re

#评标价算术平均值\评审价最低价与次低价算术平均值\最低评审价
#去掉一个最高评标价和一个最低评标价
#去掉评审价高于B值
#demo

aaa1 = """以所有通过初步评审的评审价最低价与次低价算术平均值×0.97作为本次评审的评标价基准值B。
并应满足计算规则：
（1）当参与计算的投标人超过5家时去掉一个最高评标价和一个最低评标价；
（2）当同一企业集团多家所属企业（单位）参与本项目投标时，取其中最低评标价参与评标价基准值计算，无论该价格是否在步骤（1）中被筛选掉；
评标价为经算术错误修正后的投标报价（不含增值税）。
（3）依据（1）、（2）规则计算B值后，如参与计算的报价人不少于3名，去掉评审价高于B值×130%（含）的评标价，重新按本步骤计算B值。本步骤仅计算一次。"""

aaa = """
当0<Di≤3%时，每高1%扣1分；
当3%<Di≤6%时，每高1%扣1.5分；
当6%<Di，每高1%扣2分；
当-3%<Di≤0时，不扣分；
当-6%<Di≤-3%时，每低1%扣0.5分；
当-9%<Di≤-6%时，每低1%扣1分；
当Di≤-9%时，每低1%扣1.5分；
满分为100分，最低得60分。"""

#基准值计算方式
def reference_value(datas, key_word):
    if key_word == '评标价算术平均值':
        value = sum(datas)/len(datas)
    elif key_word == '评审价最低价与次低价算术平均值':
        total_list.sort()
        value = sum(datas[:2])/2.0
    elif key_word == '最低评审价':
        value = min(datas)
    else:
        value = min(datas)
    # print(datas, value)
    return value

import copy
total_list = [95,93,92,90,99,117,119]
#基准值计算
def reference_value_count(total_list, aaa):

    total_list_new = copy.copy(total_list)
    coefficient_data = 1.0
    reference_word = '最低评审价'
    aaa = re.sub('\n', '', aaa)
    aaa = re.sub('。|；|;', '\n', aaa)
    for a in aaa.split('\n'):
        # print('coefficient_data', coefficient_data)
        if re.findall('^当', a) and re.findall('\d%', a):
            break
        B_data = re.findall('评标价算术平均值|评审价最低价与次低价算术平均值|最低评审价', a)
        if B_data:
            reference_word = B_data[0]
            coefficient = re.findall('\d\.?\d*', a)
            if coefficient:
                coefficient_data = float(coefficient[0])
            value = reference_value(total_list, reference_word)
            value = value * coefficient_data
        if re.findall('去掉一个最高评标价和一个最低评标价', a):
            num_list  = re.findall('超过\d+家时', a)
            if not num_list:
                num = 5
            else:
                num = int(num_list[0][2:-2])
            if len(total_list) >= num:
                total_list.sort()
                # print(total_list)
                total_list = total_list[1:-1]
            value = reference_value(total_list, reference_word)
            value = value * coefficient_data
        elif re.findall('去掉评审价高于B值', a):
            num_word = re.findall('\d+%', a)
            num_data = 130
            if num_list:
                num_data = int(num_word[0][:-1])
            num_list  = re.findall('不少于\d名', a)
            if not num_list:
                num = 3
            else:
                num = int(num_list[0][3:-1])
            value_new = value * num_data/100
            # print('x'*10, value, value_new)
            new_total_list = []
            if len(total_list) >= num:
                # print(value_new)
                for i in range(len(total_list)):
                    if total_list[i] > value_new:
                        continue
                    new_total_list.append(total_list[i])
                value = reference_value(new_total_list, reference_word)
                value = value * coefficient_data
    # print(value)
    try:
        value
    except:
        value = reference_value(total_list, "评标价算术平均值")
    return value


#计算每多或少一个百分百扣分多少
def score_dict_count(aaa):
    score_json = {}
    aaa = re.sub('\n', '', aaa)
    aaa = re.sub('。|；|;', '\n', aaa)
    for a in aaa.split('\n'):    
        if not a:
            continue
        
        if re.findall('^报价得分=（评审基准价÷最终报价）', a):
            for i in range(-100, 100):
                score_json[i] = 1
            score_json[0] = 1
            break

        if not re.findall('^[当满]', a):
            continue
        
        num_list = re.findall('0|-?\d+%', a.split('，')[0])
        score = re.findall('\d\.?\d*分', a.split('，')[1])
        if num_list[0] == '0':
            num_list[0] = 0
        else:
            num_list[0] = int(num_list[0][:-1])
        if len(num_list) > 1:
            if num_list[1] == '0':
                num_list[1] = 0
            else:
                num_list[1] = int(num_list[1][:-1])
        else:
            if num_list[0] < 0:
                num_list.append(-100)
                num_list[1] = num_list[0]
                num_list[0] = -100
            else:
                num_list.append(100)
        if not score:
            score = 0
        else:
            score = float(score[0][:-1])
        for x in range(num_list[0]+1, num_list[1]+1):
            #print(x)
            score_json[x] = score
        #print(num_list, score)

    min_score_flag = re.findall('最低得\d+分', str(aaa))
    if min_score_flag:
        min_score_flag = float(re.findall('\d+', min_score_flag[0])[0])
    else:
        min_score_flag = 60.0
    print(score_json)
    return score_json, min_score_flag

B = 95
A = 105

#单个企业报价得分
def company_score(A, B, score_json, min_score_flag):
    ratio = (A-B)/B*100
    sum_score = 0
    # print(ratio)
    if ratio < 0:
        for i in range(int(ratio), 0+1):
            sum_score = sum_score + score_json[i]
    else:
        for i in range(0, int(ratio) + 1):
            sum_score = sum_score + score_json[i]
    # print(A,B, sum_score)
    sum_score = 100.0 - sum_score
    if sum_score < min_score_flag:
        sum_score = min_score_flag
    
    # print(A,B, sum_score)
    return sum_score

score_json, min_score_flag = score_dict_count(aaa)

company_score(A, B, score_json, min_score_flag)
company_score(97, B, score_json, min_score_flag)
company_score(136, B, score_json, min_score_flag)
company_score(B, B, score_json, min_score_flag)
value = reference_value_count(total_list, aaa1)
company_list = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
print('x'*20, value)
for i in range(len(company_list)):
    print('投标人'+company_list[i], '报价部分得分为', company_score(total_list[i], value, score_json, min_score_flag))


# 索引表
# 商务、技术评审因素在标书页码位置区域

# 标书标题抽取；
# 评审因素与标书标题一一对应。
# 采购文件->投标人资格要求及评审因素信息抽取，带星★条款获取
# 一一定位
# 投标人名称 -> 资格、资质证书
# 报价函 -> 报价函、投标函
# 业绩 -> 近年类似项目业绩
# 财务要求 -> 审计报告、财务状况表
# 信誉要求 -> 供应商信用评价、信用评价
# 信用 -> 供应商信用评价、信用评价
# 投标人资质 -> 资格、资质
# 项目经理 -> 主要负责人、项目经理、项目业绩、项目经验、项目经历
# 投标报价 -> 工程量报价
# 

# 目录
# 评分索引表、评分对照表、索引表 #不同评审因素对应页面


CN_NUM = {
    '〇' : 0, '一' : 1, '二' : 2, '三' : 3, '四' : 4, '五' : 5, '六' : 6, '七' : 7, '八' : 8, '九' : 9, '零' : 0,
    '壹' : 1, '贰' : 2, '叁' : 3, '肆' : 4, '伍' : 5, '陆' : 6, '柒' : 7, '捌' : 8, '玖' : 9, '貮' : 2, '两' : 2,
}

CN_UNIT = {
    '十' : 10,
    '拾' : 10,
    '百' : 100,
    '佰' : 100,
    '千' : 1000,
    '仟' : 1000,
    '万' : 10000,
    '萬' : 10000,
    '亿' : 100000000,
    '億' : 100000000,
    '兆' : 1000000000000,
}
#大写转数字
def chinese_to_arabic(cn:str) -> int:
    if len(re.findall('\d', cn)) == len(cn):
        return int(cn)
    #print(type(cn), cn)
    unit = 0   # current
    ldig = []  # digest
    for cndig in reversed(cn):
        if cndig in CN_UNIT:
            unit = CN_UNIT.get(cndig)
            if unit == 10000 or unit == 100000000:
                ldig.append(unit)
                unit = 1
        else:
            dig = CN_NUM.get(cndig)
            if unit:
                dig *= unit
                unit = 0
            ldig.append(dig)
    if unit == 10:
        ldig.append(10)
    val, tmp = 0, 0
    #print(ldig)
    for x in reversed(ldig):
        #print('x',x)
        if x == 10000 or x == 100000000:
            val += tmp * x
            tmp = 0
        else:
            tmp += x
    val += tmp
    return val

# 读取目录
# def get_directory():


# line = open('data_1.json', 'r', encoding='utf-8').read()



json_data = {"calMethod": """
当0<Di≤3%时，每高1%扣1分；
当3%<Di≤6%时，每高1%扣1.5分；
当6%<Di，每高1%扣2分；
当-3%<Di≤0时，不扣分；
当-6%<Di≤-3%时，每低1%扣0.5分；
当-9%<Di≤-6%时，每低1%扣1分；
当Di≤-9%时，每低1%扣1.5分；
满分为100分，最低得60分。""",
        "scoreWeight":"30%",
        "quoteRes": [
            {
                "proNum": "序号",
                "projectName": "资料收集及整理",
                "unit": "项",
                "quantity": "14.76",
                "suppliers": [
                    {
                        "name": "供应商A",
                        "taxRate": "13%",
                        "supplier": {
                            "finalQuote": {
                                "unitPrice": "875.00",
                                "totalPrice": "12915.00"
                            },
                            "taxCompareRes": {
                                "theoryValue": "12915.00",
                                "deviation": "0.00"
                            },
                            "finalExcludeTaxPrice": {
                                "unitPrice": "774.34",
                                "totalPrice": "11429.20"
                            }
                        }
                    },
                    {
                        "name": "供应商B",
                        "taxRate": "13%",
                        "supplier": {
                            "finalQuote": {
                                "unitPrice": "672.00",
                                "totalPrice": "9918.72"
                            },
                            "taxCompareRes": {
                                "theoryValue": "9918.72",
                                "deviation": "0.00"
                            },
                            "finalExcludeTaxPrice": {
                                "unitPrice": "594.69",
                                "totalPrice": "8777.63"
                            }
                        }
                    },
                    {
                        "name": "供应商C",
                        "taxRate": "9%",
                        "supplier": {
                            "finalQuote": {
                                "unitPrice": "800.00",
                                "totalPrice": "11808.00"
                            },
                            "taxCompareRes": {
                                "theoryValue": "11808.00",
                                "deviation": "0.00"
                            },
                            "finalExcludeTaxPrice": {
                                "unitPrice": "733.94",
                                "totalPrice": "10833.03"
                            }
                        }
                    }
                ]
            }
        ],
        "calQuoteRes": {
            "avgPrice": "3270233.96",
            "benchmarkPrice": "3270233.96",
            "suppliers": [
                {
                    "name": "供应商A",
                    "supplier": {
                        "taxIncludedTotal": "3913250.00",
                        "taxExcludedTotal": "3691745.28",
                        "deviationRate": "12.889%",
                        "score": "70.333",
                        "finalScore": "21.10"
                    }
                },
                {
                    "name": "供应商B",
                    "supplier": {
                        "taxIncludedTotal": "3534213.00",
                        "taxExcludedTotal": "3334163.21",
                        "deviationRate": "1.955%",
                        "score": "98.045",
                        "finalScore": "29.41"
                    }
                },
                {
                    "name": "供应商C",
                    "supplier": {
                        "taxIncludedTotal": "3206304.72",
                        "taxExcludedTotal": "3206304.72",
                        "deviationRate": "-1.955%",
                        "score": "100",
                        "finalScore": "30.00"
                    }
                }
            ]
        }
    }


def quote_review_result(json_data):
    score_weight = json_data['scoreWeight']
    score_weight = float(score_weight[:-1])*0.01
    # company = '12'
    total_list = []
    for i in range(len(json_data['calQuoteRes']['suppliers'])):
        total_list.append(float(json_data['calQuoteRes']['suppliers'][i]['taxExcludedTotal']))
        
    value = reference_value_count(total_list, json_data['calMethod'])
    score_json, min_score = score_dict_count(json_data['calMethod'])
    _json_cal_quote_res = {"avgPrice":"%.2f"%(float(sum(total_list))/len(total_list)), 'benchmarkPrice':"%.2f"%(value), 'suppliers':[]}
    for i in range(len(json_data['calQuoteRes']['suppliers'])):
        
        score = company_score(float(json_data['calQuoteRes']['suppliers'][i]['taxExcludedTotal']), value, score_json, min_score)
    
        # print(score, json_data['calQuoteRes']['suppliers'][i])
        
        _json_cal_quote_res['suppliers'].append({"name":json_data['calQuoteRes']['suppliers'][i]['name'], "taxIncludedTotal":json_data['calQuoteRes']['suppliers'][i]['taxIncludedTotal'], "taxExcludedTotal":json_data['calQuoteRes']['suppliers'][i]['taxExcludedTotal'],'deviationRate':"%.2f"%((float(json_data['calQuoteRes']['suppliers'][i]['taxExcludedTotal'])-value)/value*100) + '%', "score":"%.2f"%(score), "finalScore":"%.2f"%(score*score_weight)})

    print(_json_cal_quote_res)

    _json_quote_res = []
    quoteRes = json_data['quoteRes']
    for y in range(len(quoteRes)):
        _ = {"proNum":quoteRes[y]["proNum"],"projectName":quoteRes[y]["projectName"],"unit":quoteRes[y]["unit"], "quantity":quoteRes[y]["quantity"], "suppliers":[]}
        suppliers_list = []
        for x in range(len(quoteRes[y]['suppliers'])):
            supplier = {}
            supplier['name'] = quoteRes[y]['suppliers'][x]['name']
            supplier['taxRate'] = quoteRes[y]['suppliers'][x]['taxRate']
            taxRate = float(supplier['taxRate'][:-1])*0.01
            
            supplier['finalQuote'] = {}
            supplier['finalQuote']['unitPrice'] = quoteRes[y]['suppliers'][x]['finalQuote']['unitPrice']
            supplier['finalQuote']['totalPrice'] = quoteRes[y]['suppliers'][x]['finalQuote']['totalPrice']
            supplier['taxCompareRes'] = {}
            supplier['taxCompareRes']['theoryValue'] = "%.2f"%(float(quoteRes[y]['suppliers'][x]['finalQuote']['unitPrice']) * float(_['quantity']))
            supplier['taxCompareRes']['deviation'] = "%.2f"%(float(supplier['taxCompareRes']['theoryValue']) - float(quoteRes[y]['suppliers'][x]['finalQuote']['totalPrice']))
            supplier['finalExcludeTaxPrice'] = {}
            supplier['finalExcludeTaxPrice']['unitPrice'] = "%.2f"%(float(quoteRes[y]['suppliers'][x]['finalQuote']['unitPrice']) / (1+taxRate))
            supplier['finalExcludeTaxPrice']['totalPrice'] = "%.2f"%(float(supplier['finalExcludeTaxPrice']['unitPrice']) * float(_['quantity']))
            suppliers_list.append(supplier)
        _['suppliers'] = suppliers_list
        _json_quote_res.append(_)
    print(_json_quote_res)

    result_json = {}
    result_json['calMethod'] = json_data['calMethod']
    result_json['scoreWeight'] = json_data['scoreWeight']
    result_json['quoteRes'] = _json_quote_res
    result_json['calQuoteRes'] = _json_cal_quote_res

    print(result_json)
    return [result_json]


# quote_review_result(json_data)

jjj = [
    {
        "calMethod": "当0<Di≤3%时，每高1%扣1分；\n当3%<Di≤6%时，每高1%扣2分；\n当6%<Di，每高1%扣3分；\n当-3%<Di≤0时，不扣分；\n当-6%<Di≤-3%时，每低1%扣1分；\n当-9%<Di≤-6%时，每低1%扣2分；\n当Di≤-9%时，每低1%扣3分；\n满分为100分，最低得60分。\n上述计分按分段累进计算，当入围报价人评审价与评审价基准值B比例值（偏差率）处于分段计算区间内时，分段计算按内插法等比例计扣分。",
        "scoreWeight": "30%",
        "quoteRes": [
            {
                "proNum": "一",
                "projectName": "设备1",
                "unit": "m2",
                "quantity": "14.76",
                "suppliers": [
                    {
                        "name": "供应商A",
                        "taxRate": "13%",
                        "finalQuote": {
                            "unitPrice": "875.00",
                            "totalPrice": "12915.00"
                        },
                        "taxCompareRes": {
                            "theoryValue": "12915.00",
                            "deviation": "0.00"
                        },
                        "finalExcludeTaxPrice": {
                            "unitPrice": "774.34",
                            "totalPrice": "11429.20"
                        }
                    },
                    {
                        "name": "供应商B",
                        "taxRate": "13%",
                        "finalQuote": {
                            "unitPrice": "672.00",
                            "totalPrice": "9918.72"
                        },
                        "taxCompareRes": {
                            "theoryValue": "9918.72",
                            "deviation": "0.00"
                        },
                        "finalExcludeTaxPrice": {
                            "unitPrice": "594.69",
                            "totalPrice": "8777.63"
                        }
                    },
                    {
                        "name": "供应商C",
                        "taxRate": "9%",
                        "finalQuote": {
                            "unitPrice": "800.00",
                            "totalPrice": "11808.00"
                        },
                        "taxCompareRes": {
                            "theoryValue": "11808.00",
                            "deviation": "0.00"
                        },
                        "finalExcludeTaxPrice": {
                            "unitPrice": "733.94",
                            "totalPrice": "10833.03"
                        }
                    },
                    {
                        "name": "供应商D",
                        "taxRate": "9%",
                        "finalQuote": {
                            "unitPrice": "850.00",
                            "totalPrice": "12546.00"
                        },
                        "taxCompareRes": {
                            "theoryValue": "12546.00",
                            "deviation": "0.00"
                        },
                        "finalExcludeTaxPrice": {
                            "unitPrice": "773.50",
                            "totalPrice": "11416.86"
                        }
                    },
                    {
                        "name": "供应商E",
                        "taxRate": "13%",
                        "finalQuote": {
                            "unitPrice": "672.00",
                            "totalPrice": "9918.72"
                        },
                        "taxCompareRes": {
                            "theoryValue": "9918.72",
                            "deviation": "0.00"
                        },
                        "finalExcludeTaxPrice": {
                            "unitPrice": "594.69",
                            "totalPrice": "8777.63"
                        }
                    }
                ]
            },
            {
                "proNum": "二",
                "projectName": "设备2",
                "unit": "套",
                "quantity": "2",
                "suppliers": [
                    {
                        "name": "供应商A",
                        "taxRate": "13%",
                        "finalQuote": {
                            "unitPrice": "10000.00",
                            "totalPrice": "20000.00"
                        },
                        "taxCompareRes": {
                            "theoryValue": "20000.00",
                            "deviation": "0.00"
                        },
                        "finalExcludeTaxPrice": {
                            "unitPrice": "8700.00",
                            "totalPrice": "17400.00"
                        }
                    },
                    {
                        "name": "供应商B",
                        "taxRate": "13%",
                        "finalQuote": {
                            "unitPrice": "11000.00",
                            "totalPrice": "22000.00"
                        },
                        "taxCompareRes": {
                            "theoryValue": "22000.00",
                            "deviation": "0.00"
                        },
                        "finalExcludeTaxPrice": {
                            "unitPrice": "9570.00",
                            "totalPrice": "19140.00"
                        }
                    },
                    {
                        "name": "供应商C",
                        "taxRate": "9%",
                        "finalQuote": {
                            "unitPrice": "10000.00",
                            "totalPrice": "20000.00"
                        },
                        "taxCompareRes": {
                            "theoryValue": "20000.00",
                            "deviation": "0.00"
                        },
                        "finalExcludeTaxPrice": {
                            "unitPrice": "9100.00",
                            "totalPrice": "18200.00"
                        }
                    },
                    {
                        "name": "供应商D",
                        "taxRate": "9%",
                        "finalQuote": {
                            "unitPrice": "9000.00",
                            "totalPrice": "18000.00"
                        },
                        "taxCompareRes": {
                            "theoryValue": "18000.00",
                            "deviation": "0.00"
                        },
                        "finalExcludeTaxPrice": {
                            "unitPrice": "8190.00",
                            "totalPrice": "16380.00"
                        }
                    },
                    {
                        "name": "供应商E",
                        "taxRate": "13%",
                        "finalQuote": {
                            "unitPrice": "11000.00",
                            "totalPrice": "22000.00"
                        },
                        "taxCompareRes": {
                            "theoryValue": "22000.00",
                            "deviation": "0.00"
                        },
                        "finalExcludeTaxPrice": {
                            "unitPrice": "9570.00",
                            "totalPrice": "19140.00"
                        }
                    }
                ]
            }
        ],
        "calQuoteRes": {
            "avgPrice": "28393.96",
            "benchmarkPrice": "28393.96",
            "suppliers": [
                {
                    "name": "供应商A",
                    "taxIncludedTotal": "32915.00",
                    "taxExcludedTotal": "28829.20",
                    "deviationRate": "0.01533",
                    "score": "90.333",
                    "finalScore": "28.00"
                },
                {
                    "name": "供应商B",
                    "taxIncludedTotal": "31918.72",
                    "taxExcludedTotal": "27917.63",
                    "deviationRate": "-0.01677",
                    "score": "80.333",
                    "finalScore": "24.10"
                },
                {
                    "name": "供应商C",
                    "taxIncludedTotal": "31808.00",
                    "taxExcludedTotal": "29033.03",
                    "deviationRate": "0.0225",
                    "score": "70.667",
                    "finalScore": "21.10"
                },
                {
                    "name": "供应商D",
                    "taxIncludedTotal": "30546.00",
                    "taxExcludedTotal": "27796.00",
                    "deviationRate": "0.02105",
                    "score": "75.00",
                    "finalScore": "22.50"
                },
                {
                    "name": "供应商E",
                    "taxIncludedTotal": "31918.72",
                    "taxExcludedTotal": "27917.63",
                    "deviationRate": "-0.01677",
                    "score": "80.333",
                    "finalScore": "24.10"
                }
            ]
        }
    }
]

quote_review_result(jjj[0])
# 招标文件中评审方法中评审因素表


# 清标-报价部分表格抽取
# 分项报价表
# 单价  全费用综合单价
# 合价  合价
# 单位  单位
# 数量  数量、工程量、工作量
# 名称  项目名称、名称
# 报价汇总表
# 税率  增值税税率
# 总价  含税总价、含税报价
# 增值税    增值税金额、增值税额
# 不含税总价    不含税合价

# 投标文件
# table 表头，表格跨页

# 计算ocr识别文本与标准信息的相似度
def text_sim(word, black_lists):
    _json = {}
    for word_key in black_lists:
        # print(word_key.lower(), word)
        if word_key == word or word_key in word:
            return word_key
        sim_score = Levenshtein.ratio(word_key.lower(), word)
        if(sim_score > 0.9):
            return word_key
        _json[word_key] = sim_score
    datas = sorted(_json.items(), key=lambda x:x[1], reverse=True)
    # print('xx'*10, datas)
    return datas[0][0]
black_lists = ['商务部分评分标准', '技术部分评分标准', '报价评分标准']

print(text_sim('商务评分标准',black_lists))

def get_money_score(aaa, bidderUnit, key_word_list):
     
    name = ''
    # for i in range(len(json_lines['para_nodes'])):
    #     if json_lines['para_nodes'][i]['node_type'] == 'table':
    #         aaa = json_lines['para_nodes'][i]['text']
    # print(lines)
    # aaa = """|||权重|中水北方勘测公司|长江勘测公司|中国电建中南院|北桥中七|\n|商务部分评分标准(15%)|信用评价|3%|100|100|100|100|\n|商务部分评分标准(15%)|财务状况|1%|87|98|93|81|\n|商务部分评分标准(15%)|报价合理性|3%|85|94|85|84|\n|商务部分评分标准(15%)|以往类似项目业绩、经验|7%|85|95|94|82|\n|商务部分评分标准(15%)|报价文件涉密内容检查|1%|100|100|100|100|\n|报价评分标准(35%)|价格得分|35%|||||\n|技术部分评分标准(50%)|总体方案|7%|83|94|85|82|\n|技术部分评分标准(50%)|外墙设计|20%|83|95|84|0|\n|技术部分评分标准(50%)|内部设计|15%|82|93|81|0|\n|技术部分评分标准(50%)|园区设计|8%|0|94|0|0|\n|专家签字：杨明2024年3月26日|专家签字：杨明2024年3月26日|专家签字：杨明2024年3月26日|专家签字：杨明2024年3月26日|专家签字：杨明2024年3月26日|专家签字：杨明2024年3月26日|专家签字：杨明2024年3月26日|"""

    aaa_list = aaa.split('\n')

    _beg = -1
    _row_index = -1 
    for i in range(len(aaa_list)):    
        aaa_list[i] = aaa_list[i][1:-1].split('|')

    for i in range(len(aaa_list)):    
        if '权重' in aaa_list[i]:
            _row_index = aaa_list[i].index('权重')
            _beg = i
            break

    for i in range(len(aaa_list)): 
        if '权重' in aaa_list[i]:
            continue
        category = text_sim(aaa_list[i][0], key_word_list.keys())
        scoringFactors = text_sim(aaa_list[i][1], key_word_list[category].keys())
        percentage = key_word_list[category][scoringFactors]
        aaa_list[i][0] = category
        aaa_list[i][1] = scoringFactors
        aaa_list[i][2] = percentage



    # print(aaa_list)

    json_array = {}
    for j in range(_row_index+1, len(aaa_list[_beg])):
        # print(aaa_list[_beg][j])
        company = text_sim(aaa_list[_beg][j], bidderUnit)
        aaa_list[_beg][j] = company
        json_array[company] = []

    for j in range(_beg+1, len(aaa_list)):
        if '专家签字' in str(aaa_list[j]) or '专家' in str(aaa_list[j]):
            break
        for x in range(_row_index+1, len(aaa_list[_beg])):
            json_array[aaa_list[_beg][x]].append(aaa_list[j][:_row_index+1] + [aaa_list[j][x]])


    # print(json.dumps(json_array, ensure_ascii=False))
    code = 0
    ok = True
    if code != 0:
        code = 1
        ok = False
    json_data = {
        "code":code,
        "name":name,
        "msg":"",
        "data":json_array,
        "ok":ok
        }
    # print(json.dumps(json_data, ensure_ascii=False))
    return json_data

aaa = """|||权重|中水北方勘测公司|长江勘测公司|中国电建中南院|北桥中七|\n|商务部分评分标准(15%)|信用评价|3%|100|100|100|100|\n|商务部分评分标准(15%)|财务状兄|1%|87|98|93|81|\n|商务部分评分标准(15%)|报价合理性|3%|85|94|85|84|\n|商务部分评分标准(15%)|以往类似项目业绩、经验|7%|85|95|94|82|\n|商务部分评分标准(15%)|报价文件涉密内容检查|1%|100|100|100|100|\n|报价评分标准(35%)|价格得分|35%|||||\n|技术部分评分标准(50%)|总体方案|7%|83|94|85|82|\n|技术部分评分标准(50%)|外墙设计|20%|83|95|84|0|\n|技术部分评分标准(50%)|内部设计|15%|82|93|81|0|\n|技术部分评分标准(50%)|园区设计|8%|0|94|0|0|\n|专家签字：杨明2024年3月26日|专家签字：杨明2024年3月26日|专家签字：杨明2024年3月26日|专家签字：杨明2024年3月26日|专家签字：杨明2024年3月26日|专家签字：杨明2024年3月26日|专家签字：杨明2024年3月26日|"""

aaa1 = """|||权重|中水北方勘测公司|长江勘测公司|中国电建中南院|北桥中七|\n|商务部分评分标准(15%)|信用评价|3%|93|93|93|93|\n|商务部分评分标准(15%)|财务状况|1%|88|88|88|88|\n|商务部分评分标准(15%)|报价合理性|3%|88|99|88|99|\n|商务部分评分标准(15%)|以往类似项目业绩、经验|7%|97|94|83|86|\n|商务部分评分标准(15%)|报价文件涉密内容检查|1%|104|103|101|102|\n|报价评分标准(35%)|价格得分|35%|||||\n|技术部分评分标准(50%)|总体方案|7%|71|93|65|77|\n|技术部分评分标准(50%)|外墙设计|20%|88|55|88|20|\n|技术部分评分标准(50%)|内部设计|15%|80|90|80|10|\n|技术部分评分标准(50%)|园区设计|8%|10|194|20|30|\n|专家签字：杨明2024年3月26日|专家签字：杨明2024年3月26日|专家签字：杨明2024年3月26日|专家签字：杨明2024年3月26日|专家签字：杨明2024年3月26日|专家签字：杨明2024年3月26日|专家签字：杨明2024年3月26日|"""

aaa2 = """|||权重|中水北方勘测公司|长江勘测公司|中国电建中南院|苏州派维斯|\n|商务部分评分标准(15%)|信用评价|3%|91|93|95|97|\n|商务部分评分标准(15%)|财务状况|1%|89|90|91|92|\n|商务部分评分标准(15%)|报价合理性|3%|88|99|88|99|\n|商务部分评分标准(15%)|以往类似项目业绩、经验|7%|87|94|63|56|\n|商务部分评分标准(15%)|报价文件涉密内容检查|1%|114|113|111|112|\n|报价评分标准(35%)|价格得分|35%|||||\n|技术部分评分标准(50%)|总体方案|7%|72|97|68|78|\n|技术部分评分标准(50%)|外墙设计|20%|88|57|88|30|\n|技术部分评分标准(50%)|内部设计|15%|88|99|83|20|\n|技术部分评分标准(50%)|园区设计|8%|09|11|22|33|\n|专家签字：杨明2024年3月26日|专家签字：杨明2024年3月26日|专家签字：杨明2024年3月26日|专家签字：杨明2024年3月26日|专家签字：杨明2024年3月26日|专家签字：杨明2024年3月26日|专家签字：杨明2024年3月26日|"""

quoteCheck = [
    {   "name":"商务部分评分标准",
        "businessScoringCriteria": [
            {
                "scoringFactors": "信用评价",
                "scoringStandard ": "与营业执照（法人证书）一致",
                "percentage": "3%",
                "expertAdvice": "专家意见",
                "suppliers": [
                    {
                        "name": "供应商A",
                        "supplier": "供应商A的算法输出结果..."
                    },
                    {
                        "name": "供应商B",
                        "supplier": "供应商B的算法输出结果..."
                    },
                    {
                        "name": "供应商C",
                        "supplier": "供应商C的算法输出结果..."
                    }
                ]
            },
            {
                "scoringFactors": "财务状况",
                "scoringStandard ": "与营业执照（法人证书）一致",
                "percentage": "3%"
            },
            {
                "scoringFactors": "报价合理性",
                "scoringStandard ": "与营业执照（法人证书）一致",
                "percentage": "3%"
            },
            {
                "scoringFactors": "以往类似项目业绩、经验",
                "scoringStandard ": "与营业执照（法人证书）一致",
                "percentage": "3%"
            },
            {
                "scoringFactors": "报价文件涉密内容检查",
                "scoringStandard ": "与营业执照（法人证书）一致",
                "percentage": "3%"
            }
        ]
    },    
    {   "name":"报价评分标准",
        "quoteScoringCriteria": [
            {
                "scoringFactors": "价格得分",
                "scoringStandard ": "当0<Di≤3%时，每高1%扣1分；",
                "percentage": "35%",
                "expertAdvice": "专家意见",
                "suppliers": [
                    {
                        "name": "供应商A",
                        "supplier": "供应商A的算法输出结果..."
                    },
                    {
                        "name": "供应商B",
                        "supplier": "供应商B的算法输出结果..."
                    },
                    {
                        "name": "供应商C",
                        "supplier": "供应商C的算法输出结果..."
                    }
                ]
            }
        ]
    },
    {"name":"技术部分评分标准",
        "techPartScoringCriteria": [
            {
                "scoringFactors": "总体方案",
                "scoringStandard ": "对报价人提供的总体服务方案的全面性...",
                "percentage": "7%"                
            },
            {
                "scoringFactors": "外墙设计",
                "scoringStandard ": "与营业执照（法人证书）一致",
                "percentage": "20%"
            },
            {
                "scoringFactors": "内部设计",
                "scoringStandard ": "与营业执照（法人证书）一致",
                "percentage": "15%"
            },
            {
                "scoringFactors": "园区设计",
                "scoringStandard ": "与营业执照（法人证书）一致",
                "percentage": "8%"
            }
        ]
    }
]
bidderUnit = ["中水北方勘测公司", "长江勘测公司", "中国电建中南院", "北桥中七", "苏州派维斯科技有限公司"]

def quote_check_score(quoteCheck=quoteCheck, bidderUnit=bidderUnit):
    # 获取输入的quoteCheck的内容，不同模块的评审因素字段
    key_word_list = {}
    for y in range(len(quoteCheck)):
        name = quoteCheck[y]['name']
        if name == '商务部分评分标准':
            key = 'businessScoringCriteria'
        elif name == '报价评分标准':
            key = 'quoteScoringCriteria'
        elif name == '技术部分评分标准':
            key = 'techPartScoringCriteria'
        key_word_list[name] = {}
        for j in range(len(quoteCheck[y][key])):
            key_word_list[name][quoteCheck[y][key][j]['scoringFactors']] = quoteCheck[y][key][j]['percentage']
    print(key_word_list)


    json_data = get_money_score(aaa, bidderUnit, key_word_list)
    json_data['name'] = '张三'
    json_data_1 = get_money_score(aaa1, bidderUnit, key_word_list)
    json_data_1['name'] = '李四'
    json_data_2 = get_money_score(aaa2, bidderUnit, key_word_list)
    json_data_2['name'] = '王五1'
    print(json_data)

    json_array = [json_data, json_data_1, json_data_2]
    name_list = []
    for i in range(len(json_array)):
        name_list.append(json_array[i]['name'])
    result_json = {"detail":[{"category": "商务部分评分标准","factorsList":[]}, {"category": "报价评分标准","factorsList":[]}, {"category": "技术部分评分标准","factorsList":[]}]}
    for i in range(len(json_array)):
        json_data = json_array[i]
        name = json_data['name']
        for k in json_data['data']:
            company = k
            data = json_data['data'][k]
            category = ''
            json_list = []
            _beg = -1
            for y in data:
                if category != y[0]:
                    category = y[0]            
                    for j in range(len(result_json["detail"])):
                        if result_json["detail"][j]['category'] == category or result_json["detail"][j]['category'] in category:
                            _beg = j
                            break
                # print(company, name, y)
                scoringFactors = y[1]
                percentage = y[2] # 占比
                score = y[3]  #得分 
                try:
                    result_json["detail"][_beg]["factorsList"][0]
                except:
                    result_json["detail"][_beg]["factorsList"].append({"scoringFactors":scoringFactors, "percentage":percentage,"suppliers":[]})
                _sed_beg = -1
                for xx in range(len(result_json["detail"][_beg]['factorsList'])):
                    if result_json["detail"][_beg]['factorsList'][xx]['scoringFactors'] == scoringFactors or result_json["detail"][_beg]['factorsList'][xx]['scoringFactors'] in scoringFactors:
                        _sed_beg = xx
                        break
                
                if _sed_beg == -1:
                    result_json["detail"][_beg]["factorsList"].append({"scoringFactors":scoringFactors, "percentage":percentage,"suppliers":[]})
                    _sed_beg = len(result_json["detail"][_beg]["factorsList"]) - 1
                suppliers_beg = -1
                for xx in range(len(result_json["detail"][_beg]['factorsList'][_sed_beg]['suppliers'])):
                    if result_json["detail"][_beg]['factorsList'][_sed_beg]['suppliers'][xx]["name"] == company or company in result_json["detail"][_beg]['factorsList'][_sed_beg]['suppliers'][xx]["name"] :
                        suppliers_beg = xx
                        break
                if suppliers_beg == -1:
                    result_json["detail"][_beg]['factorsList'][_sed_beg]['suppliers'].append({"name":company,"grade":"", "scores":[],"avgScore":"","percentScore":''})
                    suppliers_beg = len(result_json["detail"][_beg]['factorsList'][_sed_beg]['suppliers']) - 1
                    for j in range(len(name_list)):
                        result_json["detail"][_beg]['factorsList'][_sed_beg]['suppliers'][suppliers_beg]['scores'].append({"name":name_list[j], "score":""})
                name_beg = -1
                for xx in range(len(result_json["detail"][_beg]['factorsList'][_sed_beg]['suppliers'][suppliers_beg]['scores'])):
                    if result_json["detail"][_beg]['factorsList'][_sed_beg]['suppliers'][suppliers_beg]['scores'][xx]["name"] == name:
                        result_json["detail"][_beg]['factorsList'][_sed_beg]['suppliers'][suppliers_beg]['scores'][xx]["score"] = score
                        name_beg = xx
                        break
                # print(company, name, y, _sed_beg, suppliers_beg, name_beg)
        
        # print(result_json)

    _json = {'code':0, 'ok':True, 'data':result_json, 'msg':'成功'}
    print(json.dumps(_json, ensure_ascii=False))
    return  result_json


