# -*- 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 TodoCommonList(models.Model):
    _name = 'jd.todo.common.list'
    _inherit = 'jdg.abstract.base.data.m'
    _description = u'待办事项列表'
    _order = 'priority asc'

    category_id = fields.Many2one('jd.todo.task.list.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'对应岗位')
    days_due = fields.Integer(string=u'逾期天数', default=1, required=True, help=u'待办应在逾期日期前完成。待办开始日期 + 逾期天数 = 逾期日期')
    priority = fields.Integer(string=u'优先级', default=100, help=u'在界面中优先显示，数值越小代表优先级越高', required=True)
    method = fields.Char(string=u'执行方法', required=True)
    note = fields.Text(string=u'待办任务描述')

    line_ids = fields.One2many('jd.todo.task.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(TodoCommonList, self).create(vals)

    @api.multi
    @api.constrains('line_ids')
    def check_line_number(self):
        item = self[0]
        number_list = []
        for line in item.line_ids:
            if line.number not in number_list:
                number_list.append(line.number)
            else:
                raise ValidationError(u'参数明细存在重复的编号【%s】，请检查' % line.number)

    @api.multi
    @api.constrains('method')
    def check_method_unique(self):
        for item in self:
            rec = self.sudo().search([('method', '=', item.method), ('id', '!=', item.id)])
            if rec:
                raise ValidationError(u'执行方法名重复，待办任务【%s】已使用方法名【%s】' % (rec.name, rec.method))
    
    @api.model
    def get_param_value(self, method_name):
        rec = self.sudo().search([('method', '=', method_name)])
        rec.ensure_one()
        result = {'todo_id': str(rec.id), 'days_due': str(rec.days_due)}
        for line_id in rec.line_ids:
            if line_id.type == 'text':
                result[line_id.number] = '\'' + line_id.value + '\''
            elif line_id.type == 'range':
                # 范围用法的定义：替换{{number_min}} {{number_max}}
                min_val, max_val = line_id.value.split(';')
                if not min_val.isdigit():
                    min_val = '\'' + min_val + '\''
                if not max_val.isdigit():
                    max_val = '\'' + max_val + '\''
                result[line_id.number + '_min'] = min_val
                result[line_id.number + '_max'] = max_val
            elif line_id.type == 'bool':
                result[line_id.number] = line_id.value.upper()
            else:
                result[line_id.number] = line_id.value
        return result


class TodoTaskLine(models.Model):
    _name = 'jd.todo.task.line'
    _description = u'参数明细(待办任务)'

    parent_id = fields.Many2one('jd.todo.task', string=u'待办任务', required=True, ondelete='cascade')

    param_id = fields.Many2one('jd.todo.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.todo.param'].sudo().browse(int(vals['param_id'])).number
            vals.update({'number': number})
        return super(TodoTaskLine, 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 item.value.upper() not 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))
