avita_special_processor.py 55.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
# -*- coding: utf-8 -*-
"""
阿维塔专项 独立处理器
====================
对应 ORM 表:avita_special_month_data(明细,逐门店一行)
            avita_special_month_summary_metrics(汇总指标,单任务一行)
数据来源:主机厂数据表(Excel)。

源文件结构(经 7月样本核对,以实际附件为准):
  - 行1(大类合并表头):门店名称 | 门店简称 | 门店模式 | 入驻时间 | 驻店姓名 | 2026-07月主机厂数据(5列) | 2026-07月广联数据(2列)
  - 行2(子字段表头)  :        |        |        |        |        | 交付数 延保成交数 无忧成交数 门店单车收入(延保+无忧) 门店总产值 | 交付数 触客数
  - 行3 起              :逐门店明细
  - 末尾汇总段          :'阿维塔品牌汇总'(品牌标签,空值) + 售后门店数/售后场景开通率/售后订单数 等
本处理器:跳过前 2 行表头 → 解析明细行 → 捕获末尾汇总段 → 按 task_id 先逻辑删除(旧行置 is_deleted=1)后插入新行(is_deleted=0)落库,不再物理删除。
明细表中 store_mode(门店模式,文本)、entry_time(入驻时间,格式化为 YYYY-MM-DD)、resident_name(驻店姓名,文本)现已由源文件解析填充;
regional_operation(区域运营)由 dj_smartcarlife 两跳查询填充(门店名→merchant_id→director_name,director_type=9,多条去重以'/'分隔)。
cutoff_gl_extended_warranty_deal_count(广联延保成交数)/ cutoff_gl_worry_free_deal_count(广联无忧成交数)由 dj.glsx.com.cn 报表导出接口填充:
  取「通用品牌」报表 → 按门店名称精确匹配 → 延保小计行取「整车延保成交数」作广联延保成交数、
  取「延保小计」行「原厂权益成交数」(Z列) 作广联无忧成交数;
  报表中不存在的门店(如未纳入通用品牌)该两列留空(NULL)。
汇总表中 store_count/output_value/delivery_count/pre_sales_visit_count 及各渗透率/环比列,样本汇总段未提供 → 留空,待最终 Excel 生成或后续填充。
结果表生成(generate_result_excel):复制用户模板(exporttemplete/avita_special_report_template.xlsx),标题/表头/段标题的月份与截止日期占位替换:
  截止日期规则=用报表所属月(task.month);若当前时间已在报表所属月之后→取所属月最后一天(封账),否则取真实生成日期(进行中);
  明细行从 avita_special_month_data 读真实值并计算衍生指标(渗透率/触客率/引荐转化率),6月(上月)主机厂块无源 → '-';
  品牌汇总 项目/品牌 固定 = 阿维塔,门店数 = 明细数,售后三项取汇总表;售前触客率=售前触客数/交付数、整车延保渗透率=整车延保成交数/交付数、原厂权益渗透率=原厂权益成交数/交付数;环比(本月-上月)优先从 DB 取上月汇总、无则留空;生成后上传 OSS 并回填 result_file_url。
"""
import io
import logging
import os
import tempfile
from calendar import monthrange
from copy import copy
from datetime import datetime, date
from decimal import Decimal, InvalidOperation

import openpyxl
import requests
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
from sqlalchemy import create_engine, text
from config import Config
from report_utils import (
    mark_task_failed, cleanup_tmp_dir, download_all_files, _get_biz_sql_conn,
)
from oss_utils import upload_file
from models import (
    DataProcessTask, db,
    AvitaSpecialMonthData, AvitaSpecialMonthSummaryMetrics,
)

# 结果表生成模板(由用户提供的「字段取值说明(模板版)」复制而来,作为布局基线)
AVITA_TEMPLATE_PATH = os.path.join(
    os.path.dirname(os.path.abspath(__file__)),
    'exporttemplete', 'avita_special_report_template.xlsx')

# 附件导入模板底稿(静态空白版);下载接口会据此动态预填 D+ 阿维塔项目组门店名称
AVITA_ATTACH_TEMPLATE_PATH = os.path.join(
    os.path.dirname(os.path.abspath(__file__)),
    'import_templates', '阿维塔专项-主机厂数据表模板.xlsx')

logger = logging.getLogger('AvitaSpecialProcessor')

AVITA_TYPE = 'avita_special'

# 明细行列索引(0-based),依据最新源文件「行2 子字段」结构
# (门店模式/入驻时间/驻店姓名已插入到 col2/col3/col4,其余指标列整体右移 +3)
# col0=门店名称 col1=门店简称 col2=门店模式 col3=入驻时间 col4=驻店姓名
# col5=主机厂交付数 col6=主机厂延保成交数 col7=主机厂无忧成交数
# col8=门店单车收入(延保+无忧) col9=门店总产值 col10=广联交付数 col11=广联触客数
DETAIL_COL = {
    'store_name': 0,
    'store_short_name': 1,
    'store_mode': 2,
    'entry_time': 3,
    'resident_name': 4,
    'oem_delivery_count': 5,
    'oem_extended_warranty_deal_count': 6,
    'oem_worry_free_deal_count': 7,
    'oem_revenue_per_vehicle': 8,
    'oem_total_output': 9,
    'cutoff_gl_delivery_count': 10,
    'cutoff_gl_visit_count': 11,
}
_INT_COLS = {
    'oem_delivery_count', 'oem_extended_warranty_deal_count', 'oem_worry_free_deal_count',
    'cutoff_gl_delivery_count', 'cutoff_gl_visit_count',
    # 注:cutoff_gl_extended_warranty_deal_count / cutoff_gl_worry_free_deal_count
    #     来源于广联报表导出接口(非源文件),在 _save 中由 fetch_glsx_deal_counts 填充。
}
_STR_COLS = {'store_name', 'store_short_name', 'store_mode', 'entry_time', 'resident_name'}

# 末尾汇总段:源文件标签 → ORM 属性
SUMMARY_LABELS = {
    '售后门店数': 'after_sales_store_count',
    '售后场景开通率': 'after_sales_scene_open_rate',
    '售后订单数': 'after_sales_order_count',
}
BRAND_SUMMARY_LABEL = '阿维塔品牌汇总'

# 品牌汇总「段标题 / 列头」样式:与模板原始行(标题行=深蓝 FF1F3864 + 白字加粗、列头行=浅蓝 FF8EA9DB + 深蓝加粗居中)保持一致。
# 动态排版时标题/列头会随明细行数下移,必须显式把样式带过去,否则只搬了文字、样式留在原位(空行)导致“标题行样式没跟随移动”。
_TITLE_FONT = Font(name='等线', size=12, bold=True, color='FFFFFFFF')
_TITLE_FILL = PatternFill(fill_type='solid', fgColor='FF1F3864')
_HEADER_FONT = Font(name='等线', size=10, bold=True, color='FF1F3864')
_HEADER_FILL = PatternFill(fill_type='solid', fgColor='FF8EA9DB')
_HEADER_ALIGN = Alignment(horizontal='center', vertical='center', wrap_text=True)


