from __future__ import print_function
import volcenginesdkbilling
from volcenginesdkcore.rest import ApiException


class BillClient:
    """账单服务客户端"""
    
    def __init__(self):
        self._api_instance = volcenginesdkbilling.BILLINGApi()
    
    def list_bill_detail(self, bill_period, expense_date, group_period=1, group_term=2, ignore_zero=1, limit=300):
        try:
            list_bill_detail_request = volcenginesdkbilling.ListBillDetailRequest(
                bill_period=bill_period,
                expense_date=expense_date,
                group_period=group_period,
                group_term=group_term,
                ignore_zero=ignore_zero,
                limit=limit,
            )

            response = self._api_instance.list_bill_detail(list_bill_detail_request)

            if hasattr(response, 'list') and response.list:
                bill_list = response.list
                total_cost = 0
                bill_data = []

                for item in bill_list:
                    expense_date_item = getattr(item, 'expense_date', 'N/A')
                    product_zh = getattr(item, 'product_zh', 'N/A')
                    billing_mode = getattr(item, 'billing_mode', 'N/A')
                    payable_amount = float(getattr(item, 'payable_amount', 0) or 0)

                    if payable_amount > 0:
                        bill_data.append({
                            'date': expense_date_item,
                            'product': product_zh,
                            'billing_mode': billing_mode,
                            'amount': payable_amount
                        })
                        total_cost += payable_amount

                return {
                    'success': True,
                    'bill_period': bill_period,
                    'expense_date': expense_date,
                    'total_cost': total_cost,
                    'bill_count': len(bill_data),
                    'bill_data': bill_data
                }
            else:
                return {
                    'success': False,
                    'error': '未找到账单数据'
                }

        except ApiException as e:
            return {
                'success': False,
                'error': f'API调用异常: {str(e)}'
            }
        except Exception as e:
            return {
                'success': False,
                'error': f'其他异常: {str(e)}'
            }
