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

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

TYPE = [('digit', u'数字'),
        ('bool', u'布尔'),
        ('text', u'文本'),
        ('range', u'范围')]


class AbnormalInfo(models.Model):
    _name = 'jd.abnormal.info'
    _inherit = 'jdg.abstract.base.data.m'
    _description = u'异常预警'

    category_id = fields.Many2one('jd.abnormal.category', string=u'所属分类', required=True, ondelete='cascade')
    state = fields.Selection([('enable', u'启用'), ('disable', u'停用')], default='enable')

    name = fields.Char(string=u'异常预警')
    department_type_ids = fields.Char(string=u'对应岗位')
    method = fields.Char(string=u'执行方法', required=True)
    note = fields.Text(string=u'异常预警描述')

    line_ids = fields.One2many('jd.abnormal.info.line', 'parent_id', string=u'参数明细')

    @api.multi
    @api.depends('state')
    def get_hide_edit_button(self):
        for item in self:
            item.hide_edit_button = item.state == 'enable'
    
    @api.model
    def create(self, vals):
        number = vals.get('number', '/')
        if number == '/':
            number = self.env['ir.sequence'].next_by_code(self._name)
        vals.update({'number': number})
        return super(AbnormalInfo, self).create(vals)
    

class AbnormalInfoLine(models.Model):
    _name = 'jd.abnormal.info.line'
    _description = u'参数明细(异常预警)'

    parent_id = fields.Many2one('jd.abnormal.info', string=u'异常预警', required=True, ondelete='cascade')

    param_id = fields.Many2one('jd.abnormal.param', string=u'异常预警参数', required=True)
    number = fields.Char(string=u'参数编码')
    type = fields.Selection(TYPE, string=u'参数值类型', compute='_get_param_info', store=True,
                            help=u'范围类型参数由;(英文分号)分隔，左边为空则无穷小，右边为空则无穷大')

    value = fields.Char(string=u'参数值', required=True)
    note = fields.Text(string=u'备注')

    @api.model
    def create(self, vals):
        # number默认值为待办参数number
        if 'number' not in vals:
            number = self.env['jd.abnormal.param'].sudo().browse(int(vals['param_id'])).number
            vals.update({'number': number})
        return super(AbnormalInfoLine, self).create(vals)

    @api.multi
    @api.depends('param_id')
    def _get_param_info(self):
        for item in self:
            if item.param_id:
                item.number = item.param_id.number
                item.type = item.param_id.type
            else:
                item.number = False
                item.type = False

    @api.multi
    @api.constrains('type', 'value')
    def check_type(self):
        for item in self:
            param_id = item.param_id
            if item.type == 'digit':
                is_match = re.match(r'^\d+([\.]\d+){0,1}\d*$', item.value)
                if is_match is None:
                    raise ValidationError(u'参数【%s-%s】的类型为数字，当前值【%s】不匹配' % (param_id.name, param_id.number, item.value))
            elif item.type == 'bool' and not item.value in ('True', 'False'):
                raise ValidationError(
                    u'参数【%s-%s】的类型为布尔，当前值【%s】不匹配，请输入True或False' % (param_id.name, param_id.number, item.value))
            elif item.type == 'range':
                split_data = item.value.split(';')
                if len(split_data) != 2:
                    raise ValidationError(u'参数【%s-%s】的类型为范围，当前值【%s】不匹配\r\n请输入;(英文分号)分隔的范围值，如：0;10' % (
                    param_id.name, param_id.number, item.value))
                # elif not split_data[0] or not split_data[1]:
                #     raise ValidationError(u'参数【%s-%s】的类型为范围，当前值【%s】分号两边不允许存在空值' % (param_id.name, param_id.number, item.value))
