# -*- 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 DashboardWidget(models.Model):
    _name = 'jd.dashboard.widget'
    _description = u'KPI部件'

    name = fields.Char(string=u'名称', required=True, index=True)
    image = fields.Binary(string=u'部件缩略图')
    type = fields.Selection([('0', u'列表'), ('1', u'图表'), ('2', u'卡片'), ('3', u'菜单'), ('4', u'文字')], string=u'类型', index=True,
                            required=True)
    width_default = fields.Integer(string=u'默认宽度', default=4, required=True)
    height_default = fields.Integer(string=u'默认高度', default=4, required=True)
    init_code = fields.Text(string=u'部件初始化')
    init_data = fields.Text(string=u'初始化数据')
    notes = fields.Text(string=u'描述')
    active = fields.Boolean(u'可用', required=True, index=True, default=True)

    @api.model
    def get_data(self, params):
        '''
        加载KPI部件数据
        :param params:
        :return:
        '''
        widget_id = int(params.get('widget_id', 0))
        widget = self.browse(widget_id)
        # model_name = widget.model.model
        # fields = []
        # fields_label = {}
        # for f in widget.field_ids:
        #     fields.append(f.field_id.name)
        #     fields_label.update({f.field_id.name: f.label})
        # result = self.env[model_name].search([], limit=10).read(fields)
        result = {}
        if widget.type == '0':
            return {'data': result, 'header': fields_label, 'type': widget.type, 'title': widget.title}
        elif widget.type == '1':
            return {'name': widget.name, 'type': widget.type, 'init_code': widget.init_code, 'init_data': widget.init_data}
        elif widget.type == '4':
            return {'type': widget.type, 'init_code': widget.init_code}

    @api.model
    def get_widget_list(self, params):
        '''
        获取KPI部件列表
        :param params:
        :return:
        '''
        page = int(params.get('page', 0))
        page_size = 10
        offset = page * page_size
        widgets = self.search([], offset=offset, limit=page)
        result = []
        for item in widgets:
            result.append({
                'title': item.name or '',
                'type': item.type,
                'notes': item.notes or '',
                'id': item.id,
                'widthDefault': item.width_default,
                'heightDefault': item.height_default,
                'init_data': item.init_data,
            })
        return result
