# -*- coding: utf-8 -*-
# 项目: jdg-hd-node-farm
# Copyright 2018 JDG <www.yunside.com>
# Created by LLH <lianghua.liu@yunside.com> at 2018/9/5

from odoo import models, fields, api
from odoo.exceptions import ValidationError
import logging

_logger = logging.getLogger(__name__)


class PushStrategy(models.Model):
    """
    凭证推送策略
    分为公司、凭证定义两个纬度
    """
    _name = 'jd.int.push.strategy'
    _description = u'推送策略'

    system_type = fields.Selection([
        ('sap', 'SAP'),
        ('bpm', 'BPM'),
        ('fssc', 'FSSC')
    ], string=u'推送系统', required=True, default='sap', help=u'不同的推送系统可能会对应不同的推送逻辑')
    active = fields.Boolean(string=u'有效', default=True)
    note = fields.Text(string=u'备注')
    company_line_ids = fields.One2many('jd.int.push.strategy.company', 'order_id', string=u'公司明细')
    voucher_line_ids = fields.One2many('jd.int.push.strategy.voucher', 'order_id', string=u'凭证明细')

    _sql_constraints = [
        ('system_uniq', 'unique (system_type)', u'该推送系统已有推送策略！')
    ]

    @api.multi
    def name_get(self):
        result = []
        for o in self:
            result.append((o.id, "%s(%s)" % ('推送策略', o.system_type)))
        return result

    @api.model
    def get_strategy_info(self, company_id, system_type, date=None):
        """
        返回指定公司的推送策略信息
        :param company_id:
        :param system_type:
        :param date:
        :return:
        """
        if isinstance(company_id, int):
            company_id = self.env['res.company'].browse(company_id)
        if not system_type:
            system_type = 'sap'
        if not date:
            date = fields.Date.context_today(self)
        cr = self.env.cr
        sql = '''
        SELECT
          psc.id                AS line_id,
          psc.bukrs             AS bukrs,
          -- 公司代码
          psc.prctr             AS prctr,
          -- 利润中心
          psc.kostl             AS kostl,
          -- 成本中心-制造费用
          psc.kostl_manager     AS kostl_manager,
          -- 成本中心-管理费用
          psc.date_start        AS date_start -- 开始推送日期
        FROM jd_int_push_strategy_company psc
        WHERE psc.order_id = (SELECT ps.id
                              FROM jd_int_push_strategy ps
                              WHERE ps.system_type = %(system_type)s
                                    AND ps.active = TRUE
                              ORDER BY ps.id DESC
                              LIMIT 1
        )
              AND psc.company_id = %(company_id)s
        LIMIT 1
        '''
        params = {
            'company_id': company_id.id,
            'system_type': system_type
        }
        cr.execute(sql, params)
        rec = cr.dictfetchone()
        if rec and rec.get('line_id'):
            date_start = rec.get('date_start')
            if date_start <= date:
                return rec
        return None


class PushStrategyCompany(models.Model):
    """
    凭证推送策略 公司明细
    """
    _name = 'jd.int.push.strategy.company'
    _description = u'推送策略公司明细'

    order_id = fields.Many2one('jd.int.push.strategy', string=u'推送策略', ondelete='cascade')
    company_id = fields.Many2one('res.company', string=u'公司', required=True)
    is_push = fields.Boolean(string=u'是否推送', default=True)
    date_start = fields.Date(string=u'开始推送日期', required=True, help=u'单据业务日期在此日期之前时，将不触发凭证推送')
    note = fields.Char(string=u'备注')


class PushStrategyVoucher(models.Model):
    """
    凭证推送策略 凭证明细
    """
    _name = 'jd.int.push.strategy.voucher'
    _description = u'推送策略凭证明细'

    order_id = fields.Many2one('jd.int.push.strategy', string=u'推送策略', ondelete='cascade')
    voucher_id = fields.Many2one('jd.int.voucher', string=u'凭证定义', required=True)
    res_model = fields.Char(string=u'来源单据模型', related='voucher_id.res_model', store=True)
    is_push = fields.Boolean(string=u'是否推送', default=True)
    push_trigger = fields.Selection([('confirm', u'确认'),
                                     ('audit', u'审核'),
                                     ('closed', u'关账')], string=u'推送触发动作', required=True, default='confirm')

