from odoo import fields, models
import logging


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)
    surface_technics_id = fields.Many2one('sf.production.process', string="表面工艺")

    # 获得当前登陆者公司
    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, routing_type, product):
        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])
                if routing_type == 'CNC加工':
                    workcenter = self.env['mrp.workcenter'].search([('id', 'in', workcenter_ids)])
                    workcenter_ids = []
                    for item in workcenter:
                        logging.info('get_workcenter-vals:%s' % item.machine_tool_id.name)
                        if item.machine_tool_id:
                            machine_tool = self.env['sf.machine_tool'].search(
                                [('x_axis', '>', product.bom_ids.bom_line_ids.product_id.length),
                                 ('y_axis', '>', product.bom_ids.bom_line_ids.product_id.width),
                                 ('z_axis', '>', product.bom_ids.bom_line_ids.product_id.height),
                                 ('id', '=', item.machine_tool_id.id)])
                            if machine_tool:
                                workcenter_ids.append(item.id)
                    if len(workcenter_ids) == 1:
                        return workcenter_ids[0]
                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)])
                res = self.env.cr.fetchone()
                if res:
                    workcenter_id = res[0]
                else:
                    workcenter_id = workcenter_ids[0]
                return workcenter_id
