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

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


class LockRange(models.Model):
    _name = 'jd.lock.range'
    _inherit = 'jdg.abstract.base.biz'
    _description = u'锁单范围设置'
    _seq_prefix = 'LR'

    date_start = fields.Date(string=u'开始日期', required=True)
    date_end = fields.Date(string=u'结束日期', required=True)
    company_id = fields.Many2one('res.company', string=u'组织', default=None)
    model_ids = fields.Many2many('ir.model', 'rel_jd_lock_range_ir_model', 'left_id', 'right_id', string=u'单据范围')
    company_ids = fields.Many2many('res.company', 'rel_jd_lock_range_res_company', 'left_id', 'right_id',
                                   string=u'组织范围')
    domain_model_ids = fields.Char(string=u'单据范围domain', compute='_get_domain_model_ids',
                                   default=json.dumps([('id', 'in', [0])]))
    domain_company_ids = fields.Char(string=u'组织范围domain', compute='_get_domain_company_ids',
                                     default=json.dumps([('id', 'in', [0])]))

    @api.model
    def get_domain_model_ids(self):
        base_biz_class = self.env['jdg.abstract.base.biz'].__class__
        model_ids = []
        model_recs = self.env['ir.model'].sudo().search(
            [('model', 'not like', 'ir.'), ('model', 'not like', 'wizard.'), ('model', 'not like', 'abstract')])
        for rec in model_recs:
            if rec.model in self.env and issubclass(self.env[rec.model].__class__, base_biz_class):
                model_ids.append(rec.id)
        return model_ids

    @api.multi
    @api.depends('company_id')
    def _get_domain_model_ids(self):
        """
        只能选择继承了业务单据基类的模型
        :return:
        """
        for item in self:
            model_ids = item.get_domain_model_ids()
            if not model_ids:
                model_ids = [0]
            item.domain_model_ids = json.dumps([('id', 'in', model_ids)])

    @api.multi
    @api.depends('company_id')
    def _get_domain_company_ids(self):
        """
        只能选择种猪场、服务部
        :return:
        """
        for item in self:
            prefix = config.get('system_prefix', '').strip()
            if prefix == 'B':
                domain = [('org_type', 'in', ('branch', 'breeding'))]
            elif prefix == 'F':
                domain = [('org_type', 'in', ('branch', 'svc'))]
            else:
                domain = [('org_type', 'in', ('branch',))]
            item.domain_company_ids = json.dumps(domain)

    @api.multi
    def select_model(self):
        """
        全选单据
        :return:
        """
        for item in self:
            item.model_ids = None
            model_ids = item.get_domain_model_ids()
            if model_ids:
                item.model_ids = [(6, 0, model_ids)]

    @api.multi
    def delete_model(self):
        for item in self:
            item.model_ids = None

    @api.multi
    def select_company(self):
        """
        全选单据
        :return:
        """
        for item in self:
            item.company_ids = None
            cr = self.env.cr
            sql = '''
            SELECT array_agg(com.id) AS company_ids
            FROM res_company com
            WHERE com.org_type = ANY (%(org_type)s)
            '''
            prefix = config.get('system_prefix', '').strip()
            if prefix == 'B':
                org_type = ['branch', 'breeding']
            elif prefix == 'F':
                org_type = ['branch', 'svc']
            else:
                org_type = ['branch']
            cr.execute(sql, {'org_type': org_type})
            rec = cr.dictfetchone()
            if rec and rec.get('company_ids'):
                company_ids = rec.get('company_ids')
                item.company_ids = [(6, 0, company_ids)]

    @api.multi
    def delete_company(self):
        for item in self:
            item.company_ids = None

    @api.multi
    def verify_data(self):
        for item in self:
            if not item.model_ids:
                raise ValidationError(u'请填写需锁定的单据')
            cr = self.env.cr
            sql = '''
            SELECT 
              lr.number,
              lr.date_start,
              lr.date_end
            FROM jd_lock_range lr
            WHERE lr.state != 'cancel'
              AND lr.date_start <= %(date_end)s
              AND lr.date_end >= %(date_start)s
              AND lr.id != %(record_id)s
            LIMIT 1
            '''
            params = {
                'date_start': item.date_start,
                'date_end': item.date_end,
                'record_id': item.id
            }
            cr.execute(sql, params)
            rec = cr.dictfetchone()
            if rec and rec.get('number'):
                raise ValidationError(u'锁单范围不能重复。错误详情如下：\r\n'
                                      u'已存在生效时间段为【%s ～ %s】锁单范围设置【%s】\r\n'
                                      u'当前单据的生效时间段【%s ～ %s】与其存在重叠范围\r\n请重新设置当前单据的生效时间段'
                                      % (rec.get('date_start'), rec.get('date_end'), rec.get('number'),
                                         item.date_start, item.date_end))

    @api.multi
    def do_confirm(self):
        for item in self:
            item.verify_data()
        super(LockRange, self).do_confirm()

    @api.multi
    def do_audit(self):
        for item in self:
            item.verify_data()
        super(LockRange, self).do_audit()
