import calendar
import requests
import logging
import datetime as date_time
from datetime import datetime
from odoo import models, fields, api, _
from odoo.exceptions import ValidationError
_logger = logging.getLogger(__name__)


class ProductIncomeExpense(models.Model):
    _name = "roke.product.income.expense"

    business_date = fields.Date(string="业务日期", index=True)
    abstract = fields.Text(string="摘要", index=True)
    income = fields.Float(string="收入")
    expenditure = fields.Float(string="支出")
    balance = fields.Float(string="结余", compute="_compute_balance", store=True)
    machinery_type = fields.Selection([("烘干桶", "烘干桶"), ("钣金", "钣金"), ("颗粒机", "颗粒机"), ("其他", "其他")],
                                      default="其他", string="类型", index=True)
    customer = fields.Char(string="客户", index=True)

    @api.depends("income", "expenditure")
    def _compute_balance(self):
        data = self.search([], order="business_date asc, create_date asc")
        for v in data:
            last_data = self.search([
                "|",
                "&",
                ("business_date", "=", v.business_date),
                ("create_date", "<", v.create_date),
                ("business_date", "<", v.business_date),
                ("id", "!=", v.id)
            ], limit=1, order="business_date desc, create_date desc")
            if not last_data:
                v.balance = round(0 + v.income - v.expenditure, 2)
            else:
                v.balance = round(last_data.balance + v.income - v.expenditure, 2)
    def update_all_balances(self):
        """定时任务手动批量更新所有记录的结余字段值"""
        # 确保记录按正确顺序处理（与计算逻辑保持一致）
        records = self.search([], order="business_date asc, create_date asc")

        # 关闭自动提交，提高批量处理性能
        self.env.cr.autocommit(False)
        try:
            # 调用计算方法
            records._compute_balance()
            # 手动提交事务
            self.env.cr.commit()
            return True
        except Exception as e:
            # 发生错误时回滚
            self.env.cr.rollback()
            _logger.error(f"更新结余字段失败: {str(e)}")
            return False
        finally:
            # 恢复自动提交设置
            self.env.cr.autocommit(True)
