from odoo import fields, models


class ResMrpRoutingWorkcenter(models.Model):
    _inherit = 'mrp.routing.workcenter'

    routing_type = fields.Selection([
        ('获取CNC加工程序', '获取CNC加工程序'),
        ('装夹', '装夹'),
        ('前置三元定位检测', '前置三元定位检测'),
        ('CNC加工', 'CNC加工'),
        ('后置三元质量检测', '后置三元质量检测'),
        ('解除装夹', '解除装夹'),
        ('切割', '切割')
    ], string="工序类型")
    is_repeat = fields.Boolean('重复', default=False)
    workcenter_id = fields.Many2one('mrp.workcenter', required=False)
    workcenter_ids = fields.Many2many('mrp.workcenter', 'rel_workcenter_route', required=True)
    bom_id = fields.Many2one('mrp.bom', required=False)

    # 获得当前登陆者公司
    def get_company_id(self):
        self.company_id = self.env.user.company_id.id

    company_id = fields.Many2one('res.company', compute="get_company_id", related=False)

    # 工单对应的工作中心，根据工序中的工作中心去匹配，
    # 如果只配置了一个工作中心，则默认采用该工作中心；
    # 如果有多个工作中心，
    # 则根据该工作中心的工单个数进行分配（优先分配给工单个数最少的）；
    def get_workcenter(self, workcenter_ids):
        if workcenter_ids:
            if len(workcenter_ids) == 1:
                return workcenter_ids[0]
            elif len(workcenter_ids) >= 2:
                # workcenter_ids_str = ','.join([str(s) for s in workcenter_ids])
                self.env.cr.execute("""
                    SELECT  workcenter_id FROM mrp_workorder where workcenter_id 
                          in  %s group by workcenter_id 
                          order by count(*),workcenter_id asc limit 1 """, [tuple(workcenter_ids)])
                return self.env.cr.dictfetchall()[0].get('workcenter_id')
