import pandas as pd
from typing import Dict, Any
import os
from .rpa_complete_ import ExcelWriter
from .ikea_status import task_status_to_str


class RpaBackfillingRecong:
    def __init__(self, order_path: str):
        # 预加载订单表
        self.order_df = None
        order_file = order_path
        if os.path.exists(order_file):
            self.order_df = pd.read_excel(order_file, dtype=str)
            # 转换日期格式
            if 'transdate' in self.order_df.columns:
                self.order_df['transdate'] = pd.to_datetime(self.order_df['transdate'], format='%Y%m%d').dt.strftime('%Y-%m-%d')
            else:
                self.order_df['transdate'] = ''

    def _data_mapper(self, task: Dict[str, Any]) -> Dict[str, Any]:
        log = ''
        if self.order_df is None:
            log = "订单表未加载，请检查订单表.xlsx文件是否存在\n"
            raise ValueError(log)

        meta = task['meta']
        
        # 匹配参考号
        ref_no = meta.get('ums_receipt_info', {}).get('参考号', '')
        matched_row = self.order_df[self.order_df['traceno'] == ref_no]
        
        if matched_row.empty:
            log = f"参考号{ref_no}不存在，请从银联小票中查询并修正\n"
            return [None] * 8 + [log] + [None] * 11
            
        # 提取匹配的行数据
        transdate = matched_row['transdate'].values[0]
        order_amount = matched_row['order_amount'].values[0]
        should_amount = matched_row['should_amount'].values[0]
        chl_discount = matched_row['chl_discount'].values[0]
        termid = matched_row['termid'].values[0]
        
        # 返回指定格式的数组
        return {
            '交易时间': transdate,
            '参考号': ref_no,
            '终端号': termid,
            '顾客姓名': meta.get('invoice_info', {}).get('购买方名称', ''),
            '交易金额': order_amount,
            '顾客实付金额': should_amount,
            '政府补贴金额': chl_discount,
            '已回款金额': None,
            '状态': log + ';' + task_status_to_str(meta['status']),
            '宜家发票号': meta.get('invoice_info', {}).get('发票号码', ''),
            '含税发票金额': None,
            '宜家订单号': meta.get('invoice_info', {}).get('宜家订单号', ''),
            '宜家收银小票含税金额': None,
            '宜家产品金额': None,
            '宜家服务费': None,
            '宜家SPA/Coupon金额': None,
            '差额(发票与银联交易)': None,
            '差额(发票与宜家交易)': None,
            '差额（银联交易-宜家交易）': None,
            '回款差额': None
        }


class Handler:
    def __init__(self, xlsx_path: str, order_path: str):
        """
        初始化处理类
        :param xlsx_path: xlsx文件路径
        :param order_path: 订单
        """
        self.xlsx_path = xlsx_path
        self._writer = ExcelWriter(data_mapper=RpaBackfillingRecong(order_path=order_path), xlsx_path=xlsx_path)

    def doh(self, task_info: dict):
        """
        处理任务
        :param task_info: 任务信息
        """
        self._writer.write_to_excel(task_info)

