# -*- coding: utf-8 -*-

import logging
import time
from datetime import datetime
from odoo.tools.mail import html2plaintext

from odoo import fields, models, api, exceptions
import pytz
from odoo import tools

_logger = logging.getLogger(__name__)


class NewsCategory(models.Model):
    _name = 'jd.news.category'
    _description = u'新闻分类'

    number = fields.Char(u'编码', readonly=True, default='/')
    name = fields.Char(u'名称', index=True, required=True)
    parent_id = fields.Many2one('jd.news.category', string=u'父类', index=True)

    @api.model
    def create(self, vals):
        if vals.get('number', '/') == '/':
            vals['number'] = self.env['ir.sequence'].sudo().next_by_code(self._name) or '/'
        return super(NewsCategory, self).create(vals)


class News(models.Model):
    _inherit = 'jdg.abstract.base'
    _name = "jd.news"
    _description = u"新闻动态"
    _order = 'top desc,send_date desc'

    number = fields.Char(u'编码', readonly=True, default='/')
    company_ids = fields.Many2many('res.company', 'jd_notice_company_ref', 'notice_id', 'company_id', string=u'公司')
    title = fields.Char(u'标题', required=True, index=True)
    content = fields.Html(u'内容', required=True)
    categ_id = fields.Many2one('jd.news.category', string=u'分类', index=True, required=True)
    send_date = fields.Datetime(u'发送日期', required=True,
                                default=lambda self: time.strftime(tools.DEFAULT_SERVER_DATETIME_FORMAT, time.gmtime()))
    state = fields.Selection([('draft', u'草稿'), ('confirm', u'确认')], u'状态', default='draft', index=True)
    # 用于记录是否置顶，默认不置顶
    top = fields.Boolean(u'置顶', default=False)

    @api.model
    def create(self, vals):
        if vals.get('number', '/') == '/':
            vals['number'] = self.env['ir.sequence'].sudo().next_by_code(self._name) or '/'
        return super(News, self).create(vals)

    @api.model
    def news_fetch(self, domain, limit=10):
        result = []
        notice_list = self.search(domain, offset=0, limit=limit, order='top desc,send_date desc')
        for notice in notice_list:
            tmp_date = datetime.strptime(notice.send_date, tools.DEFAULT_SERVER_DATETIME_FORMAT)
            # 时区加8个小时 2016-11-16 15:40:06+08:00
            tmp_date = tmp_date.replace(tzinfo=pytz.timezone('UTC')).astimezone(
                pytz.timezone('Asia/Shanghai'))
            send_date = tmp_date.strftime("%Y/%m/%d")
            item = {
                'id': notice.id,
                'categ_name': notice.categ_id.name or '',
                'title': notice.title,
                'send_date': send_date,
                'url': '/v1/page/notice/detail?id=%d&type=news' % notice.id
            }
            result.append(item)
        return result