# -*- coding: utf-8 -*-
# Copyright 2018 JDG <www.yunside.com>
# Created by YGJ <guojian.ye@yunside.com> at 2018/7/30

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

STATE = [('draft', u'新建'), ('enable', u'启用'), ('disable', u'停用'), ('discard', u'废弃')]


class JDBaseWizardBaseDataBatchToggle(models.Model):
    _name = 'jd.base.wizard.base.data.batch.toggle'
    _description = u'批量启用/停用主数据'

    line_ids = fields.One2many('jd.base.wizard.base.data.batch.toggle.line', 'order_id', string=u'批量处理明细')

    @api.model
    def default_get(self, default_fields):
        result = super(JDBaseWizardBaseDataBatchToggle, self).default_get(default_fields)
        active_ids = self.env.context.get('active_ids')
        active_model = self.env.context.get('active_model')
        lines = []
        for active_id in active_ids:
            rec = self.env[active_model].browse(active_id)
            lines.append((0, 0, {
                'origin': '%s,%d' % (active_model, active_id),
                'number': rec.number,
                'name': rec.name,
                'state': rec.state,
            }))
        result.update({
            'line_ids': lines
        })
        return result

    @api.multi
    def do_multi_enable(self):
        for item in self:
            if item.line_ids:
                for line in item.line_ids:
                    if line.origin.state == 'draft' or line.origin.state == 'disable':
                        line.origin.do_enable()

    @api.multi
    def do_multi_disable(self):
        for item in self:
            if item.line_ids:
                for line in item.line_ids:
                    if line.origin.state == 'enable':
                        line.origin.do_disable()


class JDBaseWizardBaseDataBatchToggleLine(models.Model):
    _name = 'jd.base.wizard.base.data.batch.toggle.line'
    _description = u'批量启用/停用主数据明细'

    order_id = fields.Many2one('jd.base.wizard.base.data.batch.toggle', string=u'批量处理向导')
    origin = fields.Reference(string=u'源数据', selection='_reference_models', readonly=True)
    number = fields.Char(string=u'编码', readonly=True)
    name = fields.Char(string=u'名称', readonly=True)
    state = fields.Selection(STATE, string=u'状态', readonly=True)

    @api.model
    def _reference_models(self):
        ref_models = self.env['ir.model'].search([('state', '!=', 'manual')])
        return [(model.model, model.name)
                for model in ref_models
                if not model.model.startswith('ir.')]
