# -*- coding: utf-8 -*-
import logging
import time
from datetime import datetime
from odoo.tools.mail import html2plaintext
import json
from odoo import fields, models, api, exceptions
import pytz
from odoo import tools

_logger = logging.getLogger(__name__)


class DashboardPageConfig(models.Model):
    _name = 'jd.dashboard.kpi.view'
    _description = u'驾驶舱配置'

    name = fields.Char(string=u"页面名称", required=True)
    menu_id = fields.Many2one("ir.ui.menu", string=u"对应菜单")
    # compute_menu_name = fields.Char(compute='_compute_complete_name', string=u'菜单完整路径')
    background_style = fields.Char(string=u'页面背景')
    # items = fields.Text(u'布局配置')
    items_ids = fields.One2many('jd.dashboard.kpi.widget.object', 'parent_id', string=u'看板实例列表', copy=True)

    # @api.depends('menu_id')
    # def _compute_complete_name(self):
    #     for menu in self:
    #         menu.compute_menu_name = menu.menu_id.complete_name

    @api.model
    def create_or_update(self, values):
        '''
        保存驾驶舱配置
        :param values:
        :return:
        '''
        # items = json.dumps(values['items'])
        items = values['items']
        action_id = values.get('action_id', None)
        background_style = values.get('background_style', 'F0EEEE')
        if action_id:
            item_ids = []
            domain = [('menu_id.action', '=', '%s,%s' % ('ir.actions.client', action_id))]
            old_values = self.search(domain)
            if len(old_values) > 0:
                for record in old_values[0].items_ids:
                    # 存在则更新
                    if items.get(record.name, None):
                        item_ids.append((1, record.id, {
                            'name': record.name,
                            'config_based': json.dumps(items[record.name]),
                        }))
                        # 删除已添加到更新列表的值
                        items.pop(record.name)
                    # 不存在则删除
                    else:
                        item_ids.append((2, record.id))
                for item in items:
                    # 剩下的都是需要新增的
                    item_ids.append((0, 0, {
                        'name': item,
                        'mark': items[item]['title'],
                        'config_based': json.dumps(items[item])
                    }))
                # print item_ids
                old_values[0].write({
                    'background_style': background_style,
                    'items_ids': item_ids
                })
                # old_values[0].write({'items': items, 'background_style': background_style})

        else:
            return []

    @api.model
    def load_items(self, params):
        '''
        加载驾驶舱配置
        :return:
        '''
        action_id = params.get('action_id', None)
        if action_id:
            domain = [('menu_id.action', '=', '%s,%s' % ('ir.actions.client', action_id))]
            old_values = self.search(domain)
            if len(old_values) > 0:
                items = []
                for item in old_values[0].items_ids:
                    items.append({
                        'config_based': json.loads(item.config_based),
                        'config_advanced': item.config_advanced
                    })
                items = items if items else []
                # items = json.loads(old_values[0].items) if old_values[0].items else []
                background_style = old_values[0].background_style if old_values[0].background_style else 'f0eeee'
                return {
                    'items': items,
                    'background_style': background_style,
                }
        return []


class DashboardPageConfigItems(models.Model):
    _name = 'jd.dashboard.kpi.widget.object'
    _description = u'KPI部件对象列表'

    parent_id = fields.Many2one('jd.dashboard.kpi.view', string=u'驾驶舱配置')

    name = fields.Char(string=u'实例ID', readonly=True, index=True)
    mark = fields.Char(string=u'名称标识')
    config_based = fields.Text(string=u"基础配置", required=True)
    config_advanced = fields.Char(string=u"高级配置(js)")