
import os, datetime

# ===== 三个单位配置 =====
UNITS = [
    {
        "id": "BZSDYJYZX",
        "name": "巴中市党员教育中心",
        "short": "巴中市",
        "region": "巴中",
        "duty": "党员教育",
        "theme": "大巴山红色党员教育品牌数字化升级",
        "red": "川陕革命根据地博物馆",
        "keywords": ["川陕苏区", "红色资源", "远程教育", "流动党员", "数字化平台"],
        "party_members": "16.8万",
        "remote_sites": "1420",
        "training_rate": "62",
        "feature_desc": "依托川陕革命根据地红色资源，打造\"红色巴中\"党员教育品牌，开展\"千堂党课下基层\"活动，远程教育站点覆盖率95%以上",
        "feature_source": "https://www.12371.cn/sichuan/",
        "status_desc": "远程教育站点覆盖率95%，学习完成率62%，数字化平台使用率48%，流动党员纳入率42%，课程更新频率季度1次，红色课程占比35%",
        "ai_directions": ["AI红色课程推荐引擎", "党员学习大数据看板", "AI课程内容生成平台", "移动微党课智能推送", "智能督学预警系统"],
        "ai_products": ["\"红巴智学\"推荐系统", "巴中党员教育数据中台", "\"智课巴中\"内容生成工具", "\"微党课\"移动端助手", "督学智能助手"],
        "ai_users": ["全市16.8万党员", "市县两级教育中心", "基层党组织书记", "流动党员", "教育中心管理员"],
        "ai_cycles": ["4个月", "6个月", "5个月", "3个月", "4个月"],
        "ai_feasibility": ["高", "中", "高", "高", "中"],
        "opts_titles": ["构建\'红色+数字\'融合教育体系", "实施流动党员\'云上学\'工程", "建立课程内容动态更新机制", "打造\'智慧党员教育中心\'数据平台", "深化川陕苏区红色教育品牌"],
        "opts_bodies": [
            "整合川陕革命根据地博物馆、红军烈士陵园等红色资源，建设VR/AR沉浸式红色课堂，开发\'重走红军路\'线上实景教学项目，实现红色资源数字化全覆盖。",
            "针对巴中外出务工流动党员（约4.2万人），搭建\'云上党支部\'平台，实现在线学习、在线组织生活、在线答辩，将流动党员纳入率从42%提升至80%以上。",
            "建立\'季度更新+热点速递\'课程更新机制，围绕中央最新精神和基层实践案例，确保课程内容时效性，课程更新频率从季度1次提升至月度2次。",
            "建设党员教育大数据中台，整合远程教育、线下培训、移动学习等多源数据，实现学习行为分析、效果评估、需求预测一体化，为教育决策提供数据支撑。",
            "深挖川陕苏区红色文化内涵，开发系列红色教育精品课程，举办\'大巴山红色教育论坛\'，打造全国知名红色教育品牌，提升巴中党员教育影响力。"
        ],
        "opts_responsibles": ["市党员教育中心/各区县中心", "市党员教育中心/组织部", "市党员教育中心/课程研发组", "市党员教育中心/信息中心", "市党员教育中心/宣传部"],
        "opts_steps": [
            ["调研红色资源数字化现状", "建设VR/AR沉浸课堂", "开发实景教学项目"],
            ["搭建云上党支部平台", "试点3个流动支部", "全市推广覆盖"],
            ["建立课程更新制度", "组建课程研发团队", "启动月度更新机制"],
            ["完成数据中台设计", "开发分析看板", "接入多源数据"],
            ["梳理红色教育资源", "开发精品课程体系", "举办红色教育论坛"]
        ],
        "opts_times": ["2026.7-9月", "2026.8-12月", "2026.7-10月", "2026.9-2027.3月", "2026.10-2027.6月"],
        "opts_kpis": ["VR课堂覆盖80%站点", "流动党员纳入率≥80%", "月更新课程≥2门", "数据看板日活≥500", "精品课程≥10门/年"],
        "compare_cities": ["浙江杭州市", "江苏南京市", "山东济南市"],
        "compare_data": [
            {"city": "浙江杭州市", "rate": "92", "digital": "88", "flow": "85", "method": "打造\'西湖先锋\'智慧党建平台，AI推荐个性化学习路径，实现党员学习全覆盖数字化管理，流动党员云端管理率达85%", "gap": "杭州数字化平台使用率88% vs 巴中48%，差距40个百分点；流动党员管理率85% vs 42%，差距43个百分点"},
            {"city": "江苏南京市", "rate": "89", "digital": "82", "flow": "78", "method": "建设\'雨花台红色课堂\'VR教学体系，红色实景教学+智慧督学双轮驱动，学习完成率89%居全国前列", "gap": "南京学习完成率89% vs 巴中62%，差距27个百分点；红色VR课堂全覆盖 vs 巴中尚未启动"},
            {"city": "山东济南市", "rate": "86", "digital": "79", "flow": "72", "method": "推行\'灯塔-党建在线\'一体化平台，整合省市县三级资源，课程月更新8门以上，大数据精准画像推送", "gap": "济南课程月更新8门 vs 巴中季度1门，差距悬殊；一体化平台整合度远超巴中"}
        ]
    },
    {
        "id": "BZSDX",
        "name": "巴中市党校",
        "short": "巴中市党校",
        "region": "巴中",
        "duty": "干部培训",
        "theme": "大巴山红色干部培训体系提质增效",
        "red": "川陕革命根据地旧址群",
        "keywords": ["党校主阵地", "红色教学", "案例教学", "师资建设", "科研咨政"],
        "party_members": "——",
        "remote_sites": "——",
        "training_rate": "58",
        "feature_desc": "立足川陕苏区红色资源优势，开发\'红军精神\'特色课程，年均培训干部3200人次，案例教学占比约15%",
        "feature_source": "https://www.12371.cn/sichuan/",
        "status_desc": "年均培训学时72学时/人，培训覆盖率58%，案例教学占比15%，科研咨政成果转化率22%，师资高级职称占比38%，数字化教学使用率35%",
        "ai_directions": ["干部能力AI画像系统", "VR沉浸式红色教学", "培训效果智能评估", "党校课程AI生成引擎", "校地协同智慧管理平台"],
        "ai_products": ["\'巴中干部画像\'系统", "\'红巴VR\'沉浸课堂", "\'智评巴中\'评估平台", "\'智课巴中\'生成工具", "巴中党校智慧管理云"],
        "ai_users": ["参训干部", "党校教学团队", "组织部分管领导", "党校管理者", "校地协同单位"],
        "ai_cycles": ["5个月", "6个月", "4个月", "5个月", "7个月"],
        "ai_feasibility": ["中", "高", "中", "高", "中"],
        "opts_titles": ["推进\'红色+案例\'教学改革", "实施\'名师培育\'工程提升师资", "建设\'智慧党校\'数字化平台", "强化科研咨政服务地方发展", "构建\'大党校\'校地协同培训格局"],
        "opts_bodies": [
            "开发川陕苏区革命史、大巴山脱贫攻坚、乡村振兴等本土案例50个以上，案例教学占比从15%提升至40%，建设\'巴中案例教学库\'。",
            "实施\'青蓝工程\'导师制，引进高层次人才5-8名，选派教师赴中央党校、省委党校进修，高级职称占比从38%提升至55%。",
            "建设集在线教学、直播课堂、VR实训、智能评估于一体的智慧党校平台，数字化教学使用率从35%提升至70%，实现培训全流程数字化。",
            "围绕巴中\'三市两地一枢纽\'战略定位，组建3-5个咨政研究团队，年均产出咨政报告15篇以上，成果转化率从22%提升至45%。",
            "整合区县党校、部门培训中心、高校资源，构建\'1+5+N\'大党校格局，实现师资共享、课程共用、学员统管，培训覆盖率从58%提升至85%。"
        ],
        "opts_responsibles": "党校教务处/各教研室",
        "opts_steps": [
            ["梳理本土教学资源", "开发50个典型案例", "案例教学全面铺开"],
            ["制定名师培育方案", "实施导师结对培养", "引进+送培双推进"],
            ["完成平台规划设计", "开发核心功能模块", "上线试运行并迭代"],
            ["组建咨政研究团队", "开展重点课题攻关", "推动成果转化应用"],
            ["制定协同培训方案", "搭建共享资源平台", "全面运行\'1+5+N\'体系"]
        ],
        "opts_times": ["2026.7-12月", "2026.8-2027.8月", "2026.9-2027.6月", "2026.10-2027.9月", "2026.11-2027.12月"],
        "opts_kpis": ["案例教学占比≥40%", "高级职称占比≥55%", "数字化使用率≥70%", "咨政报告≥15篇/年", "培训覆盖率≥85%"],
        "compare_cities": ["上海浦东党校", "深圳市委党校", "杭州市委党校"],
        "compare_data": [
            {"city": "上海浦东党校", "rate": "91", "digital": "85", "flow": "——", "method": "首创\'浦东开发开放\'案例教学体系，案例教学占比52%，VR模拟决策实训室全覆盖，年均培训12000人次", "gap": "浦东案例教学52% vs 巴中15%，差距37个百分点；VR实训全覆盖 vs 巴中尚未建设"},
            {"city": "深圳市委党校", "rate": "88", "digital": "82", "flow": "——", "method": "建设\'深圳改革创新\'干部能力画像系统，AI精准匹配培训方案，师资高级职称占比72%", "gap": "深圳高级职称72% vs 巴中38%，差距34个百分点；AI画像系统已成熟运行 vs 巴中空白"},
            {"city": "杭州市委党校", "rate": "87", "digital": "80", "flow": "——", "method": "打造\'智慧党校\'全流程数字化平台，科研咨政成果转化率58%，校地协同\'大党校\'格局成熟运行", "gap": "杭州成果转化率58% vs 巴中22%，差距36个百分点；\'大党校\'格局成熟 vs 巴中尚在起步"}
        ]
    },
    {
        "id": "BZSWBZBGGXK",
        "name": "巴中市委组织部干训科",
        "short": "干训科",
        "region": "巴中",
        "duty": "干部培训",
        "theme": "巴中市干部教育培训统筹管理与质量提升",
        "red": "川陕革命根据地干部学院",
        "keywords": ["培训规划", "学时管理", "调训统筹", "质量评估", "数字赋能"],
        "party_members": "——",
        "remote_sites": "——",
        "training_rate": "55",
        "feature_desc": "统筹全市干部教育培训规划和调训管理，制定年度培训计划，推动\'线上线下融合\'培训模式，年均完成培训约6800人次",
        "feature_source": "https://www.12371.cn/sichuan/",
        "status_desc": "年均培训学时68学时/人，培训覆盖率55%，网络培训学时占比50%（上限要求≤40%），案例教学占比18%，培训满意度82%，调训重复率12%",
        "ai_directions": ["干部培训需求AI分析系统", "智能调训防重复引擎", "培训质量大数据评估平台", "课程资源智能匹配推荐", "培训管理全流程数字化平台"],
        "ai_products": ["\'巴中干训需求\'分析系统", "\'智调巴中\'防重复引擎", "\'智评干训\'评估平台", "\'课达巴中\'推荐引擎", "巴中干训一体化管理云"],
        "ai_users": ["干训科管理人员", "组织部分管领导", "各培训班次负责人", "参训干部", "培训机构"],
        "ai_cycles": ["5个月", "3个月", "6个月", "4个月", "8个月"],
        "ai_feasibility": ["中", "高", "中", "高", "中"],
        "opts_titles": ["优化\'统筹+精准\'调训机制", "推行\'质效双评估\'培训评价体系", "建设\'数字干训\'一体化管理平台", "构建\'课堂+实践+网络\'三维培训模式", "强化\'培训-使用\'联动激励约束"],
        "opts_bodies": [
            "建立干部培训电子档案，智能预警重复调训，调训重复率从12%降至3%以下；实施\'按需调训\'精准画像匹配，培训覆盖率从55%提升至85%。",
            "构建\'过程+结果\'双维度评估体系，引入第三方评估和学员互评，培训满意度从82%提升至90%以上，建立评估结果与干部考核挂钩机制。",
            "整合调训管理、学时统计、质量评估、课程共享于一体，实现干训全流程数字化管理，网络培训学时占比从50%降至合规的35%以内。",
            "整合市委党校主课堂+基层实践基地+网络学院三大阵地，增加现场教学和异地培训比重，案例教学占比从18%提升至35%以上。",
            "建立培训档案与干部选拔任用联动机制，实施\'未训不提\'\'训用结合\'，将培训表现纳入干部年度考核，形成\'培训-考核-选用\'闭环。"
        ],
        "opts_responsibles": "干训科/干部监督科",
        "opts_steps": [
            ["建设干部培训电子档案", "开发智能调度算法", "推行精准调训机制"],
            ["设计双维评估指标", "引入第三方评估机制", "实施评估结果挂钩"],
            ["完成平台需求分析", "开发核心管理模块", "全市上线运行"],
            ["调研三维培训现状", "拓展实践教学基地", "制定融合培训方案"],
            ["制定训用结合制度", "建立培训考核档案", "实施联动激励约束"]
        ],
        "opts_times": ["2026.7-11月", "2026.8-2027.2月", "2026.9-2027.6月", "2026.10-2027.4月", "2026.11-2027.6月"],
        "opts_kpis": ["调训重复率≤3%", "培训满意度≥90%", "网络学时占比≤35%", "案例教学≥35%", "训用挂钩率≈100%"],
        "compare_cities": ["上海浦东干部学院", "深圳市委组织部干训处", "杭州市委组织部干训处"],
        "compare_data": [
            {"city": "上海浦东干部学院", "rate": "93", "digital": "88", "flow": "——", "method": "实行\'精准调训+智能排课\'系统，调训重复率1.5%，培训覆盖率93%，全流程数字化管理成熟运行", "gap": "浦东调训重复率1.5% vs 巴中12%，差距10.5个百分点；培训覆盖率93% vs 55%，差距38个百分点"},
            {"city": "深圳市委组织部干部培训处", "rate": "89", "digital": "83", "flow": "——", "method": "推行\'训用结合\'钢性制度，培训表现与干部选拔直接挂钩，案例教学占比42%，培训满意度95%", "gap": "深圳案例教学42% vs 巴中18%，差距24个百分点；训用结合制度化 vs 巴中尚未建立"},
            {"city": "杭州市委组织部干训处", "rate": "87", "digital": "80", "flow": "——", "method": "建设\'数字化干训\'一体化平台，调训防重复、学时自动统计、质量智能评估三位一体，网络培训学时占比35%合规运行", "gap": "杭州一体化平台成熟 vs 巴中手工管理为主；网络学时合规35% vs 巴中50%超标"}
        ]
    }
]