# 通用细边框(明细行与品牌汇总块数据行都需要边框,避免模板残留边框/无边框不一致)
_THIN = Side(style='thin', color='FF000000')
_THIN_BORDER = Border(left=_THIN, right=_THIN, top=_THIN, bottom=_THIN)
_CENTER_ALIGN = Alignment(horizontal='center', vertical='center')


def _apply_title_style(ws, r, width):
    """把段标题样式(深蓝填充 + 白字加粗 + 边框)铺满该行前 width 列。"""
    for c in range(1, width + 1):
        cell = ws.cell(row=r, column=c)
        cell.font = _TITLE_FONT
        cell.fill = _TITLE_FILL
        cell.alignment = _CENTER_ALIGN
        cell.border = _THIN_BORDER


def _apply_header_style(ws, r, width):
    """把列头样式(浅蓝填充 + 深蓝加粗居中 + 边框)铺满该行前 width 列。"""
    for c in range(1, width + 1):
        cell = ws.cell(row=r, column=c)
        cell.font = _HEADER_FONT
        cell.fill = _HEADER_FILL
        cell.alignment = _HEADER_ALIGN
        cell.border = _THIN_BORDER


# 明细列数字格式(其余列默认 General)。模板原固定块位于 7~13 行,门店多时会覆盖这些行,
# 必须把列格式显式写死,否则入驻时间(日期)/渗透率(%)会继承原固定块的错格式。
_DETAIL_NF = {
    4: 'yyyy/m/d;@',         # D 入驻时间(日期)
    11: '0.00%', 12: '0.00%',  # K/L 延保/无忧渗透率
    23: '0.00%', 24: '0.00%', 25: '0.00%', 26: '0.00%', 27: '0.00%',  # W~AA 各率(统一两位小数)
}


def _set_detail_cell(ws, r, c, v):
    """写明细单元格:清掉模板残留的填充/字体/对齐/数字格式,重设细边框 + 居中,
    并按列套用正确数字格式(日期/百分比),避免门店数变化时旧格式泄漏到明细行。"""
    cl = ws.cell(row=r, column=c)
    cl.value = v
    cl.fill = PatternFill(fill_type=None)
    cl.font = Font()
    cl.alignment = _CENTER_ALIGN
    cl.border = _THIN_BORDER
    cl.number_format = _DETAIL_NF.get(c, 'General')


# 品牌汇总「数据行」数字格式:渗透率/环比用百分比,其余默认。
_BLOCK_DATA_NF = {
    7: '0.00%', 12: '0.00%', 14: '0.00%',
    9: '0%', 15: '0.00%', 16: '0.00%', 17: '0.00%', 18: '0.00%',
}


def _set_block_data_cell(ws, r, c, v):
    """写品牌汇总数据单元格:清残留样式 + 细边框 + 居中 + 正确数字格式。"""
    cl = ws.cell(row=r, column=c)
    cl.value = v
    cl.fill = PatternFill(fill_type=None)
    cl.font = Font()
    cl.alignment = _CENTER_ALIGN
    cl.border = _THIN_BORDER
    cl.number_format = _BLOCK_DATA_NF.get(c, 'General')


def _to_int(v):
    if v is None:
        return None
    s = str(v).strip().replace(',', '')
    if s == '':
        return None
    try:
        return int(Decimal(s))
    except (InvalidOperation, ValueError):
        logger.warning(f"[阿维塔] 非整数值被置空: {v!r}")
        return None


def _to_dec(v):
    if v is None:
        return None
    s = str(v).strip().replace(',', '')
    if s == '':
        return None
    try:
        return Decimal(s)
    except (InvalidOperation, ValueError):
        logger.warning(f"[阿维塔] 非小数值被置空: {v!r}")
        return None


def _to_date_str(v):
    """入驻时间:datetime/date → 'YYYY-MM-DD';字符串截断到 10 位;空 → None"""
    if v is None:
        return None
    if isinstance(v, (datetime, date)):
        return v.strftime('%Y-%m-%d')
    s = str(v).strip()
    if s == '':
        return None
    return s[:10]


# ===================================================================
# 区域运营(regional_operation)查询:数据源 dj_smartcarlife
#   第1跳:门店名称 → merchant_id(dj_car_life_service_merchant.deleted_flag='N')
#   第2跳:merchant_id + director_type=9 → director_name
#           (dj_car_life_shop_merchant_director_config.deleted_flag='N')
#   多条记录去重后用 '/' 分隔;查不到返回 None(不致命,仅告警留空)
# ===================================================================
_BIZ_ENGINE = None


def _get_biz_engine():
    global _BIZ_ENGINE
    if _BIZ_ENGINE is None:
        _BIZ_ENGINE = create_engine(Config.BIZ_SQL_DATABASE_URL, echo=False, pool_pre_ping=True)
    return _BIZ_ENGINE


def fetch_regional_operation(store_name):
    """根据门店名称查询区域运营(dj_smartcarlife 两跳查询)。失败返回 None。"""
    if not store_name:
        return None
    engine = _get_biz_engine()
    try:
        with engine.connect() as conn:
            mids = conn.execute(
                text("SELECT merchant_id FROM dj_car_life_service_merchant "
                     "WHERE merchant_name=:name AND deleted_flag='N'"),
                {"name": store_name},
            ).fetchall()
            if not mids:
                logger.warning(f"[阿维塔] 区域运营:门店名未匹配商户号 store_name={store_name!r}")
                return None
            names = set()
            for (mid,) in mids:
                if mid is None:
                    continue
                rows = conn.execute(
                    text("SELECT director_name FROM dj_car_life_shop_merchant_director_config "
                         "WHERE deleted_flag='N' AND merchant_id=:mid AND director_type=9"),
                    {"mid": mid},
                ).fetchall()
                for (dn,) in rows:
                    if dn is not None and str(dn).strip() != '':
                        names.add(str(dn).strip())
            if not names:
                return None
            return '/'.join(sorted(names))
    except Exception as e:
        logger.warning(f"[阿维塔] 区域运营查询失败 store_name={store_name!r}: {e}")
        return None


# ===================================================================
# 广联延保/权益成交数(cutoff_gl_*_deal_count)查询:数据源 dj.glsx.com.cn 报表导出
#   第1步:queryAllExcel?filename={stat_month}&... 取 list 中 filename 含 '通用品牌' 的 key
#   第2步:download?key={key} 取 data.list[0].url
#   第3步:GET 该 url 下载 xlsx,解析 Sheet1
#          - 表头行(col0=='业务类型',表头单元格可能含换行需归一)定位列
#          - 门店(col2) / 整车延保成交数 / 原厂权益成交数
#          - 行 col0=='延保小计' → 取 整车延保成交数 作为 广联延保成交数;
#                                 取 原厂权益成交数(Z列) 作为 广联权益(无忧)成交数
#            (worry_free 由「延保小计」行取「原厂权益成交数」,不再取「权益小计」行)
#   按门店名称(与 avita_special_month_data.store_name 精确匹配)聚合,
#   返回 {store_name: (ext_count, worry_count)};失败返回 {}(不致命,仅告警留空)
# ===================================================================
_GLSX_BASE = 'https://dj.glsx.com.cn/reportExport'
_GLSX_TIMEOUT = (30, 120)


