# -*- coding:utf-8 -*-
# 项目: jdg-core-base
# Copyright 2018 JDG <www.yunside.com>
# Created by bjccdsrlcr (longjie.jiang@yunside.com) @ 2019/1/16

from odoo import models, fields, api
from odoo.http import request
from odoo.tools import config


class JdBillLog(models.Model):
    _name = 'jd.bill.log'
    _description = u'单据操作日志'
    _seq_prefix = 'BL'
    _order = 'id desc'

    number = fields.Char(string=u'编号', required=True, index=True, copy=False, default='/', readonly=True)
    company_id = fields.Many2one('res.company', string=u'组织', index=True, default=lambda self: self.env.user.company_id)
    note = fields.Text(string=u'备注')
    origin = fields.Reference(string=u'来源单据', selection='_reference_models', readonly=True)
    origin_number = fields.Char(string=u'来源单据编码', compute='_compute_origin_number', store=True)
    line_ids = fields.One2many('jd.bill.log.line', 'parent_id', string=u'操作明细')
    type = fields.Selection([('create', u'创建'),
                             ('write', u'编辑')], string=u'操作类型', default='create', required=True)
    operator_id = fields.Many2one('res.users', string=u'操作人')
    operator_time = fields.Datetime(string=u'操作时间')
    origin_terminal = fields.Char(string=u'来源终端')
    ip = fields.Char(string=u'ip地址')

    @api.depends('origin')
    @api.multi
    def _compute_origin_number(self):
        """
        冗余来源单据编号用于查询
        :return:
        """
        for record in self:
            record.origin_number = record.origin.number if record.origin else False

    @api.model
    def _reference_models(self):
        """
        所有单据的来源单据
        :return:
        """
        models = self.env['ir.model'].search([('state', '!=', 'manual')])
        return [(model.model, model.name)
                for model in models
                if not model.model.startswith('ir.')]

    @api.model
    def create_default_sequence(self):
        """
        :return: {object: ir_sequence}
        """
        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 + '%(y)s%(month)s%(day)s'
            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.model
    def create(self, values):
        """
        获取自动单号
        :param values:
        :return:
        """
        if values.get('number', '/') == '/':
            seq_rec = self.create_default_sequence()
            values.update({
                'number': seq_rec._next()
            })
        return super(JdBillLog, self).create(values)

    def create_log(self, origin, type, company_id, lines, operator_id, operator_time, origin_terminal, ip):
        """
        创建日志接口
        :return:
        """
        line_ids = []
        for line in lines:
            line_ids.append((0, 0, line))
        values = {
            'origin': origin,
            'company_id': company_id,
            'type': type,
            'operator_id': operator_id,
            'operator_time': operator_time,
            'origin_terminal': origin_terminal,
            'ip': ip,
            'line_ids': line_ids
        }
        if lines:
            self.env['jd.bill.log'].sudo().create(values)

    def _get_ipaddress(self):
        try:
            environ = request.httprequest.headers.environ
            return environ['REMOTE_ADDR']
        except Exception as e:
            return ''

    def _get_user_agent(self):
        # return hasattr(request, 'httprequest') and request.httprequest.headers.environ.get('HTTP_USER_AGENT')
        try:
            environ = request.httprequest.headers.environ
            return environ.get('HTTP_USER_AGENT')
        except Exception as e:
            return ''

class JdBillLogLine(models.Model):
    _name = 'jd.bill.log.line'
    _description = u'单据操作日志明细'
    _order = 'create_date desc'

    parent_id = fields.Many2one('jd.bill.log', string=u'所属日志', ondelete='cascade')
    field = fields.Char(string=u'字段名')
    field_cn = fields.Char(string=u'字段中文')
    value_before = fields.Text(string=u'修改前值', default='/')
    value_after = fields.Text(string=u'修改后值')

