# -*- coding:utf-8 -*- 

# Copyright 2019/11/13 BWP 
# Created by yaoyao <mryao.com@gmail.com> at '2019/11/13  10:36 上午'

from odoo import models, api, tools, fields
from odoo.exceptions import ValidationError
import logging

_logger = logging.getLogger(__name__)


class DepartmentType(models.Model):
    _name = 'jd.department.type'
    _inherit = 'jdg.abstract.base.data'
    _description = u'角色组类型'

    company_id = fields.Many2one('res.company', string=u'组织', default=None)

    @api.multi
    @api.constrains('number')
    def check_number_unique(self):
        for item in self:
            rec = self.sudo().search([('number', '=', item.number), ('id', '!=', item.id)])
            if rec:
                raise ValidationError(u'编号重复！已存在角色组类型【%s】的编号为【%s】' % (rec.name, rec.number))

    @api.multi
    @api.depends('name')
    def name_get(self):
        """
        名称显示格式：[XXX]YYY
        :return:
        """
        result = []
        for record in self:
            result.append((record.id, record.name))
        return result

    @api.model
    def get_type_list(self):
        uid = self.env.user.id
        cr = self.env.cr
        sql = '''
                SELECT DISTINCT dt.number
                FROM jd_base_department dep
                    LEFT JOIN jd_department_type dt ON dep.type_id = dt.id
                    LEFT JOIN jd_dep_user_ref ref ON dep.id = ref.dep_id
                    LEFT JOIN res_users ru ON ref.user_id = ru.id 
                WHERE ru.id = %s
        '''
        cr.execute(sql, (uid,))
        result = cr.fetchall()
        result = map(lambda r: r[0], result)
        return result