def _norm_header(s):
    """表头单元格归一:去空格/换行,便于按列名定位(如 '整车延保\n成交数'→'整车延保成交数')"""
    return ''.join(str(s).split()) if s is not None else ''


def _cell_to_int(v):
    """单元格转 int:空/非数字 → 0(用于求和聚合)"""
    if v is None:
        return 0
    s = str(v).strip().replace(',', '')
    if s == '' or s == '-':
        return 0
    try:
        return int(Decimal(s))
    except (InvalidOperation, ValueError):
        return 0


def fetch_glsx_deal_counts(stat_month):
    """从广联报表导出接口获取各门店的 广联延保成交数 / 广联权益(无忧)成交数。
    返回 {门店名称: (ext_count, worry_count)}。任何失败返回空 dict(不致命)。"""
    if not stat_month:
        logger.warning('[阿维塔] 广联报表:stat_month 为空,跳过获取')
        return {}
    try:
        # 第1步:列出报表,定位 通用品牌
        resp = requests.get(_GLSX_BASE + '/queryAllExcel', params={
            'pageSize': 10, 'currentPage': 1, 'filename': stat_month,
            'business_type': 'yanbao', 'report_type': 'yanbaoMerAndPerRanking', 'key': '',
        }, timeout=_GLSX_TIMEOUT)
        resp.raise_for_status()
        items = (resp.json().get('data') or {}).get('list') or []
        target = next((x for x in items if '通用品牌' in (x.get('filename') or '')), None)
        if not target:
            logger.warning(f'[阿维塔] 广联报表:未找到 通用品牌 报表(filename={stat_month})')
            return {}
        key = target['key']
        # 第2步:获取下载 url
        dl = requests.get(_GLSX_BASE + '/download', params={'key': key}, timeout=_GLSX_TIMEOUT)
        dl.raise_for_status()
        dlist = (dl.json().get('data') or {}).get('list') or []
        if not dlist or not dlist[0].get('url'):
            logger.warning('[阿维塔] 广联报表:download 未返回有效文件 url')
            return {}
        file_url = dlist[0]['url']
        # 第3步:下载并解析 xlsx
        x = requests.get(file_url, timeout=_GLSX_TIMEOUT)
        x.raise_for_status()
        wb = openpyxl.load_workbook(io.BytesIO(x.content), data_only=True)
        ws = wb[wb.sheetnames[0]]
        rows = list(ws.iter_rows(values_only=True))
        hidx = next((i for i, row in enumerate(rows)
                     if row and _norm_header(row[0]) == '业务类型'), None)
        if hidx is None:
            logger.warning('[阿维塔] 广联报表:未找到表头行(业务类型)')
            return {}
        col = {_norm_header(n): j for j, n in enumerate(rows[hidx]) if n is not None}
        ext_c = col.get('整车延保成交数')
        worry_c = col.get('原厂权益成交数')
        store_c = col.get('门店')
        if ext_c is None or worry_c is None or store_c is None:
            logger.warning('[阿维塔] 广联报表:缺少必要列(整车延保成交数/原厂权益成交数/门店)')
            return {}
        result = {}
        for row in rows[hidx + 1:]:
            if not row:
                continue
            a = _norm_header(row[0]) if row[0] is not None else ''
            if a == '延保小计':
                s = str(row[store_c]).strip() if row[store_c] else ''
                if not s:
                    continue
                # 广联延保成交数:整车延保成交数(ext_c)
                result.setdefault(s, [0, 0])[0] += _cell_to_int(row[ext_c])
                # 广联无忧成交数:原厂权益成交数(worry_c,Z列)—— 取自「延保小计」行
                result.setdefault(s, [0, 0])[1] += _cell_to_int(row[worry_c])
        logger.info(f'[阿维塔] 广联报表:解析到 {len(result)} 个门店的延保/权益成交数')
        return result
    except Exception as e:
        logger.warning(f'[阿维塔] 广联报表获取失败(stat_month={stat_month}): {e}')
        return {}


# ===================================================================
# 结果表生成:基于用户提供的模板(exporttemplete/avita_special_report_template.xlsx)
#   按 task 的 month 派生「报表月标签 / 上月标签」,截止日期取真实生成时间;
#   明细行从 avita_special_month_data 读真实值并计算衍生指标;
#   6月(上月)主机厂块与品牌汇总聚合字段无数据源 → 置 '-';
#   品牌汇总 项目/品牌 固定 = 阿维塔。生成后上传 OSS 并回填 result_file_url。
# ===================================================================
def _safe_div(a, b):
    """安全除法:None/0 作 0;b 为 0 时返回 0"""
    a = a if a is not None else 0
    b = b if b is not None else 0
    try:
        return (a / b) if b != 0 else 0
    except (InvalidOperation, ZeroDivisionError, TypeError):
        return 0


def _safe_sub(a, b):
    """安全减法:任一为 None → None;否则 a - b(转 float)"""
    if a is None or b is None:
        return None
    try:
        return float(a) - float(b)
    except (InvalidOperation, TypeError, ValueError):
        return None


def _prev_month_str(ym):
    """'2026-07' -> '2026-06'(跨年 2026-01 -> 2025-12);非法输入 -> None"""
    if not isinstance(ym, str) or '-' not in ym:
        return None
    try:
        y, m = ym.split('-')[:2]
        y, m = int(y), int(m)
    except (ValueError, TypeError):
        return None
    if m == 1:
        return f"{y - 1}-12"
    return f"{y}-{m - 1:02d}"


def _dec_to_float(v):
    """DECIMAL/None → float/None(openpyxl 写 DECIMAL 不稳,转 float)"""
    if v is None:
        return None
    try:
        return float(v)
    except (InvalidOperation, TypeError, ValueError):
        return None


def _to_date(v):
    """entry_time:DATE/字符串(YYYY-MM-DD) → date;空 → None"""
    if v is None:
        return None
    if isinstance(v, (datetime, date)):
        return v
    s = str(v).strip()
    if s == '':
        return None
    try:
        return datetime.strptime(s[:10], '%Y-%m-%d').date()
    except ValueError:
        return s


def _set_cell(ws, r, c, v):
    """写入单元格;v 为 None 时显式清空。
    注意:openpyxl 的 ws.cell(r, c, value=None) 不会清除已存在的旧值,
    必须用 ws.cell(r, c).value = None 才能真正清空。"""
    ws.cell(r, c).value = v


