import calendar
import requests
import datetime as date_time
from datetime import datetime
from odoo import models, fields, api, _
from odoo.exceptions import ValidationError


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

    business_date = fields.Date(string="业务日期")
    abstract = fields.Text(string="摘要")
    income = fields.Float(string="收入")
    expenditure = fields.Float(string="支出")
    balance = fields.Float(string="结余", compute="_compute_balance")

    @api.depends("income", "expenditure")
    def _compute_balance(self):
        data = self.search([("id", "in", self.ids)], 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 = 0 + v.income - v.expenditure
            else:
                v.balance = last_data.balance + v.income - v.expenditure