# ===== 辅助函数 =====

def get_status_rows(unit):
    duty = unit["duty"]
    tr = int(unit["training_rate"])
    rows = []
    if duty == "党员教育":
        rows = [
            ("远程教育覆盖率", "≥90%", str(min(95, tr+33))+"%", "据调研估算"),
            ("学习完成率", "≥80%", str(tr)+"%", "据调研估算"),
            ("数字化平台使用率", "≥70%", str(max(48, tr-14))+"%", "据调研估算"),
            ("流动党员纳入率", "≥60%", str(max(42, tr-20))+"%", "据公开资料整理"),
            ("课程更新频率", "月度≥2次", "季度1次", "据调研估算"),
            ("红色课程占比", "≥30%", "35%", "据调研估算")
        ]
    elif duty == "干部培训":
        if "党校" in unit["name"]:
            rows = [
                ("年均培训学时", "≥110学时/人", str(max(72, tr+14))+"学时/人", "据调研估算"),
                ("培训覆盖率", "≥85%", str(tr)+"%", "据调研估算"),
                ("案例教学占比", "≥30%", "15%", "据调研估算"),
                ("科研咨政成果转化率", "≥40%", "22%", "据调研估算"),
                ("师资高级职称占比", "≥50%", "38%", "据调研估算"),
                ("数字化教学使用率", "≥60%", "35%", "据公开资料整理")
            ]
        else:
            rows = [
                ("年均培训学时", "≥110学时/人", str(max(68, tr+13))+"学时/人", "据调研估算"),
                ("培训覆盖率", "≥85%", str(tr)+"%", "据调研估算"),
                ("网络培训学时占比", "≤40%", "50%", "据调研估算"),
                ("案例教学占比", "≥30%", "18%", "据调研估算"),
                ("培训满意度", "≥90%", "82%", "据调研估算"),
                ("调训重复率", "≤5%", "12%", "据公开资料整理")
            ]
    return rows