class AvitaSpecialProcessor:
    """阿维塔专项独立处理器"""

    def __init__(self, app=None):
        self.app = app

    def build_attachment_template(self):
        """基于静态空白底稿预填门店名称,返回临时文件路径与临时目录。

        门店来源:D+ `pg_group_info.group_name='阿维塔'` + `pg_group_store_rel`,
        按 pgr.id 倒序、按门店名去重;D+ 不可达/查询失败时退化为空门店模板。
        布局:A3 起连续写门店名;汇总段不固定,紧跟最后一行门店并空一行,
        其余列及汇总数值保持空白。
        """
        store_names = []
        conn = _get_biz_sql_conn()
        if conn is None:
            logger.warning('[阿维塔] 附件模板预填:D+ 连接失败,生成空门店模板')
        else:
            try:
                rows = conn.execute(text(
                    "select pgr.merchant_name "
                    "from pg_group_info pg "
                    "inner join pg_group_store_rel pgr on pg.id = pgr.group_id "
                    "  and pgr.deleted_flag = 'N' "
                    "where pg.deleted_flag = 'N' and pg.group_name = :gname "
                    "order by pgr.id desc"
                ), {'gname': '阿维塔'}).fetchall()
                seen = set()
                for r in rows:
                    name = r[0]
                    if name and name not in seen:
                        seen.add(name)
                        store_names.append(name)
            except Exception as e:
                logger.warning(f'[阿维塔] 附件模板预填:门店查询失败,生成空门店模板: {e}')
            finally:
                conn.close()
        logger.info(f'[阿维塔] 附件模板预填门店 {len(store_names)} 家')

        wb = openpyxl.load_workbook(AVITA_ATTACH_TEMPLATE_PATH)
        ws = wb[wb.sheetnames[0]]
        max_col = ws.max_column
        summary_labels = [BRAND_SUMMARY_LABEL] + list(SUMMARY_LABELS.keys())

        # 捕获底稿数据行样式与汇总段样式(汇总段位置随门店数变化)
        name_style = [copy(ws.cell(3, c)._style) for c in range(1, max_col + 1)]
        summary_styles = {}
        for r in range(3, ws.max_row + 1):
            v = ws.cell(r, 1).value
            if v in summary_labels:
                summary_styles[v] = (
                    [copy(ws.cell(r, c)._style) for c in range(1, max_col + 1)],
                    ws.row_dimensions[r].height,
                )

        # 清空第 3 行起的旧值(含底稿汇总段),再按实际门店数重写
        for r in range(3, ws.max_row + 1):
            for c in range(1, max_col + 1):
                ws.cell(r, c).value = None

        n = len(store_names)
        for i, name in enumerate(store_names):
            r = 3 + i
            for c in range(1, max_col + 1):
                ws.cell(r, c)._style = copy(name_style[c - 1])
            ws.cell(r, 1).value = name

        data_end = 2 + n
        srow = data_end + 2          # 与最后一行门店之间留一行空行

        # 间隔行清空样式,避免残留底稿边框被误认为可填门店行
        for c in range(1, max_col + 1):
            cell = ws.cell(srow - 1, c)
            cell.value = None
            cell.font = Font()
            cell.fill = PatternFill()
            cell.border = Border()
            cell.alignment = Alignment()
            cell.number_format = 'General'
        for i, label in enumerate(summary_labels):
            r = srow + i
            style, height = summary_styles[label]
            for c in range(1, max_col + 1):
                ws.cell(r, c)._style = copy(style[c - 1])
                ws.cell(r, c).value = None
            ws.cell(r, 1).value = label
            if height:
                ws.row_dimensions[r].height = height

        last_row = srow + len(summary_labels) - 1
        if ws.max_row > last_row:
            ws.delete_rows(last_row + 1, ws.max_row - last_row)

        tmp_dir = tempfile.mkdtemp(prefix='avita_tpl_')
        path = os.path.join(tmp_dir, '阿维塔专项-主机厂数据表模板.xlsx')
        wb.save(path)
        return path, tmp_dir

    def process(self, task):
        """处理单个阿维塔专项任务:解析源文件 → 落明细/汇总表 → 置 COMPLETED"""
        task_id = task.id
        try:
            detail_rows, summary = self._parse(task)
            self._save(task, detail_rows, summary)

            task = DataProcessTask.query.filter_by(id=task_id).first()
            # 生成结果 Excel(基于用户模板:日期占位替换 + 品牌固定 + 明细从 DB 读真实值)
            try:
                url = self.generate_result_excel(task)
            except Exception as ge:
                logger.warning(f"[阿维塔] 结果表生成失败(task {task_id}): {ge}")
                url = ''
            task.status = 'COMPLETED'
            task.result_file_url = url or ''   # 最终 Excel:基于用户模板生成
            task.error_msg = ''
            db.session.commit()
            logger.info(f"[阿维塔] 任务 {task_id} 处理完成:明细 {len(detail_rows)} 行,汇总 1 行")
        except Exception as e:
            db.session.rollback()
            mark_task_failed(task_id, str(e))
            raise

    # ============================================================
    # 调度器入口
    # ============================================================
    def scan_avita_special(self):
        """扫描 avita_special 类型的 PROCESSING 任务并逐个处理(供 AvitaSpecialScheduler 调用)。
        与 OutputValueProcessor.scan_output_value 对等:扫描 → 逐任务 process → 统计成功/失败。"""
        logger.info("[阿维塔] 开始扫描 avita_special 待处理任务")
        tasks = DataProcessTask.query.filter_by(
            data_table_type='avita_special',
            status='PROCESSING',
            is_deleted=0,
        ).order_by(DataProcessTask.id.asc()).all()
        logger.info(f"[阿维塔] 扫描到 {len(tasks)} 个待处理任务")

        success_count = 0
        fail_count = 0
        for task in tasks:
            try:
                self.process(task)
                success_count += 1
                logger.info(f"[阿维塔] 任务 {task.id} 处理成功")
            except Exception as e:
                import traceback as _tb
                fail_count += 1
                logger.error(f"[阿维塔] 任务 {task.id} 处理失败: {str(e)}")
                logger.error(_tb.format_exc())
                try:
                    mark_task_failed(task.id, str(e))
                except Exception as mark_err:
                    logger.error(f"[阿维塔] 标记任务失败时出错: {mark_err}")

        logger.info(f"[阿维塔] 扫描完成,成功 {success_count},失败 {fail_count}")
        return {'success': success_count, 'failed': fail_count}

    # ============================================================
    # 解析
    # ============================================================
    def _parse(self, task):
        task_id = task.id
        tmp_dir = tempfile.mkdtemp(prefix=f'avita_{task_id}_')
        try:
            file_map = download_all_files(task_id, tmp_dir)
            path = None
            for _form, p in file_map.items():
                if p:
                    path = p
                    break
            if not path:
                raise Exception('未找到可下载的阿维塔专项附件(主机厂数据表)')
            wb = openpyxl.load_workbook(path, read_only=True, data_only=True)
            ws = wb[wb.sheetnames[0]]
            rows = list(ws.iter_rows(values_only=True))
        finally:
            cleanup_tmp_dir(tmp_dir)

        detail_rows = []
        summary_vals = {attr: None for attr in SUMMARY_LABELS.values()}
        brand = None

        # 跳过前 2 行表头(大类 + 子字段),从第 3 行起解析
        for row in rows[2:]:
            a = row[0] if len(row) > 0 else None
            if a is None or str(a).strip() == '':
                continue
            label = str(a).strip()
            if label == BRAND_SUMMARY_LABEL:
                brand = '阿维塔'
                continue
            if label in SUMMARY_LABELS:
                val = row[1] if len(row) > 1 else None
                summary_vals[SUMMARY_LABELS[label]] = val
                continue
            # 否则视为明细门店行
            rec = {}
            for attr, idx in DETAIL_COL.items():
                v = row[idx] if idx < len(row) else None
                if attr in _INT_COLS:
                    rec[attr] = _to_int(v)
                elif attr in _STR_COLS:
                    if attr == 'entry_time':
                        rec[attr] = _to_date_str(v)
                    else:
                        rec[attr] = str(v).strip() if v is not None and str(v).strip() != '' else None
                else:
                    rec[attr] = _to_dec(v)
            detail_rows.append(rec)

        if not detail_rows:
            logger.warning(f"[阿维塔] 任务 {task_id} 未解析到任何明细门店行")

        return detail_rows, (brand, summary_vals)

    # ============================================================
    # 落库(按 task_id 先删后插,幂等)
    # ============================================================
    def _save(self, task, detail_rows, summary_tuple):
        task_id = task.id
        period_start = getattr(task, 'period_start', None)
        stat_month = (getattr(task, 'month', None) or ''
                      or (period_start.strftime('%Y-%m') if period_start else ''))
        brand, summary_vals = summary_tuple

        # 广联报表:按门店名称匹配 延保小计/权益小计 行,获取 广联延保成交数 / 广联无忧成交数
        glsx_map = fetch_glsx_deal_counts(stat_month)
        if glsx_map:
            logger.info(f"[阿维塔] 广联报表匹配:task {task_id} 命中 {len(glsx_map)} 个门店")

        # ---------- 明细 ----------
        # 逻辑删除(软删除):将本任务旧行置 is_deleted=1,再插入新行(is_deleted=0),不再物理删除
        AvitaSpecialMonthData.query.filter_by(task_id=task_id, is_deleted=0).update(
            {AvitaSpecialMonthData.is_deleted: 1}, synchronize_session=False)
        db.session.flush()
        detail_objs = []
        for rec in detail_rows:
            sn = rec.get('store_name') or ''
            gl = glsx_map.get(sn)
            if gl is None and sn:
                logger.warning(f"[阿维塔] 门店 {sn!r} 未在广联报表匹配到(延保/无忧成交数留空)")
            detail_objs.append(AvitaSpecialMonthData(
                task_id=task_id,
                is_deleted=0,
                stat_month=stat_month,
                store_name=sn,
                store_short_name=rec.get('store_short_name'),
                store_mode=rec.get('store_mode'),
                entry_time=rec.get('entry_time'),
                regional_operation=fetch_regional_operation(rec.get('store_name')),
                resident_name=rec.get('resident_name'),
                oem_delivery_count=rec.get('oem_delivery_count'),
                oem_extended_warranty_deal_count=rec.get('oem_extended_warranty_deal_count'),
                oem_worry_free_deal_count=rec.get('oem_worry_free_deal_count'),
                oem_revenue_per_vehicle=rec.get('oem_revenue_per_vehicle'),
                oem_total_output=rec.get('oem_total_output'),
                cutoff_gl_delivery_count=rec.get('cutoff_gl_delivery_count'),
                cutoff_gl_visit_count=rec.get('cutoff_gl_visit_count'),
                cutoff_gl_extended_warranty_deal_count=gl[0] if gl else None,
                cutoff_gl_worry_free_deal_count=gl[1] if gl else None,
            ))
        db.session.add_all(detail_objs)

        # ---------- 汇总(与结果表品牌汇总同源同步)----------
        # 逻辑删除(软删除):将本任务旧行置 is_deleted=1,再插入新行(is_deleted=0),不再物理删除
        AvitaSpecialMonthSummaryMetrics.query.filter_by(task_id=task_id, is_deleted=0).update(
            {AvitaSpecialMonthSummaryMetrics.is_deleted: 1}, synchronize_session=False)
        db.session.flush()
        # 当前明细月份聚合:门店总产值 / 主机厂交付数 / 广联触客数 /
        #   主机厂整车延保成交数 / 主机厂原厂权益(无忧)成交数 对明细行求和
        _tot_output = sum(float(d.oem_total_output or 0) for d in detail_objs)
        _tot_delivery = int(sum(d.oem_delivery_count or 0 for d in detail_objs))
        _tot_visit = int(sum(d.cutoff_gl_visit_count or 0 for d in detail_objs))
        _tot_ext = int(sum(d.oem_extended_warranty_deal_count or 0 for d in detail_objs))
        _tot_rights = int(sum(d.oem_worry_free_deal_count or 0 for d in detail_objs))
        # 售后场景开通率取自源文件汇总段(品牌汇总口径),其余三项渗透率与结果表同源:分子/交付数(E)
        _after_rate = _to_dec(summary_vals.get('after_sales_scene_open_rate'))
        _pre_rate = _safe_div(_tot_visit, _tot_delivery)        # 售前触客率 = 售前触客数/交付数 (F/E)
        _veh_rate = _safe_div(_tot_ext, _tot_delivery)          # 整车延保渗透率 = 整车延保成交数/交付数 (K/E)
        _rights_rate = _safe_div(_tot_rights, _tot_delivery)    # 原厂权益渗透率 = 原厂权益成交数/交付数 (M/E)
        # 环比(本月 - 上月):优先从 DB 取上一统计月 avita_special_month_summary_metrics;无则留空
        _mom_after = _mom_pre = _mom_veh = _mom_rights = None
        if stat_month:
            _prev_ym = _prev_month_str(stat_month)
            if _prev_ym:
                _prev = AvitaSpecialMonthSummaryMetrics.query.filter_by(
                    stat_month=_prev_ym, is_deleted=0).order_by(
                    AvitaSpecialMonthSummaryMetrics.id.desc()).first()
                if _prev is not None:
                    _p_pre = _safe_div(_prev.pre_sales_visit_count, _prev.delivery_count)
                    _p_veh = _safe_div(_prev.vehicle_extended_warranty_deal_count, _prev.delivery_count)
                    _p_rights = _safe_div(_prev.oem_rights_deal_count, _prev.delivery_count)
                    _p_after = _dec_to_float(_prev.after_sales_scene_open_rate)
                    _mom_after = _safe_sub(_dec_to_float(_after_rate), _p_after)
                    _mom_pre = _safe_sub(_pre_rate, _p_pre)
                    _mom_veh = _safe_sub(_veh_rate, _p_veh)
                    _mom_rights = _safe_sub(_rights_rate, _p_rights)
        sum_obj = AvitaSpecialMonthSummaryMetrics(
            task_id=task_id,
            is_deleted=0,
            stat_month=stat_month,
            project_name='阿维塔',
            brand=brand or '阿维塔',
            store_count=len(detail_objs),
            output_value=round(_tot_output, 2),
            delivery_count=_tot_delivery,
            pre_sales_visit_count=_tot_visit,
            pre_sales_visit_rate=_to_dec(round(_pre_rate, 6)),
            after_sales_store_count=_to_int(summary_vals.get('after_sales_store_count')),
            after_sales_scene_open_rate=_after_rate,
            after_sales_order_count=_to_int(summary_vals.get('after_sales_order_count')),
            vehicle_extended_warranty_deal_count=_tot_ext,
            vehicle_extended_warranty_penetration_rate=_to_dec(round(_veh_rate, 6)),
            oem_rights_deal_count=_tot_rights,
            oem_rights_penetration_rate=_to_dec(round(_rights_rate, 6)),
            after_sales_scene_open_rate_mom=_to_dec(round(_mom_after, 6)) if _mom_after is not None else None,
            pre_sales_visit_rate_mom=_to_dec(round(_mom_pre, 6)) if _mom_pre is not None else None,
            vehicle_extended_warranty_penetration_rate_mom=_to_dec(round(_mom_veh, 6)) if _mom_veh is not None else None,
            oem_rights_penetration_rate_mom=_to_dec(round(_mom_rights, 6)) if _mom_rights is not None else None,
        )
        db.session.add(sum_obj)
        db.session.commit()
        logger.info(f"[阿维塔] 落库完成:明细 {len(detail_objs)} 行 + 汇总 1 行(task_id={task_id})")

    # ============================================================
    # 品牌汇总块渲染(动态排版:紧贴明细行之后,不再固定于模板的 14/16/18/20 行)
    # ============================================================
    def _render_brand_summary(self, ws, details, summary, month, month_label, prev_month_label, start):
        """渲染「品牌汇总」两段(上月段 + 当前段),起始行随明细行数自动下移。

        参数:
          details          明细 ORM 列表(决定汇总块起始行)
          summary          本月汇总指标 ORM(可能 None)
          month            task.month(用于查上月汇总)
          month_label      如 '8月'
          prev_month_label 如 '7月'
          start            明细起始行(固定 4)
        两段结构(每段 = 段标题 + 列头 + 数据):
          上月段 列头 14 列(A~N),无环比;当前段 列头 18 列(A~R),含 4 个环比列。
        """
        n_stores = len(details)
        # ---- 当前月(明细月份)聚合 ----
        total_output = sum(float(_dec_to_float(d.oem_total_output) or 0) for d in details)
        total_delivery = sum(int(d.oem_delivery_count or 0) for d in details)
        total_visit = sum(int(d.cutoff_gl_visit_count or 0) for d in details)
        total_ext = sum(int(d.oem_extended_warranty_deal_count or 0) for d in details)
        total_rights = sum(int(d.oem_worry_free_deal_count or 0) for d in details)
        _sum_out = _dec_to_float(summary.output_value) if summary else None
        _sum_del = summary.delivery_count if summary else None
        _sum_vis = summary.pre_sales_visit_count if summary else None
        _sum_ext = summary.vehicle_extended_warranty_deal_count if summary else None
        _sum_rgt = summary.oem_rights_deal_count if summary else None
        _sum_stores = summary.store_count if summary else None
        E = _sum_del if _sum_del is not None else total_delivery
        F = _sum_vis if _sum_vis is not None else total_visit
        K = _sum_ext if _sum_ext is not None else total_ext
        M = _sum_rgt if _sum_rgt is not None else total_rights
        g_rate = _safe_div(F, E)     # 售前触客率 = 售前触客数 / 交付数
        l_rate = _safe_div(K, E)     # 整车延保渗透率 = 整车延保成交数 / 交付数
        n_rate = _safe_div(M, E)     # 原厂权益渗透率 = 原厂权益成交数 / 交付数
        cur_after = _dec_to_float(summary.after_sales_scene_open_rate) if summary else None

        # ---- 上月段(优先从 DB 取上一统计月的汇总指标;无则整行留空)----
        prev_summary = None
        if month:
            prev_ym = _prev_month_str(month)
            prev_summary = AvitaSpecialMonthSummaryMetrics.query.filter_by(
                stat_month=prev_ym, is_deleted=0).order_by(
                AvitaSpecialMonthSummaryMetrics.id.desc()).first()

        # ---- 动态行位:明细末尾 + 2(留 1 空行)起排布 ----
        detail_end = start + n_stores - 1
        base = detail_end + 2
        prev_hdr, prev_col, prev_data = base, base + 1, base + 2
        cur_hdr, cur_col, cur_data = base + 4, base + 5, base + 6
        # 若汇总块延伸到页脚合并占位区(B22:L26,空占位),先解除合并以免写 MergedCell 报错
        if cur_data >= 4:
            for mr in list(ws.merged_cells.ranges):
                if mr.min_row >= 4:
                    ws.unmerge_cells(str(mr))

        # ---- 段标题 / 列头 文本(提前定义,供样式铺满宽度使用)----
        _prev_headers = ['项目', '品牌', '门店数', '产值', '交付数', '售前触客数', '售前触客率',
                         '售后门店数', '售后场景开通率', '售后订单数', '整车延保成交数',
                         '整车延保渗透率', '原厂权益成交数', '原厂权益渗透率']
        # 当前段列头 = 上月段列头 + 4 个环比列
        _cur_headers = _prev_headers + ['售后场景开通率环比', '售前触客率环比',
                                        '整车延保渗透率环比', '原厂权益渗透率环比']

        # ---- 段标题(显式带样式,避免随明细行下移时只剩文字、样式留空)----
        ws.cell(row=prev_hdr, column=1, value=f"【品牌汇总 · {prev_month_label}段】")
        ws.cell(row=cur_hdr, column=1, value=f"【品牌汇总 · {month_label}段】")
        _apply_title_style(ws, prev_hdr, len(_prev_headers))
        _apply_title_style(ws, cur_hdr, len(_cur_headers))

        # ---- 上月段:列头 + 数据 ----
        for ci, h in enumerate(_prev_headers):
            _set_cell(ws, prev_col, ci + 1, h)
        _apply_header_style(ws, prev_col, len(_prev_headers))
        if prev_summary:
            p_E = prev_summary.delivery_count
            p_F = prev_summary.pre_sales_visit_count
            p_K = prev_summary.vehicle_extended_warranty_deal_count
            p_M = prev_summary.oem_rights_deal_count
            p_g = _safe_div(p_F, p_E)
            p_l = _safe_div(p_K, p_E)
            p_n = _safe_div(p_M, p_E)
            p_after = _dec_to_float(prev_summary.after_sales_scene_open_rate)
            _set_block_data_cell(ws, prev_data, 1, '阿维塔')
            _set_block_data_cell(ws, prev_data, 2, '阿维塔')
            _set_block_data_cell(ws, prev_data, 3, prev_summary.store_count)
            _set_block_data_cell(ws, prev_data, 4, _dec_to_float(prev_summary.output_value))
            _set_block_data_cell(ws, prev_data, 5, p_E)
            _set_block_data_cell(ws, prev_data, 6, p_F)
            _set_block_data_cell(ws, prev_data, 7, p_g)
            _set_block_data_cell(ws, prev_data, 8, prev_summary.after_sales_store_count)
            _set_block_data_cell(ws, prev_data, 9, p_after)
            _set_block_data_cell(ws, prev_data, 10, prev_summary.after_sales_order_count)
            _set_block_data_cell(ws, prev_data, 11, p_K)
            _set_block_data_cell(ws, prev_data, 12, p_l)
            _set_block_data_cell(ws, prev_data, 13, p_M)
            _set_block_data_cell(ws, prev_data, 14, p_n)
        else:
            _set_block_data_cell(ws, prev_data, 1, '阿维塔')
            _set_block_data_cell(ws, prev_data, 2, '阿维塔')
            for c in range(3, 15):
                _set_block_data_cell(ws, prev_data, c, None)

        # ---- 当前段:列头 + 数据 ----
        for ci, h in enumerate(_cur_headers):
            _set_cell(ws, cur_col, ci + 1, h)
        _apply_header_style(ws, cur_col, len(_cur_headers))
        _set_block_data_cell(ws, cur_data, 1, '阿维塔')
        _set_block_data_cell(ws, cur_data, 2, '阿维塔')
        _set_block_data_cell(ws, cur_data, 3, _sum_stores if _sum_stores is not None else n_stores)
        _set_block_data_cell(ws, cur_data, 4, _sum_out if _sum_out is not None else round(total_output, 2))
        _set_block_data_cell(ws, cur_data, 5, E)
        _set_block_data_cell(ws, cur_data, 6, F)
        _set_block_data_cell(ws, cur_data, 7, g_rate)
        _set_block_data_cell(ws, cur_data, 8, summary.after_sales_store_count if summary else None)
        _set_block_data_cell(ws, cur_data, 9, cur_after)
        _set_block_data_cell(ws, cur_data, 10, summary.after_sales_order_count if summary else None)
        _set_block_data_cell(ws, cur_data, 11, K)
        _set_block_data_cell(ws, cur_data, 12, l_rate)
        _set_block_data_cell(ws, cur_data, 13, M)
        _set_block_data_cell(ws, cur_data, 14, n_rate)
        _set_block_data_cell(ws, cur_data, 15, _safe_sub(cur_after, p_after) if prev_summary else None)
        _set_block_data_cell(ws, cur_data, 16, _safe_sub(g_rate, p_g) if prev_summary else None)
        _set_block_data_cell(ws, cur_data, 17, _safe_sub(l_rate, p_l) if prev_summary else None)
        _set_block_data_cell(ws, cur_data, 18, _safe_sub(n_rate, p_n) if prev_summary else None)

    # ============================================================
    # 结果表生成(基于模板 exporttemplete/avita_special_report_template.xlsx)
    # ============================================================
    def generate_result_excel(self, task):
        """根据 task 生成「阿维塔专项报表」结果 Excel:
        - 复制模板布局;标题/表头/段标题中的月份与截止日期占位替换:
          截止日期=用报表所属月(task.month),若当前时间已在所属月之后→取所属月最后一天(封账),否则取真实生成日期(进行中);
        - 明细行从 avita_special_month_data 读真实值并计算衍生指标(渗透率/触客率/引荐转化率);
        - 上一月份主机厂块(明细行 G..M):取上一统计月(task.month 相邻上月)同一门店的
          avita_special_month_data 逐格填入(交付数/延保/无忧/单车收入/两渗透率/总产值);
          无上一月任务或无同门店匹配时该行保持 '-';
        - 品牌汇总:售前触客率(G)=售前触客数(F)/交付数(E)、整车延保渗透率(L)=整车延保成交数(K)/交付数(E)、
          原厂权益渗透率(N)=原厂权益成交数(M)/交付数(E);环比(O/P/Q/R)=本月-上月,上月优先从 DB 取上一统计月
          avita_special_month_summary_metrics,无则整行(行16)与环比列留空;
        - 品牌汇总 项目/品牌 固定 = 阿维塔。
        返回 OSS 可访问 URL(失败抛异常)。"""
        task_id = task.id
        month = getattr(task, 'month', None) or ''

        # 报表月标签 / 上月标签(由 task.month 派生,保证生成器可复用)
        if len(month) >= 7 and month[4] == '-':
            try:
                y, m = int(month[:4]), int(month[5:7])
                month_label = f"{m}月"
                pm = m - 1 if m > 1 else 12
                prev_month_label = f"{pm}月"
            except (ValueError, IndexError):
                month_label, prev_month_label = '', ''
        else:
            month_label, prev_month_label = '', ''

        # 截止日期规则:用报表所属月(task.month)。
        # 若当前时间已在报表所属月之后 → 截止日期取报表所属月最后一天(月份已封账);
        # 否则(当前仍在报表所属月内)→ 取真实生成日期(月份进行中,数据为部分)。
        today = date.today()
        cutoff_date = datetime.now().strftime('%Y-%m-%d')  # 兜底
        if len(month) >= 7 and month[4] == '-':
            try:
                y, m = int(month[:4]), int(month[5:7])
                last_day = monthrange(y, m)[1]
                report_month_last = date(y, m, last_day)
                cutoff_date = (report_month_last if today > report_month_last
                               else today).strftime('%Y-%m-%d')
            except (ValueError, IndexError):
                cutoff_date = datetime.now().strftime('%Y-%m-%d')

        details = AvitaSpecialMonthData.query.filter_by(
            task_id=task_id, is_deleted=0).order_by(AvitaSpecialMonthData.id).all()
        summary = AvitaSpecialMonthSummaryMetrics.query.filter_by(
            task_id=task_id, is_deleted=0).order_by(
            AvitaSpecialMonthSummaryMetrics.id.desc()).first()

        # 上一月份任务(与当前月相邻的上一个月,取最新一条有效任务):
        # 用于明细行 G..M(上一月份主机厂数据)逐门店匹配。无上一月任务/无匹配门店时该行保持 '-'。
        prev_ym = _prev_month_str(month) if month else None
        prev_store_map = {}
        if prev_ym:
            _prev_task = DataProcessTask.query.filter_by(
                data_table_type='avita_special', month=prev_ym, is_deleted=0
            ).order_by(DataProcessTask.id.desc()).first()
            if _prev_task:
                _prev_details = AvitaSpecialMonthData.query.filter_by(
                    task_id=_prev_task.id, is_deleted=0
                ).order_by(AvitaSpecialMonthData.id).all()
                for _pd in _prev_details:
                    _k = (_pd.store_name or '').strip()
                    if _k:
                        prev_store_map[_k] = _pd
                    _sk = (_pd.store_short_name or '').strip()
                    if _sk:
                        prev_store_map.setdefault(_sk, _pd)

        if not os.path.exists(AVITA_TEMPLATE_PATH):
            raise Exception(f'阿维塔结果表模板不存在:{AVITA_TEMPLATE_PATH}')
        wb = openpyxl.load_workbook(AVITA_TEMPLATE_PATH)
        ws = wb[wb.sheetnames[0]]

        # 解除「明细/汇总区」内所有合并(min_row>=4):模板在品牌汇总块 15~19 行(B15:L19 等)
        # 及页脚占位区存在合并单元格,若不解除,门店多时明细行/汇总块写入会落到 MergedCell 上,
        # 报“attribute 'value' is read-only”。标题/表头行(1~3)的合并(A1:AA1、各列表头)保留不动。
        for mr in list(ws.merged_cells.ranges):
            if mr.min_row >= 4:
                ws.unmerge_cells(str(mr))

        # ---- 标题 / 表头 / 段标题 占位替换 ----
        ws['A1'] = f"阿维塔专项报表 ·「{month_label}」页签 ·  数据截止 {cutoff_date}"
        ws['G2'] = f"{prev_month_label}主机厂数据"
        ws['N2'] = f"截止{cutoff_date}主机厂数据"
        ws['S2'] = f"截止{cutoff_date}广联数据"
        ws['W2'] = f"数据截止{cutoff_date}"

        # ---- 明细起始行 ----
        start = 4
        n_stores = len(details)
        detail_end = start + n_stores - 1

        # 先清空模板自带的「固定品牌汇总块」(当前模板位于 7~13 行):
        # 该固定块要么被明细行覆盖(门店多)、要么成为残留(门店少)。
        # 统一先整体清空其数值/填充/字体/对齐/边框/数字格式,再交由动态块在正确位置重绘,
        # 否则门店数变化时:① 明细行会继承原块的深蓝/浅蓝填充与错的数字格式;
        # ② 固定块残留成“幽灵”行(标题行样式/格式未跟随移动的根因)。
        # 清空范围取 7 ~ max(13, 明细末行),确保覆盖固定块且不影响明细行
        # (明细行随后用 _set_detail_cell 重设边框与数字格式)。
        _reset_from = 7
        _reset_to = max(13, detail_end)
        for r in range(_reset_from, _reset_to + 1):
            for c in range(1, 28):
                _cl = ws.cell(row=r, column=c)
                _cl.value = None
                _cl.fill = PatternFill(fill_type=None)
                _cl.font = Font()
                _cl.alignment = Alignment()
                _cl.border = Border()
                _cl.number_format = 'General'

        # ---- 明细行(自第 4 行起,逐格重设边框 + 正确数字格式,杜绝模板残留格式泄漏)----
        for i, d in enumerate(details):
            r = start + i
            _set_detail_cell(ws, r, 1, d.store_name)
            _set_detail_cell(ws, r, 2, d.store_short_name)
            _set_detail_cell(ws, r, 3, d.store_mode)
            _set_detail_cell(ws, r, 4, _to_date(d.entry_time))
            _set_detail_cell(ws, r, 5, d.regional_operation)
            _set_detail_cell(ws, r, 6, d.resident_name)
            # 上一月份主机厂块 G..M:匹配上一月同门店数据;无匹配门店则保持 '-'
            _pd = (prev_store_map.get((d.store_name or '').strip())
                   or prev_store_map.get((d.store_short_name or '').strip()))
            if _pd is not None:
                _p_del = int(_pd.oem_delivery_count or 0)
                _p_ext = int(_pd.oem_extended_warranty_deal_count or 0)
                _p_wry = int(_pd.oem_worry_free_deal_count or 0)
                _set_detail_cell(ws, r, 7, _pd.oem_delivery_count)                  # G 交付数
                _set_detail_cell(ws, r, 8, _pd.oem_extended_warranty_deal_count)     # H 延保成交数
                _set_detail_cell(ws, r, 9, _pd.oem_worry_free_deal_count)            # I 无忧成交数
                _set_detail_cell(ws, r, 10, _dec_to_float(_pd.oem_revenue_per_vehicle))  # J 单车收入
                _set_detail_cell(ws, r, 11, _safe_div(_p_ext, _p_del))               # K 延保渗透率
                _set_detail_cell(ws, r, 12, _safe_div(_p_wry, _p_del))               # L 无忧渗透率
                _set_detail_cell(ws, r, 13, _dec_to_float(_pd.oem_total_output))     # M 门店总产值
            else:
                for c in range(7, 14):
                    _set_detail_cell(ws, r, c, '-')
            # 当前主机厂块 N..R
            _set_detail_cell(ws, r, 14, d.oem_delivery_count)
            _set_detail_cell(ws, r, 15, d.oem_extended_warranty_deal_count)
            _set_detail_cell(ws, r, 16, d.oem_worry_free_deal_count)
            _set_detail_cell(ws, r, 17, _dec_to_float(d.oem_revenue_per_vehicle))
            _set_detail_cell(ws, r, 18, _dec_to_float(d.oem_total_output))
            # 广联块 S..V
            _set_detail_cell(ws, r, 19, d.cutoff_gl_delivery_count)
            _set_detail_cell(ws, r, 20, d.cutoff_gl_visit_count)
            _set_detail_cell(ws, r, 21, d.cutoff_gl_extended_warranty_deal_count)
            _set_detail_cell(ws, r, 22, d.cutoff_gl_worry_free_deal_count)
            # 衍生指标
            n = d.oem_delivery_count or 0
            o = d.oem_extended_warranty_deal_count or 0
            p = d.oem_worry_free_deal_count or 0
            s = d.cutoff_gl_delivery_count or 0
            t = d.cutoff_gl_visit_count or 0
            u = d.cutoff_gl_extended_warranty_deal_count or 0
            v = d.cutoff_gl_worry_free_deal_count or 0
            _set_detail_cell(ws, r, 23, _safe_div(n, t))   # W 触客率 = 主机厂交付数 / 广联触客数 (N/T)
            _set_detail_cell(ws, r, 24, _safe_div(o, n))    # X 延保渗透率 = 延保 / 交付
            _set_detail_cell(ws, r, 25, _safe_div(p, n))    # Y 无忧渗透率 = 无忧 / 交付
            _set_detail_cell(ws, r, 26, _safe_div(u, t))    # Z 延保引荐转化率 = 广联延保 / 触客
            _set_detail_cell(ws, r, 27, _safe_div(v, t))    # AA 无忧引荐转化率 = 广联无忧 / 触客

        # 清除明细行之后的「多余预留行」:兜底清掉任何遗留的数值/填充/字体/对齐/边框/数字格式,
        # 确保动态品牌汇总块下方不残留模板旧色块或幽灵行(动态块随后在正确位置重绘)。
        # 注:模板原固定块(7~13 行)已在上方随明细区一并清空,这里覆盖明细末行之后的区域即可。
        _clear_to = max(21, start + len(details) + 12)   # 覆盖动态汇总块(最末行=cur_data=start+n+6)及页脚占位
        # 注:明细/汇总区的合并已在上方加载模板时统一解除(min_row>=4),此处无需再处理。
        for r in range(start + len(details), _clear_to):
            for c in range(1, 28):
                _cl = ws.cell(row=r, column=c)
                _cl.value = None
                _cl.fill = PatternFill(fill_type=None)
                _cl.font = Font()
                _cl.alignment = Alignment()
                _cl.border = Border()
                _cl.number_format = 'General'

        # 品牌汇总(动态排版:紧贴明细行之后,不再固定于 14/16/18/20)
        self._render_brand_summary(ws, details, summary, month, month_label, prev_month_label, start)

        # ---- sheet 重命名(月份占位替换)----
        try:
            ws.title = f"{month_label}页签-字段取值说明"
        except Exception:
            pass

        # ---- 保存 + 上传 OSS ----
        tmp = tempfile.mktemp(suffix='.xlsx')
        wb.save(tmp)
        object_key = f"data-process/{datetime.now().strftime('%Y%m%d')}/阿维塔专项_{month}_{task_id}.xlsx"
        url = upload_file(tmp, object_key)
        try:
            os.remove(tmp)
        except Exception:
            pass
        logger.info(f"[阿维塔] 结果表已生成并上传:task {task_id} -> {url}")
        return url