# -*- 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 NoticeFile(models.Model):
    _name = 'jd.notice.file'
    notice_id = fields.Many2one('jd.notice', u'通知公告')
    name = fields.Char(string=u'文件名称', default='/')
    file = fields.Binary(string=u'文件内容', attachment=True)


class Notice(models.Model):
    _inherit = 'jdg.abstract.base'
    _name = "jd.notice"
    _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)
    doc_num = fields.Char(u'文号')
    categ_id = fields.Many2one('jd.notice.category', string=u'栏目', index=True, required=True)
    tag_ids = fields.Many2many('jd.notice.tag', 'jd_notice_tag_ref', 'notice_id', 'tag_id', string=u'标签')
    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)
    attachment_ids = fields.One2many('jd.notice.file', 'notice_id', string=u'附件')
    # 用于记录是否置顶，默认不置顶
    top = fields.Boolean(u'置顶', default=False)


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

        base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url')
        if 'content' in new_vals:
            content = new_vals['content']
            if '<img src="' in content:
                content = content.replace('<img src="', '<img src="' + base_url)
                new_vals.update({'content': content})
        return super(Notice, self).create(new_vals)

    @api.multi
    def write(self, vals):
        new_vals = dict(vals)
        base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url')
        self.ensure_one()
        if 'content' in new_vals:
            content = new_vals['content']
            if '<img src="' in content:
                content = content.replace('<img src="', '<img src="' + base_url)
                new_vals.update({'content': content})
        return super(Notice, self).write(new_vals)

    @api.multi
    def unlink(self):
        for each in self:
            if each.state == 'confirm':
                raise exceptions.Warning(u'删除失败, 已经确认的通知公告不能删除')
        return super(Notice, self).unlink()

    @api.multi
    def action_confirm(self):
        for each in self:
            if each.state == 'confirm':
                raise exceptions.ValidationError(u'操作失败, 已经确认的通知公告不能再次签发！')
            sd = time.strftime(tools.DEFAULT_SERVER_DATETIME_FORMAT, time.gmtime())

            # 发送通知类型的消息，所有员工都应该收到通知公告
            # employee_dicts = self.env['hd.m.employee'].sudo().search_read([], ['partner_id'])
            # partner_ids = [employee_dict['partner_id'][0] for employee_dict in employee_dicts]
            # categ_id = self.env.ref('jd_base.message_category_07').id
            # self.env['jdg.abstract.message'].make_message(each.title, html2plaintext(each.content), 'announce',
            #                                               [775], categ_id)
            each.write({'state': 'confirm', 'send_date': sd})

    @api.multi
    def action_draft(self):
        for each in self:
            each.write({'state': 'draft'})

    @api.model
    def notice_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'))
            # 2016-11-16
            #send_date = tmp_date.strftime(tools.DEFAULT_SERVER_DATE_FORMAT)
            send_date = tmp_date.strftime("%Y/%m/%d")
            item = {
                'id': notice.id,
                'doc_num': notice.doc_num,
                'categ_name': notice.categ_id.name or '',
                'title': notice.title,
                'send_date': send_date,
                'url': '/v1/page/notice/detail?id=%d' % notice.id
            }
            result.append(item)
        return result

    def mobile_read_list(self, params):
        '''
        从JS读取巡查记录
        '''

        result = []
        page_count = 10
        page = int(params.get('page', 0))
        txt = params.get('txt')
        offset = page_count * page
        query = [('title', 'like', txt)]
        if page > 0:
            offset += 1
        notice_list = self.search(query, offset=offset, limit=page_count, order='send_date desc')
        for notice in notice_list:
            # 未确认的公告在手机端不显示
            if 'draft' == notice.state:
                continue

            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'))
            # 2016-11-16
            send_date = tmp_date.strftime(tools.DEFAULT_SERVER_DATE_FORMAT)

            item = {
                'id': notice.id,
                'doc_num': notice.doc_num,
                'categ_name': notice.categ_id.name or '',
                'title': notice.title,
                'send_date': send_date
            }
            result.append(item)

        return result

    @api.multi
    def on_top(self):
        '''
        点击置顶菜单时，改变该通知的置顶状态为真
        '''
        for each in self:
            each.top = True

    @api.multi
    def on_down(self):
        '''
        点击取消置顶菜单时，改变该通知的置顶状态为否
        '''
        for item in self:
            item.top = False

    @api.multi
    def get_raw_text(self):
        self.ensure_one()
        return self.content.split


class NoticeCategory(models.Model):
    _name = 'jd.notice.category'
    _description = u'公告栏目'

    number = fields.Char(u'编码', readonly=True, default='/')
    name = fields.Char(u'名称', index=True, required=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(NoticeCategory, self).create(vals)


class NoticeTag(models.Model):
    _name = 'jd.notice.tag'
    _description = u'公告标签'

    number = fields.Char(u'编码', readonly=True, default='/')
    name = fields.Char(u'名称', index=True, required=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(NoticeTag, self).create(vals)