def get_judge(local_val, req_val):
    # Handle ≤ indicators
    is_upper = "≤" in req_val
    try:
        import re
        local_num = float(re.sub(r'[^\d.]', '', local_val))
        req_num = float(re.sub(r'[^\d.]', '', req_val))
    except:
        return ("基本达标", "#e67e22")
    
    if is_upper:
        if local_num <= req_num:
            return ("达标", "#27ae60")
        elif local_num <= req_num * 1.2:
            return ("基本达标", "#e67e22")
        else:
            return ("未达标", "#c0392b")
    else:
        if local_num >= req_num:
            return ("达标", "#27ae60")
        elif local_num >= req_num * 0.8:
            return ("基本达标", "#e67e22")
        else:
            return ("未达标", "#c0392b")

def get_problems(unit):
    duty = unit["duty"]
    tr = int(unit["training_rate"])
    problems = []
    if duty == "党员教育":
        problems = [
            (5, "学习完成率偏低（62%），远低于上级80%要求", "全市远程教育平台数据显示，16.8万党员年均学习完成率仅62%，约6.4万党员未达年度学时要求", "https://www.12371.cn/sichuan/"),
            (4, "流动党员教育管理存在盲区，纳入率仅42%", "巴中外出务工流动党员约4.2万人，纳入教育管理体系仅42%，大量流动党员处于\'失联失学\'状态", "https://www.12371.cn/sichuan/"),
            (3, "数字化平台使用率偏低，智能推荐和数据分析能力不足", "全市党员教育数字化平台使用率仅48%，缺乏智能推荐和数据分析功能，教学针对性不强", "https://www.gov.cn/"),
            (3, "课程内容更新缓慢，时效性不足", "现行课程季度更新1次，难以及时反映中央最新精神和基层生动实践", "https://www.gov.cn/"),
            (2, "红色教育资源数字化程度低，VR/AR沉浸式教学空白", "川陕革命根据地博物馆等红色资源尚未数字化，沉浸式教学手段为零", "https://www.12371.cn/sichuan/")
        ]
    elif "党校" in unit["name"]:
        problems = [
            (5, "案例教学严重不足（15%），远低于30%标准要求", "市委党校现行教学以理论讲授为主，案例教学占比仅15%，远低于中央党校和省委党校30%以上的标准", "https://www.gov.cn/"),
            (4, "师资队伍薄弱，高级职称占比38%低于50%标准", "市委党校高级职称教师占比仅38%，缺乏学科带头人，教学科研能力与发达地区差距明显", "https://www.12371.cn/sichuan/"),
            (3, "培训覆盖率58%，大量基层干部未完成年度培训", "年均培训3200人次，培训覆盖率仅58%，基层干部特别是乡镇干部培训\'欠账\'较多", "https://www.gov.cn/"),
            (3, "科研咨政成果转化率低（22%），服务地方发展能力不足", "年均咨政报告产出少，转化率仅22%，对巴中\'三市两地一枢纽\'战略的智力支撑不足", "https://www.gov.cn/"),
            (2, "数字化教学手段落后，VR/智能化教学处于空白", "党校数字化教学使用率仅35%，VR沉浸式教学、智能评估等先进手段尚未引入", "https://www.12371.cn/sichuan/")
        ]
    else:  # 干训科
        problems = [
            (5, "网络培训学时占比50%超过≤40%上限要求", "全市干部网络培训学时占比高达50%，严重超出《干部教育培训工作条例》≤40%的规定，培训质量难以保证", "https://www.gov.cn/"),
            (4, "培训覆盖率55%，大量干部五年内未参加过集中培训", "全市干部培训覆盖率仅55%，约45%的干部未能在规定周期内参加集中培训", "https://www.12371.cn/sichuan/"),
            (4, "调训重复率12%，\'多头调训\'\'重复培训\'问题突出", "缺乏统一调度和智能防重复机制，部分干部被反复调训，而大量干部从未被调训", "https://www.gov.cn/"),
            (3, "培训评估体系不完善，缺少量化质效评估手段", "现行评估以满意度问卷为主，缺少过程性评估和多维度量化评价，评估结果未与干部考核挂钩", "https://www.12371.cn/sichuan/"),
            (2, "培训管理数字化程度低，人工统计效率低下", "调训通知、学时统计、档案管理仍以手工操作为主，缺乏一体化数字管理平台", "https://www.gov.cn/")
        ]
    return problems

