from odoo import api, fields, models
from datetime import datetime
from collections import defaultdict
from odoo.addons.resource.models.resource import Intervals


class ResWorkcenter(models.Model):
    _inherit = "mrp.workcenter"
    machine_tool_id = fields.Many2one('sf.machine_tool', '机床')
    is_process_outsourcing = fields.Boolean('工艺外协')
    users_ids = fields.Many2many("res.users", 'users_workcenter')

    equipment_ids = fields.One2many(
        'maintenance.equipment', 'workcenter_id', string="Maintenance Equipment",
        check_company=True)

    # 查询工艺外协加工中心
    def get_process_outsourcing_workcenter(self):
        outsourcing_workcenter = self.env['mrp.workcenter'].search([('is_process_outsourcing', '=', True)])
        return outsourcing_workcenter.id

    @api.onchange('machine_tool_id')
    def update_machine_tool_is_binding(self):
        machine_tool = self.env["sf.machine_tool"].search([('is_binding', '=', True)])
        if machine_tool:
            for item in machine_tool:
                workcenter_machine_tool = self.env["mrp.workcenter"].search([('machine_tool_id', '=', item.id)])
                if workcenter_machine_tool:
                    if self.machine_tool_id.id:
                        if workcenter_machine_tool.id != self.machine_tool_id.id:
                            self.machine_tool_id.is_binding = True
                    else:
                        self.machine_tool_id.is_binding = True
                else:
                    self.machine_tool_id.is_binding = True
                    item.is_binding = False
        else:
            self.machine_tool_id.is_binding = True

    def action_work_order(self):
        if not self.env.context.get('desktop_list_view', False):
            action = self.env["ir.actions.actions"]._for_xml_id("sf_manufacturing.mrp_workorder_action_tablet")
            return action
        else:
            return super(ResWorkcenter, self).action_work_order()

    def _get_unavailability_intervals(self, start_datetime, end_datetime):
        res = super(ResWorkcenter, self)._get_unavailability_intervals(start_datetime, end_datetime)
        if not self:
            return res
        sql = """
           SELECT workcenter_id, ARRAY_AGG((schedule_date || '|' || schedule_date + INTERVAL '1h' * duration)) as date_intervals
           FROM maintenance_request
           LEFT JOIN maintenance_equipment
           ON maintenance_request.equipment_id = maintenance_equipment.id
               WHERE
               schedule_date IS NOT NULL
               AND duration IS NOT NULL
               AND equipment_id IS NOT NULL
               AND maintenance_equipment.workcenter_id IS NOT NULL
               AND maintenance_equipment.workcenter_id IN %s
               AND (schedule_date, schedule_date + INT ERVAL '1h' * duration) OVERLAPS (%s, %s)
           GROUP BY maintenance_equipment.workcenter_id;
           """
        self.env.cr.execute(sql, [tuple(self.ids), fields.Datetime.to_string(start_datetime.astimezone()),
                                  fields.Datetime.to_string(end_datetime.astimezone())])
        res_maintenance = defaultdict(list)
        for wc_row in self.env.cr.dictfetchall():
            res_maintenance[wc_row.get('workcenter_id')] = [
                [fields.Datetime.to_datetime(i) for i in intervals.split('|')]
                for intervals in wc_row.get('date_intervals')
            ]

        for wc_id in self.ids:
            intervals_previous_list = [(s.timestamp(), e.timestamp(), self.env['maintenance.request']) for s, e in
                                       res[wc_id]]
            intervals_maintenances_list = [(m[0].timestamp(), m[1].timestamp(), self.env['maintenance.request']) for m
                                           in res_maintenance[wc_id]]
            final_intervals_wc = Intervals(intervals_previous_list + intervals_maintenances_list)
            res[wc_id] = [(datetime.fromtimestamp(s), datetime.fromtimestamp(e)) for s, e, _ in final_intervals_wc]
        return res


class ResWorkcenterProductivity(models.Model):
    _inherit = 'mrp.workcenter.productivity'
    workcenter_id = fields.Many2one('mrp.workcenter', required=False)
