# -*- encoding: utf-8 -*-
# 项目：JDG-
# 模块名称：
# 描述：
# Copyright 2018 JDG <www.yunside.com>
# Created by wxh (xianhuo.weng@yunside.com) at  2019/11/25 - 4:09 PM

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

CHANNEL = [('sms', u'短信'), ('inner_msg', u'系统消息'), ('mail', u'邮件'), ('qywx', u'企业微信')]


class AbnormalPushSetting(models.Model):
    _name = 'jd.abnormal.push.setting'
    _inherit = 'jdg.abstract.base.data.m'
    _description = u'异常推送设置'
    """
    关联异常预警，设置该异常所推送的渠道、模板以及人员名单。
    限制：
    1、同一公司内，单条异常预警只能关联一个有效的异常推送设置。
    """

    name = fields.Char(compute='_get_name', store=True, required=False)

    abnormal_id = fields.Many2one('jd.abnormal.info', string=u'异常预警', required=True)
    state = fields.Selection(default='enable')
    department_type_ids = fields.Char(string=u'岗位', compute='_get_info', store=True)
    channel = fields.Selection(CHANNEL, string=u'推送渠道', required=True)
    template = fields.Text(string=u'推送模板', required=True)

    @api.model
    def create(self, values):
        if values.get('number', '/') == '/':
            values.update({
                'number': self.env['ir.sequence'].next_by_code(self._name)
            })
        return super(AbnormalPushSetting, self).create(values)
    
    @api.multi
    @api.constrains('state', 'abnormal_id')
    def check_unique(self):
        for item in self:
            rec = self.search([('state', '!=', 'discard'), ('abnormal_id', '=', item.abnormal_id.id), ('id', '!=', item.id)])
            if rec:
                raise ValidationError(u'已存在非废弃状态的【%s】记录' % item.abnormal_id.name)
    
    @api.multi
    @api.depends('abnormal_id')
    def _get_name(self):
        item = self[0]
        if item.abnormal_id:
            item.name = u'【%s】(%s)' % (item.abnormal_id.name, dict(CHANNEL).get(item.channel, u'无'))
        else:
            item.name = u'异常推送设置(%s)' % dict(CHANNEL).get(item.channel, u'无')

    @api.multi
    @api.depends('abnormal_id')
    def _get_info(self):
        item = self[0]
        item.department_type_ids = item.abnormal_id.department_type_ids

    @api.multi
    @api.onchange('template')
    def onchange_template(self):
        for item in self:
            template = item.template
            key_list = re.findall(r'{{#(.*?)}}', item.template)
            if key_list:
                for key in key_list:
                    template = template.replace(key, key.strip())
            item.template = template

    @api.multi
    @api.constrains('template')
    def check_template(self):
        for item in self:
            key_list = re.findall(r'{{#(.*?)}}', item.template)
            if key_list:
                for key in key_list:
                    if key != key.strip():
                        raise ValidationError(u'模板中的数据存在空格，请检查')

    @api.multi
    def get_content(self):
        item = self[0]
        values = item.abnormal_id[item.abnormal_id.method]()
        key_list = re.findall(r'{{#(.*?)}}', item.template)

        content = item.template
        if type(values) == dict:
            key_value_tuple = values.items()
            if len(key_value_tuple) > len(key_list):
                raise ValidationError(u'系统方法返回的【参数包含的信息】大于推送模板【参数总数】\r\n%s，请检查' % str(key_value_tuple))

            # 按照模板顺序进行文本组装
            for key in key_list:
                # 如果该模板明细有number则取值
                if key not in values:
                    raise ValidationError(u'系统方法返回的结果不包含与模板的值【%s】，无法进行匹配' % key)

                content = content.replace('{{#%s}}' % key, values[key]) + '\r\n'

        elif type(values) == list:
            for key in key_list:
                content = content.replace('{{#%s}}' % key, values.pop(0)) + '\r\n'

        return content
