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

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

from odoo import fields, models, api
import pytz
from odoo import tools
from odoo.exceptions import ValidationError
from odoo.tools import config
from odoo.osv import expression
import re

_logger = logging.getLogger(__name__)

COLOR = [('red', u'红'), ('orange', u'橙'), ('green', u'绿'), ('balck', u'黑')]
STATE = [('draft', u'新建'), ('enable', u'发布'), ('disable', u'撤回'), ('discard', u'废弃')]


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.data.m'
    _name = "jd.notice"
    _description = u"通知公告"
    _order = 'is_top desc,write_date desc'
    _seq_prefix = 'JN'

    name = fields.Char(string=u'名称', store=True, compute='_get_name', required=False)
    date_start = fields.Date(string=u'生效日期', required=True, default=fields.Date.context_today)
    date_end = fields.Date(string=u'失效日期', required=True, default=fields.Date.context_today)

    state = fields.Selection(STATE, string=u'状态')
    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)
    image_background = fields.Binary(string=u'背景图', attachment=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'标签')
    attachment_ids = fields.One2many('jd.notice.file', 'notice_id', string=u'附件')
    # 用于记录是否置顶，默认不置顶
    is_top = fields.Boolean(u'置顶', default=False)

    @api.multi
    @api.constrains('date_start', 'date_end')
    def check_date(self):
        for item in self:
            if item.date_start > item.date_end:
                raise ValidationError(u'生效日期不允许大于失效日期')

    @api.model
    def create_default_sequence(self):
        force_company = self._context.get('force_company')
        if not force_company:
            force_company = self.env.user.company_id.id
        seq_code = str(self._name) + ('.%s' % force_company)
        seq_rec = self.env['ir.sequence'].sudo().search(
            ['&', ('code', '=', seq_code), ('company_id', '=', force_company)], limit=1)
        if not seq_rec:
            prefix = config.get('system_prefix', '').strip()
            company_str = ("000" + str(force_company))[-4:]
            prefix += str(self._seq_prefix) + company_str
            seq_val = {
                'name': seq_code,
                'code': seq_code,
                'prefix': prefix,
                'padding': 4,
                'company_id': force_company
            }
            seq_rec = self.env['ir.sequence'].sudo().create(seq_val)
        return seq_rec

    @api.multi
    @api.depends('state')
    def get_hide_edit_button(self):
        """
        编辑按钮可见性：根据状态控制编辑按钮可见性。子类中可以覆盖该方法添加更详细的控制条件。
        :return:
        """
        for item in self:
            item.hide_edit_button = True if item.state not in ('draft', 'disable') else False

    @api.multi
    @api.depends('company_id', 'categ_id', 'title')
    def _get_name(self):
        for item in self:
            item.name = '[%s]%s(%s~%s)' % (item.categ_id.name, item.title, item.date_start or 'Min', item.date_end
                                           or 'Max')
    
    @api.multi
    def to_top(self):
        '''
        点击置顶菜单时，改变该通知的置顶状态为真
        '''
        for item in self:
            item.is_top = True
            # model_obj = self.env['ir.model.data']
            # data_id = model_obj._get_id('jd_base', 'view_jd_notice_tree')
            # view_id = model_obj.browse(data_id).res_id
            # return {
            #     'type': 'ir.actions.client',
            #     # 'tag': 'reload',
            #     'name': self._description,
            #     'res_model': self._name,
            #     'view_type': 'tree',
            #     'view_mode': 'tree',
            #     # 'view_id': view_id,
            #     'target': 'current',
            #     'nodestroy': True,
            # }

    @api.multi
    def cancel_top(self):
        '''
        点击取消置顶菜单时，改变该通知的置顶状态为否
        '''
        for item in self:
            item.is_top = False
            # model_obj = self.env['ir.model.data']
            # data_id = model_obj._get_id('', 'view_jd_notice_tree')
            # view_id = model_obj.browse(data_id).res_id
            # return {
            #     'type': 'ir.actions.client',
            #     # 'tag': 'reload',
            #     'name': self._description,
            #     'res_model': self._name,
            #     'view_type': 'tree',
            #     'view_mode': 'tree',
            #     # 'view_id': view_id,
            #     'target': 'current',
            #     'nodestroy': True,
            # }

    @api.model
    def create(self, vals):
        new_vals = dict(vals)

        if new_vals.get('number', '/') == '/':
            seq_rec = self.create_default_sequence()
            new_vals.update({
                'number': seq_rec._next()
            })

        # 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')
    #     if 'content' in new_vals:
    #         content = new_vals['content']
    #         # 只替换新插入的图片
    #         if '<img src="' in content:
    #             def append_base_url(matched):
    #                 url = matched.group('value')
    #                 if url.startswith('/'):
    #                     url = base_url + url
    #                 return '<img src="%s"' % url
    #             content = re.sub(r'<img src="(?P<value>.*?)"', append_base_url, content)
    #             new_vals.update({'content': content})
    #     return super(Notice, self).write(new_vals)

    # @api.multi
    # def action_confirm(self):
    #     for item in self:
    #         if item.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(item.title, html2plaintext(item.content), 'announce',
    #         #                                               [775], categ_id)
    #         item.write({'state': 'confirm', 'send_date': sd})

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

    @api.model
    def notice_fetch(self, domain, limit=10):
        result = []
        domain = expression.AND([[('state', '=', 'enable')], domain])
        notice_list = self.search(domain, offset=0, limit=limit, order='is_top desc, time_enable desc')
        for notice in notice_list:
            tmp_date = datetime.strptime(notice.time_enable, 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='is_top desc, time_enable desc')
        for notice in notice_list:
            # 未确认的公告在手机端不显示
            if 'draft' == notice.state:
                continue

            tmp_date = datetime.strptime(notice.time_enable, 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 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)
    tag_color = fields.Selection(COLOR, string=u'颜色', 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)
