# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import fields, models, api, _
from odoo.exceptions import UserError
from datetime import datetime
from odoo.addons import decimal_precision as dp


class StockMove(models.Model):
    _inherit = "stock.move"

    pass_qty = fields.Float(string="Pass Qty", copy=False, digits=dp.get_precision('Product Unit of Measure'))
    fail_qty = fields.Float(string="Fail Qty", copy=False, digits=dp.get_precision('Product Unit of Measure'))
    fail_reason = fields.Char(string="Fail Reason", copy=False)
    rejection_num = fields.Float(string='拒收数量', copy=False, digits=dp.get_precision('Product Unit of Measure'))
    check_id = fields.Many2one('stock.quality.check', string="Quality Check")

    @api.multi
    def print_quality_check_report(self):
        action = self.env.ref('inward_quality.stock_quality_check_action')
        result = action.read()[0]
        if self.check_id:
            result['domain'] = "[('id','=',%s)]" % self.check_id.id
        return result


class Picking(models.Model):
    _inherit = "stock.picking"

    # @api.multi
    # def action_done(self):
    #     需求349
    #     349-去掉质量检测 功能多余
    #     res = super(Picking, self).action_done()
    #     for record in self:
    #         if record.picking_type_code == 'incoming' and record.state == 'done':
    #             for line in record.move_lines:
    #                 if line.fail_qty:
    #                     self.rejected_moves(line, context=None)
    #                 total_qty = line.pass_qty + line.fail_qty
    #                 if not total_qty == line.quantity_done:
    #                     raise UserError(_(u'合格和不合格的产品数量应该等于完成的数量 ( ' + (
    #                             line.product_id.default_code or '') + ' ' + (line.product_id.name) + ' )'))
    #                 if line.fail_qty and not line.fail_reason:
    #                     raise UserError(_(u'有一个失败的产品数量 (' + (line.product_id.default_code or '') + ' ' + (
    #                         line.product_id.name) + u') .所以请给出失败的原因。'))
    #                 qc_obj = self.env['stock.quality.check']
    #                 if not line.pass_qty and line.fail_qty:
    #                     qc_state = 'failed'
    #                 elif line.pass_qty and not line.fail_qty:
    #                     qc_state = 'passed'
    #                 elif line.pass_qty and line.fail_qty:
    #                     qc_state = 'partial'
    #                 if line.quantity_done:
    #                     create_vals = {
    #                         'product_id': line.product_id.id,
    #                         'partner_id': record.partner_id.id,
    #                         'done_qty': line.quantity_done,
    #                         'pass_qty': line.pass_qty,
    #                         'fail_qty': line.fail_qty,
    #                         'rejection_num': line.rejection_num,
    #                         'purchase_origin': self.origin,
    #                         'product_uom_id': line.product_uom.id,
    #                         'state': qc_state,
    #                         'date': fields.Date.today(),
    #                         'move_id': line.id,
    #                         'reason_of_failure': line.fail_reason,
    #                     }
    #                     new_check_id = qc_obj.create(create_vals)
    #                     if new_check_id:
    #                         line.write({'check_id': new_check_id.id})
    #     return res

    def rejected_moves(self, line, context=None):
        vals_obj = {}
        create_vals = {}
        move_line_list = []
        stock_move_obj = self.env['stock.move']
        dest_loc_id = self.env['ir.config_parameter'].sudo().get_param('inward_quality.rejection_location')
        if not dest_loc_id:
            raise UserError(_('请在被拒绝的位置中设置配置.'))

        total_fail_qty = line.fail_qty
        for move_line in line.move_line_ids:

            if total_fail_qty <= 0.00:
                break
            qty_done = min(total_fail_qty, move_line.qty_done)
            val = {
                'reference': self.name,
                'product_id': line.product_id.id,
                'product_uom_qty': 0,
                'product_uom_id': line.product_uom.id,
                'package_id': move_line.result_package_id.id,
                'qty_done': qty_done,
                'location_id': self.location_dest_id.id,
                'location_dest_id': dest_loc_id,
            }
            move_line_list.append((0, 0, val))
            total_fail_qty -= qty_done

        vals_obj = {
            'name': self.name,
            'product_id': line.product_id.id,
            'product_uom': line.product_uom.id,
            'product_uom_qty': line.fail_qty,
            'origin': line.product_id.name or '',
            'location_id': self.location_dest_id.id,
            'location_dest_id': dest_loc_id,
            'move_line_ids': move_line_list
        }
        new_id = stock_move_obj.create(vals_obj)
        new_id._action_done()


