# -*- 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


class TodoCategory(models.Model):
    _name = 'jd.todo.category'
    _inherit = 'jdg.abstract.base.data'
    _description = u'待办分类'

    sequence = fields.Integer(string=u'排序', default=9999)

    parent_id = fields.Many2one('jd.todo.category', string=u'上级分类')
    child_ids = fields.One2many('jd.todo.category', 'parent_id', string=u'子类')
    child_all_ids = fields.One2many('jd.todo.category', string=u'所有子类', compute='get_all_child_ids',
                                    help=u'该分类下所有子分类')

    todo_ids = fields.One2many('jd.todo.task', string=u'待办任务列表', compute='get_all_todo_task',
                               help=u'该分类下的所有待办，包括子分类的待办')
    
    @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(TodoCategory, self).create(vals)

    @api.multi
    def get_all_child_ids(self):
        """
        获取分类下所有子分类
        :return:
        """

        def get_all_child_ids(categ, child_ids):
            for c in categ.child_ids:
                child_ids.append(c.id)
                get_all_child_ids(c, child_ids)

        for each in self:
            all_child_ids = []
            for c in each.child_ids:
                get_all_child_ids(c, all_child_ids)
                all_child_ids.append(c.id)
            all_child_ids = list(set(all_child_ids))
            each.child_all_ids = all_child_ids

    @api.multi
    def get_all_todo_task(self):
        """
        获取该分类下（包括子分类）的所有待办
        :return:
        """
        for item in self:
            todo_ids = self.env['jd.todo.task'].sudo().search(
                [('category_id', 'in', item.child_all_ids.ids + [item.id]), ('state', '=', 'enable')])
            item.todo_ids = todo_ids.ids
