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

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

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


class WizardUserCompanyChange(models.TransientModel):
    _name = 'jd.base.wizard.user.company.change'
    _description = u'用户组织变更'

    user_id = fields.Many2one('res.users', string=u'用户')
    type_change = fields.Selection(TYPE_CHANGE, string=u'变更类型', required=True, default='remove')
    company_ids = fields.Many2many('res.company', 'rel_wizard_user_company_change_company', 'left_id', 'right_id',
                                   string=u'组织范围')
    domain_company_ids = fields.Char(string=u'组织domain', compute='_get_domain_company_ids',
                                     default=json.dumps([('id', 'in', [0])]))

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

    @api.multi
    @api.depends('type_change')
    def _get_domain_company_ids(self):
        for item in self:
            cr = self.env.cr
            params = {
                'user_id': item.user_id.id or 0
            }
            if item.type_change == 'remove':
                sql = '''
                SELECT array_agg(rel.cid) AS company_ids
                FROM res_company_users_rel rel
                WHERE rel.user_id = %(user_id)s
                '''
            elif item.type_change == 'add':
                sql = '''
                SELECT array_agg(com.id) AS company_ids
                FROM res_company com
                  LEFT JOIN (
                              SELECT rel.cid AS company_id
                              FROM res_company_users_rel rel
                              WHERE rel.user_id = %(user_id)s
                            ) rel ON rel.company_id = com.id
                WHERE rel.company_id ISNULL
                '''
            else:
                sql = ''
            company_ids = []
            if sql:
                cr.execute(sql, params)
                rec = cr.dictfetchone()
                if rec and rec.get('company_ids'):
                    company_ids = rec.get('company_ids')
            if not company_ids:
                company_ids = [0]
            item.domain_company_ids = json.dumps(([('id', 'in', company_ids)]))

    @api.multi
    @api.onchange('type_change')
    def onchange_type_change(self):
        for item in self:
            item.company_ids = None

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