# -*- coding: utf-8 -*-
# @File  : wizard_department_company_change.py
# Created by cx on 2020/7/7
# xuan.chen@yunside.com


from odoo import api, models, fields
from odoo.exceptions import ValidationError
import json

TYPE_CHANGE = [('add', u'新增组织'),
               ('remove', u'移除组织')]


class WizardDepartmentCompanyChange(models.TransientModel):
    _name = 'jd.base.wizard.department.company.change'
    _description = u'角色组用户组织变更'

    department_id = fields.Many2one('jd_base.department', string=u'角色组')
    type_change = fields.Selection(TYPE_CHANGE, string=u'变更类型', required=True, default='add')
    company_ids = fields.Many2many('res.company', 'rel_wizard_department_company_change_company', 'left_id', 'right_id',
                                   string=u'组织范围')

    @api.model
    def default_get(self, default_fields):
        result = super(WizardDepartmentCompanyChange, self).default_get(default_fields)
        department_id = self.env.context.get('department_id', None)
        result.update({
            'department_id': department_id
        })
        return result

    @api.multi
    def do_confirm(self):
        for item in self:
            if item.department_id and item.type_change and item.company_ids:
                cr = self.env.cr
                params = {
                    'department_id': item.department_id.id,
                    'wizard_id': item.id
                }
                if item.type_change == 'remove':
                    sql = '''
                    DELETE FROM res_company_users_rel rel
                    WHERE rel.user_id = ANY (array(SELECT rel.user_id
                                                   FROM jd_dep_user_ref rel
                                                   WHERE rel.dep_id = %(department_id)s))
                          AND rel.cid = ANY (array(SELECT rel.right_id
                                                   FROM rel_wizard_department_company_change_company rel
                                                   WHERE rel.left_id = %(wizard_id)s))
                    '''
                else:
                    sql = '''
                    DO $$
                    DECLARE
                      rec RECORD;
                    BEGIN
                      FOR rec IN (
                        SELECT
                          ur.user_id,
                          com.id AS company_id
                        FROM (
                               SELECT rel.user_id
                               FROM jd_dep_user_ref rel
                               WHERE rel.dep_id = %(department_id)s
                             ) ur
                          INNER JOIN (
                                       SELECT
                                         id,
                                         name
                                       FROM res_company com
                                       WHERE 1 = 1
                                             AND com.id = ANY (array(SELECT rel.right_id
                                                                     FROM rel_wizard_department_company_change_company rel
                                                                     WHERE rel.left_id = %(wizard_id)s))
                                     ) com ON 1 = 1
                          LEFT JOIN (
                                      SELECT
                                        rel.user_id AS user_id,
                                        rel.cid     AS company_id
                                      FROM res_company_users_rel rel
                                      WHERE rel.user_id = ANY (array(SELECT rel.user_id
                                                                     FROM jd_dep_user_ref rel
                                                                     WHERE rel.dep_id = %(department_id)s))
                                    ) rel ON rel.user_id = ur.user_id AND rel.company_id = com.id
                        WHERE rel.company_id ISNULL
                        ORDER BY ur.user_id, com.id
                      ) LOOP
                        INSERT INTO res_company_users_rel
                        (cid, user_id)
                        VALUES
                          (rec.company_id, rec.user_id);
                      END LOOP;
                    END;
                    $$
                    '''
                cr.execute(sql, params)