# Copyright 2020-21 ForgeFlow S.L.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).

from odoo import api, fields, models


class RmaOrderLine(models.Model):
    _inherit = "rma.order.line"

    @api.depends("repair_ids", "repair_type", "repair_ids.state", "qty_to_receive")
    def _compute_qty_to_repair(self):
        for line in self:
            if line.repair_type == "no":
                line.qty_to_repair = 0.0
            elif line.repair_type == "ordered":
                qty = line._get_rma_repaired_qty() + line._get_rma_under_repair_qty()
                line.qty_to_repair = max(line.product_qty - qty, 0)
            elif line.repair_type == "received":
                qty = line._get_rma_repaired_qty() + line._get_rma_under_repair_qty()
                line.qty_to_repair = max(line.qty_received - qty, 0)
            else:
                line.qty_to_repair = 0.0

    @api.depends("repair_ids", "repair_type", "repair_ids.state", "qty_to_receive")
    def _compute_qty_repaired(self):
        for line in self:
            line.qty_repaired = line._get_rma_repaired_qty()

    @api.depends("repair_ids", "repair_type", "repair_ids.state", "qty_to_receive")
    def _compute_qty_under_repair(self):
        for line in self:
            line.qty_under_repair = line._get_rma_under_repair_qty()

    @api.depends("repair_ids")
    def _compute_repair_count(self):
        for line in self:
            line.repair_count = len(line.repair_ids)

    def _compute_repair_transfer_count(self):
        for line in self:
            pickings = line.move_ids.filtered(
                lambda m: m.is_rma_repair_transfer
            ).mapped("picking_id")
            line.repair_transfer_count = len(pickings)

    repair_ids = fields.One2many(
        comodel_name="repair.order",
        inverse_name="rma_line_id",
        string="Repair Orders",
        readonly=True,
        states={"draft": [("readonly", False)]},
        copy=False,
    )
    qty_to_repair = fields.Float(
        copy=False,
        digits="Product Unit of Measure",
        readonly=True,
        compute="_compute_qty_to_repair",
        store=True,
    )
    qty_under_repair = fields.Float(
        copy=False,
        digits="Product Unit of Measure",
        readonly=True,
        compute="_compute_qty_under_repair",
        store=True,
    )
    qty_repaired = fields.Float(
        copy=False,
        digits="Product Unit of Measure",
        readonly=True,
        compute="_compute_qty_repaired",
        store=True,
        help="Quantity repaired or being repaired.",
    )
    repair_type = fields.Selection(
        selection=[
            ("no", "Not required"),
            ("ordered", "Based on Ordered Quantities"),
            ("received", "Based on Received Quantities"),
        ],
        string="Repair Policy",
        default="no",
        required=True,
    )
    repair_count = fields.Integer(
        compute="_compute_repair_count", string="# of Repairs"
    )

    repair_transfer_count = fields.Integer(
        compute="_compute_repair_transfer_count", string="# of Repair Transfers"
    )

    delivery_policy = fields.Selection(
        selection_add=[("repair", "Based on Repair Quantities")],
        ondelete={"repair": lambda recs: recs.write({"delivery_policy": "no"})},
    )
    qty_to_pay = fields.Float(
        compute="_compute_qty_to_pay",
        digits="Product Unit of Measure",
    )

    @api.depends(
        "delivery_policy",
        "product_qty",
        "type",
        "repair_ids",
        "repair_ids.state",
        "repair_ids.invoice_method",
        "repair_type",
        "repair_ids.invoice_id",
        "repair_ids.invoice_id.payment_state",
    )
    def _compute_qty_to_pay(self):
        for rec in self:
            qty_to_pay = 0.0
            if rec.delivery_policy == "repair":
                for repair in rec.repair_ids.filtered(
                    lambda r: r.invoice_method != "none"
                    and r.invoice_id
                    and r.invoice_id.state != "cancel"
                    and r.invoice_id.payment_state in ["not_paid", "partial"]
                ):
                    qty_to_pay += self.uom_id._compute_quantity(
                        repair.product_qty, repair.product_uom
                    )
            rec.qty_to_pay = qty_to_pay

    def action_view_repair_order(self):
        action = self.env.ref("repair.action_repair_order_tree")
        result = action.sudo().read()[0]
        repair_ids = self.repair_ids.ids
        if len(repair_ids) != 1:
            result["domain"] = [("id", "in", repair_ids)]
        elif len(repair_ids) == 1:
            res = self.env.ref("repair.view_repair_order_form", False)
            result["views"] = [(res and res.id or False, "form")]
            result["res_id"] = repair_ids[0]
        return result

    def action_rma_cancel(self):
        res = super().action_rma_cancel()
        for line in self:
            line.repair_ids.action_repair_cancel()
        return res

    def _get_rma_repaired_qty(self):
        self.ensure_one()
        qty = 0.0
        for repair in self.repair_ids.filtered(lambda p: p.state == "done"):
            repair_qty = self.uom_id._compute_quantity(
                repair.product_qty, repair.product_uom
            )
            qty += repair_qty
        return qty

    def _get_rma_under_repair_qty(self):
        self.ensure_one()
        qty = 0.0
        for repair in self.repair_ids.filtered(
            lambda p: p.state not in ("cancel", "done")
        ):
            repair_qty = self.uom_id._compute_quantity(
                repair.product_qty, repair.product_uom
            )
            qty += repair_qty
        return qty

    @api.onchange("operation_id")
    def _onchange_operation_id(self):
        result = super(RmaOrderLine, self)._onchange_operation_id()
        if self.operation_id:
            self.repair_type = self.operation_id.repair_type or "no"
        return result

    @api.depends(
        "move_ids",
        "move_ids.state",
        "delivery_policy",
        "product_qty",
        "type",
        "qty_delivered",
        "qty_received",
        "repair_ids",
        "repair_type",
        "repair_ids.state",
        "qty_to_pay",
        "repair_ids.invoice_id",
        "repair_ids.payment_state",
    )
    def _compute_qty_to_deliver(self):
        res = super(RmaOrderLine, self)._compute_qty_to_deliver()
        for rec in self.filtered(lambda l: l.delivery_policy == "repair"):
            rec.qty_to_deliver = rec.qty_repaired - rec.qty_delivered
        return res

    def action_view_repair_transfers(self):
        action = self.env.ref("stock.action_picking_tree_all")
        result = action.sudo().read()[0]
        pickings = self.env["stock.picking"]
        for line in self:
            pickings |= line.move_ids.filtered(
                lambda m: m.is_rma_repair_transfer
            ).mapped("picking_id")
        # choose the view_mode accordingly
        if len(pickings) != 1:
            result["domain"] = "[('id', 'in', " + str(pickings.ids) + ")]"
        elif len(pickings) == 1:
            res = self.env.ref("stock.view_picking_form", False)
            result["views"] = [(res and res.id or False, "form")]
            result["res_id"] = pickings.ids[0]
        return result
