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

from odoo import models, fields, api
from odoo.exceptions import ValidationError
from odoo.osv import expression
import datetime


class WizardOnChangeMethod(models.TransientModel):
    _name = 'jd.rpt.wizard.onchange.method'
    _description = u'onchange方法向导'
    _order = 'id asc'

    datasource_id = fields.Many2one('jd.table.datasource', string=u'数据源', readonly=True)
    line_id = fields.Many2one('jd.table.datasource.onchange.method.line', string=u'关联明细', readonly=True)
    method_code = fields.Text(string=u'方法代码')

    @api.model
    def default_get(self, fields):
        """
        :return:
        """
        res = super(WizardOnChangeMethod, self).default_get(fields)
        line = None
        if self.env.context.get('edit'):
            active_id = self.env.context.get('active_id', None)
            line = self.env['jd.table.datasource.onchange.method.line'].browse(active_id)
            datasource_id = line.parent_id.id
        else:
            active_id = self.env.context.get('active_id', None)
            datasource_id = active_id
        method_code = ""
        if line:
            method_code = line.method_code
        res.update({'datasource_id': datasource_id,
                    'line_id': line.id if line else False,
                    'method_code': method_code})
        return res

    @api.multi
    def do_confirm(self):
        """
        :return:
        """
        for item in self:
            if item.line_id:
                item.line_id.write({'method_code': item.method_code})
            else:
                line_vals = [(0, 0, {
                    'method_code': item.method_code
                })]
                item.datasource_id.onchange_method_line_ids = line_vals