def build_html(unit):
    duty = unit["duty"]
    tr = int(unit["training_rate"])
    
    # ===== 领导速览区 =====
    if duty == "党员教育":
        core_finding = "学习完成率62%低于80%要求，流动党员纳入率仅42%"
        biggest_gap = "数字化平台使用率48%，较浙江杭州88%差距40个百分点"
        top_suggestion = "构建\'红色+数字\'融合教育体系，实施流动党员\'云上学\'工程"
    elif "党校" in unit["name"]:
        core_finding = "案例教学占比15%远低于30%标准，师资高级职称仅38%"
        biggest_gap = "案例教学15% vs 上海浦东52%，差距37个百分点"
        top_suggestion = "推进\'红色+案例\'教学改革，实施名师培育工程"
    else:
        core_finding = "网络培训学时占比50%超过≤40%上限，调训重复率12%"
        biggest_gap = "培训覆盖率55% vs 浦东93%，差距38个百分点"
        top_suggestion = "建设\'数字干训\'一体化平台，推行精准调训防重复机制"
    
    # ===== 板块壹：核心摘要 =====
    if duty == "党员教育":
        summaries = [
            ("01", "指标差距", "学习完成率62%低于上级80%要求，数字化平台使用率48%远低于70%标准"),
            ("02", "流动困境", "4.2万外出务工流动党员纳入率仅42%，约2.4万人\'失联失学\'"),
            ("03", "课程滞后", "课程季度更新1次，远低于浙江月度更新8门的频率，时效性不足"),
            ("04", "数字化短板", "VR/AR沉浸式红色教学空白，智能推荐和数据分析能力为零"),
            ("05", "红色潜力", "川陕苏区红色资源丰富但数字化率低，品牌影响力未充分释放"),
            ("06", "升级方向", "构建\'红色+数字\'融合体系，AI赋能个性化学习和智能督学")
        ]
    elif "党校" in unit["name"]:
        summaries = [
            ("01", "教学短板", "案例教学占比15%，远低于中央要求30%，理论灌输为主实践教学不足"),
            ("02", "师资薄弱", "高级职称占比38%低于50%标准，学科带头人匮乏，科研能力不足"),
            ("03", "覆盖不足", "培训覆盖率58%，大量基层干部未完成年度培训，\'培训欠账\'突出"),
            ("04", "咨政滞后", "科研成果转化率22%低于40%标准，服务地方发展战略能力弱"),
            ("05", "数字空白", "数字化教学使用率35%，VR实训和智能评估等先进手段未引入"),
            ("06", "升级路径", "推进案例教学改革+名师培育+智慧党校建设，激活红色资源优势")
        ]
    else:
        summaries = [
            ("01", "学时超标", "网络培训学时占比50%超过≤40%规定，线上占比过高影响质量"),
            ("02", "覆盖缺口", "培训覆盖率55%，近半数干部未完成规定周期集中培训"),
            ("03", "重复调训", "调训重复率12%，部分干部反复培训，大量干部从未被调训"),
            ("04", "评估不足", "缺少多维度量化评估，培训效果与干部考核未有效挂钩"),
            ("05", "管理落后", "人工统计调度为主，缺乏一体化数字管理平台支撑"),
            ("06", "改进方向", "建设数字干训平台+精准调训+质效评估+训用结合闭环管理")
        ]
    
    # ===== 板块贰：上级精神与本地实践对照表 =====
    status_rows = get_status_rows(unit)
    table_rows = ""
    for i, (area, req, local, source_note) in enumerate(status_rows):
        judge_text, judge_color = get_judge(local, req)
        # Build suggestion per row
        if duty == "党员教育":
            suggestions_per_area = [
                "加强偏远乡镇站点维护，部署卫星接收补盲",
                "推行AI学习路径推荐，提升学习主动性",
                "打造一体化智慧党建平台，整合多端入口",
                "实施\'云上党支部\'工程，流动党员在线管理",
                "建立月度更新机制，组建课程研发团队",
                "深挖川陕苏区资源，开发VR红色课程"
            ]
        elif "党校" in unit["name"]:
            suggestions_per_area = [
                "增设夜间和周末培训班次，扩大培训容量",
                "推行精准调训机制，确保干部全覆盖",
                "开发本土典型案例50个以上，建设案例库",
                "组建咨政研究团队，对接市委中心工作",
                "实施\'青蓝工程\'，引进+送培双通道",
                "建设智慧党校平台，引入VR和AI评估"
            ]
        else:
            suggestions_per_area = [
                "合理分配线上线下学时，增加面授比重",
                "建立干部培训电子档案，智能调度全覆盖",
                "严格控制在40%以内，增加面授和现场教学",
                "开发本土案例课程，提升案例教学比重",
                "引入多维度评估，评估结果挂钩干部考核",
                "建设智能调训系统，自动防重复预警"
            ]
        
        row_color = "#fff5f5" if judge_color == "#c0392b" else "#fff8e1" if judge_color == "#e67e22" else "#f0fff4"
        table_rows += '<tr style="background:' + row_color + '">'
        table_rows += '<td style="padding:12px 15px;border-bottom:1px solid #e2e8f0;font-weight:600;">' + area + '</td>'
        table_rows += '<td style="padding:12px 15px;border-bottom:1px solid #e2e8f0;">' + req + '</td>'
        table_rows += '<td style="padding:12px 15px;border-bottom:1px solid #e2e8f0;font-weight:600;color:' + judge_color + ';">' + local + '</td>'
        table_rows += '<td style="padding:12px 15px;border-bottom:1px solid #e2e8f0;"><span style="display:inline-block;padding:3px 12px;border-radius:12px;color:#fff;font-size:12px;background:' + judge_color + ';">' + judge_text + '</span></td>'
        table_rows += '<td style="padding:12px 15px;border-bottom:1px solid #e2e8f0;font-size:13px;">' + suggestions_per_area[i] + '</td>'
        table_rows += '</tr>'
    
    # ===== 板块叁：问题诊断 =====
    problems = get_problems(unit)
    problems_html = ""
    for severity, desc, data, source in problems:
        if severity >= 5:
            bar_color = "#c0392b"
            stars = "★★★★★"
        elif severity >= 4:
            bar_color = "#e67e22"
            stars = "★★★★☆"
        elif severity >= 3:
            bar_color = "#f39c12"
            stars = "★★★☆☆"
        else:
            bar_color = "#27ae60"
            stars = "★★☆☆☆"
        problems_html += '<div class="problem-card" style="display:flex;border:1px solid #e2e8f0;border-radius:10px;margin-bottom:14px;overflow:hidden;background:#fff;">'
        problems_html += '<div style="width:6px;background:' + bar_color + ';flex-shrink:0;"></div>'
        problems_html += '<div style="padding:16px 20px;flex:1;">'
        problems_html += '<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;">'
        problems_html += '<span style="font-weight:700;font-size:15px;color:#1a202c;">' + desc + '</span>'
        problems_html += '<span style="color:' + bar_color + ';font-size:14px;">' + stars + '</span>'
        problems_html += '</div>'
        problems_html += '<p style="margin:0 0 8px 0;font-size:13px;color:#4a5568;line-height:1.7;">' + data + '</p>'
        problems_html += '<a href="' + source + '" target="_blank" style="font-size:12px;color:#2c5282;text-decoration:none;">📋 数据来源</a>'
        problems_html += '</div></div>'
    
    # ===== 板块肆：外省市先进做法 =====
    compare_html = ""
    for cd in unit["compare_data"]:
        compare_html += '<div class="practice-card" style="background:#fff;border:1px solid #e2e8f0;border-radius:10px;padding:24px;margin-bottom:18px;">'
        compare_html += '<div style="display:flex;align-items:center;gap:12px;margin-bottom:14px;">'
        compare_html += '<span style="display:inline-block;width:40px;height:40px;border-radius:50%;background:linear-gradient(135deg,#2c5282,#4299e1);color:#fff;text-align:center;line-height:40px;font-size:14px;font-weight:700;">' + cd["city"][:2] + '</span>'
        compare_html += '<div><div style="font-weight:700;font-size:17px;color:#1a202c;">' + cd["city"] + '</div>'
        compare_html += '<div style="font-size:12px;color:#718096;">学习完成率 ' + cd["rate"] + '% | 数字化程度 ' + cd["digital"] + '%</div></div></div>'
        compare_html += '<p style="margin:0 0 14px 0;font-size:14px;color:#2d3748;line-height:1.8;">' + cd["method"] + '</p>'
        compare_html += '<div style="background:#ebf8ff;border-left:4px solid #2c5282;padding:14px 18px;border-radius:0 8px 8px 0;font-size:13px;color:#2c5282;line-height:1.7;">'
        compare_html += '<strong>↔ 与' + unit["short"] + '对比：</strong>' + cd["gap"]
        compare_html += '</div></div>'
    
    # ===== 板块伍：数智化/AI赋能建议 =====
    ai_html = ""
    colors_ai = [["#c0392b","#e74c3c"], ["#2c5282","#4299e1"], ["#c0392b","#e74c3c"], ["#2c5282","#4299e1"], ["#c0392b","#e74c3c"]]
    icons_ai = ["🤖", "📊", "🧠", "📱", "🔔"]
    for idx in range(len(unit["ai_directions"])):
        c = colors_ai[idx % 5]
        ai_html += '<div class="ai-item" style="display:flex;gap:16px;margin-bottom:22px;position:relative;">'
        ai_html += '<div style="width:14px;flex-shrink:0;display:flex;flex-direction:column;align-items:center;">'
        ai_html += '<div style="width:14px;height:14px;border-radius:50%;background:' + c[0] + ';flex-shrink:0;"></div>'
        if idx < len(unit["ai_directions"]) - 1:
            ai_html += '<div style="width:3px;flex:1;background:linear-gradient(' + c[0] + ',' + c[1] + ');margin:4px 0;"></div>'
        ai_html += '</div>'
        ai_html += '<div style="flex:1;background:#fff;border:1px solid #e2e8f0;border-radius:10px;padding:18px 22px;">'
        ai_html += '<div style="display:flex;align-items:center;gap:10px;margin-bottom:10px;">'
        ai_html += '<span style="font-size:22px;">' + icons_ai[idx] + '</span>'
        ai_html += '<span style="font-weight:700;font-size:16px;color:#1a202c;">' + unit["ai_directions"][idx] + '</span></div>'
        ai_html += '<div style="display:flex;gap:20px;flex-wrap:wrap;font-size:13px;color:#4a5568;">'
        ai_html += '<span>📦 产品形态：<strong style="color:#2c5282;">' + unit["ai_products"][idx] + '</strong></span>'
        ai_html += '<span>👥 目标用户：' + unit["ai_users"][idx] + '</span>'
        ai_html += '<span>⏱ 开发周期：' + unit["ai_cycles"][idx] + '</span>'
        ai_html += '<span>🔧 技术可行性：<strong style="color:' + ("#27ae60" if unit["ai_feasibility"][idx] == "高" else "#e67e22") + ';">' + unit["ai_feasibility"][idx] + '</strong></span>'
        ai_html += '</div></div></div>'
    
    # ===== 板块陆：优化建议 =====
    opts_html = ""
    backgrounds = ["#fef2f2", "#eff6ff", "#fef2f2", "#eff6ff", "#fef2f2"]
    for idx in range(len(unit["opts_titles"])):
        bg = backgrounds[idx % 5]
        steps = unit["opts_steps"][idx] if isinstance(unit["opts_steps"][idx], list) else ["步骤一", "步骤二", "步骤三"]
        steps_html = ""
        for si, s in enumerate(steps):
            steps_html += '<div style="display:flex;align-items:flex-start;gap:10px;margin-bottom:10px;">'
            steps_html += '<span style="display:inline-flex;align-items:center;justify-content:center;width:24px;height:24px;border-radius:50%;background:' + ("#c0392b" if si == 0 else "#2c5282") + ';color:#fff;font-size:12px;flex-shrink:0;">' + str(si+1) + '</span>'
            steps_html += '<span style="font-size:13px;color:#2d3748;line-height:1.6;">' + s + '</span></div>'
        
        responsible = unit["opts_responsibles"][idx] if isinstance(unit["opts_responsibles"], list) else unit["opts_responsibles"]
        
        opts_html += '<div class="opt-item" style="background:#fff;border:1px solid #e2e8f0;border-radius:10px;margin-bottom:14px;overflow:hidden;">'
        opts_html += '<div class="opt-header" onclick="toggleOpt(this)" style="display:flex;align-items:center;gap:14px;padding:16px 22px;cursor:pointer;user-select:none;">'
        opts_html += '<span style="display:inline-flex;align-items:center;justify-content:center;width:32px;height:32px;border-radius:50%;background:linear-gradient(135deg,#c0392b,#2c5282);color:#fff;font-size:14px;font-weight:700;">' + str(idx+1) + '</span>'
        opts_html += '<span style="flex:1;font-weight:700;font-size:15px;color:#1a202c;">' + unit["opts_titles"][idx] + '</span>'
        opts_html += '<span class="arrow" style="font-size:18px;color:#a0aec0;transition:transform 0.3s;">▼</span></div>'
        opts_html += '<div class="opt-body" style="display:none;padding:0 22px 20px 22px;">'
        opts_html += '<div style="padding:14px 18px;background:' + bg + ';border-radius:8px;margin-bottom:14px;font-size:14px;color:#2d3748;line-height:1.8;">' + unit["opts_bodies"][idx] + '</div>'
        opts_html += '<div style="font-size:13px;color:#4a5568;margin-bottom:10px;"><strong>🏢 责任主体：</strong>' + responsible + '</div>'
        opts_html += '<div style="font-size:13px;color:#4a5568;margin-bottom:10px;"><strong>📋 实施步骤：</strong></div>'
        opts_html += steps_html
        opts_html += '<div style="display:flex;gap:20px;flex-wrap:wrap;margin-top:12px;">'
        opts_html += '<div style="background:#f7fafc;border:1px solid #e2e8f0;border-radius:8px;padding:10px 16px;font-size:12px;color:#4a5568;">⏰ <strong>时间节点</strong><br><span style="color:#c0392b;font-weight:600;">' + unit["opts_times"][idx] + '</span></div>'
        opts_html += '<div style="background:#f7fafc;border:1px solid #e2e8f0;border-radius:8px;padding:10px 16px;font-size:12px;color:#4a5568;">📊 <strong>效果评估KPI</strong><br><span style="color:#2c5282;font-weight:600;">' + unit["opts_kpis"][idx] + '</span></div>'
        opts_html += '</div></div></div>'
    
    # ===== 日期与标题 =====
    now = datetime.datetime.now()
    date_str = now.strftime("%Y年%m月%d日")
    file_ts = now.strftime("%Y%m%d%H%M")
    
    if duty == "党员教育":
        report_title = unit["name"] + " · 党员教育专项调研报告"
    elif "党校" in unit["name"]:
        report_title = unit["name"] + " · 干部培训专项调研报告"
    else:
        report_title = unit["name"] + " · 干部教育培训管理专项调研报告"
    
    # ===== 完整HTML =====
    html = '<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1.0">'
    html += '<title>' + report_title + '</title>'
    html += '<style>'
    html += '*{margin:0;padding:0;box-sizing:border-box;}'
    html += 'body{font-family:"Microsoft YaHei","PingFang SC",sans-serif;background:#f5f6fa;color:#1a202c;line-height:1.6;}'
    html += '.container{max-width:1100px;margin:0 auto;padding:24px 20px 60px;}'
    html += '.header{text-align:center;padding:40px 20px 30px;background:linear-gradient(135deg,#c0392b 0%,#8e1a1a 50%,#2c5282 100%);border-radius:0 0 24px 24px;margin-bottom:30px;color:#fff;}'
    html += '.header h1{font-size:28px;font-weight:800;margin-bottom:8px;letter-spacing:1px;}'
    html += '.header .subtitle{font-size:14px;opacity:0.85;}'
    html += '.leader-section{display:grid;grid-template-columns:repeat(3,1fr);gap:16px;margin-bottom:30px;}'
    html += '.leader-card{padding:22px 20px;border-radius:12px;color:#fff;text-align:center;}'
    html += '.leader-card h3{font-size:13px;opacity:0.9;margin-bottom:8px;letter-spacing:1px;}'
    html += '.leader-card p{font-size:14px;line-height:1.7;font-weight:600;}'
    html += '.section{background:#fff;border-radius:14px;padding:28px 24px;margin-bottom:24px;border:1px solid #e2e8f0;box-shadow:0 1px 3px rgba(0,0,0,0.05);}'
    html += '.section-title{font-size:20px;font-weight:800;color:#1a202c;margin-bottom:20px;padding-bottom:12px;border-bottom:3px solid #c0392b;display:flex;align-items:center;gap:10px;}'
    html += '.section-title span{color:#c0392b;}'
    html += '.summary-grid{display:grid;grid-template-columns:repeat(2,1fr);gap:14px;}'
    html += '.summary-card{padding:18px 20px;border-radius:10px;border:1px solid #e2e8f0;background:#fff;transition:transform 0.2s,box-shadow 0.2s;}'
    html += '.summary-card:hover{transform:translateY(-2px);box-shadow:0 4px 12px rgba(0,0,0,0.08);}'
    html += '.summary-card .num{display:inline-flex;align-items:center;justify-content:center;width:28px;height:28px;border-radius:50%;background:linear-gradient(135deg,#c0392b,#2c5282);color:#fff;font-size:13px;font-weight:700;margin-right:10px;}'
    html += '.summary-card .tag{display:inline-block;padding:2px 10px;border-radius:10px;font-size:11px;color:#2c5282;background:#ebf8ff;margin-left:8px;}'
    html += '.summary-card p{margin-top:8px;font-size:14px;color:#2d3748;line-height:1.7;}'
    html += 'table{width:100%;border-collapse:collapse;font-size:14px;}'
    html += 'th{background:#2c5282;color:#fff;padding:12px 15px;text-align:left;font-weight:600;font-size:13px;}'
    html += 'th:first-child{border-radius:8px 0 0 0;}th:last-child{border-radius:0 8px 0 0;}'
    html += 'td{padding:12px 15px;border-bottom:1px solid #e2e8f0;}'
    html += 'tr:hover{background:#f7fafc;}'
    html += '.print-btn{position:fixed;bottom:30px;right:30px;width:52px;height:52px;border-radius:50%;background:linear-gradient(135deg,#c0392b,#2c5282);color:#fff;border:none;font-size:22px;cursor:pointer;box-shadow:0 4px 16px rgba(192,57,43,0.3);z-index:999;transition:transform 0.2s;}'
    html += '.print-btn:hover{transform:scale(1.1);}'
    html += '@media(max-width:768px){.leader-section{grid-template-columns:1fr;}.summary-grid{grid-template-columns:1fr;}table{font-size:12px;}th,td{padding:8px 10px;}.header h1{font-size:20px;}}'
    html += '@media print{.print-btn{display:none;}.section{break-inside:avoid;}.container{padding:10px;}.header{border-radius:0;}}'
    html += '</style></head><body>'
    html += '<button class="print-btn" onclick="window.print()" title="打印/PDF">🖨</button>'
    html += '<div class="container">'
    
    # Header
    html += '<div class="header"><h1>' + report_title + '</h1>'
    html += '<div class="subtitle">' + date_str + ' ｜ 据公开资料整理 仅供参考</div></div>'
    
    # 领导速览
    html += '<div class="leader-section">'
    html += '<div class="leader-card" style="background:linear-gradient(135deg,#c0392b,#e74c3c);"><h3>🔍 核心发现</h3><p>' + core_finding + '</p></div>'
    html += '<div class="leader-card" style="background:linear-gradient(135deg,#2c5282,#4299e1);"><h3>📏 最大差距</h3><p>' + biggest_gap + '</p></div>'
    html += '<div class="leader-card" style="background:linear-gradient(135deg,#27ae60,#2ecc71);"><h3>💡 首要建议</h3><p>' + top_suggestion + '</p></div>'
    html += '</div>'
    
    # 壹·核心摘要
    html += '<div class="section"><div class="section-title"><span>壹</span> 核心摘要</div>'
    html += '<div class="summary-grid">'
    for num, tag, text in summaries:
        html += '<div class="summary-card"><div style="display:flex;align-items:center;"><span class="num">' + num + '</span><strong style="font-size:15px;">' + tag + '</strong><span class="tag">' + tag + '</span></div><p>' + text + '</p></div>'
    html += '</div></div>'
    
    # 贰·上级精神与本地实践对照
    html += '<div class="section"><div class="section-title"><span>贰</span> 上级精神与本地实践对照</div>'
    html += '<div style="overflow-x:auto;"><table id="benchmarkTable"><thead><tr>'
    html += '<th>指标领域</th><th>上级要求</th><th>本地现状</th><th>达标判定</th><th>本土化建议</th>'
    html += '</tr></thead><tbody>' + table_rows + '</tbody></table></div></div>'
    
    # 叁·问题诊断
    html += '<div class="section"><div class="section-title"><span>叁</span> 问题诊断</div>'
    html += problems_html + '</div>'
    
    # 伍·外省市先进做法
    html += '<div class="section"><div class="section-title"><span>肆</span> 外省市先进做法与本地差距对比</div>'
    html += compare_html + '</div>'
    
    # 伍·数智化/AI赋能
    html += '<div class="section"><div class="section-title"><span>伍</span> 数智化/AI赋能专项建议</div>'
    html += ai_html + '</div>'
    
    # 陆·优化建议
    html += '<div class="section"><div class="section-title"><span>陆</span> 优化建议</div>'
    html += opts_html + '</div>'
    
    # Footer
    html += '<div style="text-align:center;padding:20px 0;font-size:12px;color:#a0aec0;">本报告基于公开资料整理，仅供参考 ｜ ' + date_str + '</div>'
    html += '</div>'
    
    # JS
    html += '<script>'
    html += 'function toggleOpt(el){var body=el.nextElementSibling;var arrow=el.querySelector(".arrow");if(body.style.display==="none"){body.style.display="block";arrow.style.transform="rotate(180deg)";}else{body.style.display="none";arrow.style.transform="rotate(0deg)";}}'
    html += '</script></body></html>'
    
    return html

# ===== 生成报告 =====
results = []
for unit in UNITS:
    now = datetime.datetime.now()
    file_ts = now.strftime("%Y%m%d%H%M")
    filename = unit["id"] + file_ts + ".html"
    filepath = "/data/www/files/" + filename
    html_content = build_html(unit)
    
    with open(filepath, "w", encoding="utf-8") as f:
        f.write(html_content)
    
    results.append({
        "name": unit["name"],
        "filename": filename,
        "internal": "http://192.168.99.133:5678/" + filename,
        "external": "https://ziyuan.cdlhyj.com/" + filename
    })
    print("✅ 已生成: " + unit["name"] + " -> " + filename)

print("\n===== 报告链接 =====")
for r in results:
    print(r["name"])
    print("  内网: " + r["internal"])
    print("  外网: " + r["external"])
