# -*- coding: utf-8 -*-
# Part of SmartGo. See LICENSE file for full copyright and licensing details.
import base64
from io import BytesIO
from odoo import api, fields, models
#from pystrich.code128 import Code128Encoder


class Tray(models.Model):
    _inherit = 'sf.tray'
    _description = '托盘'
    qr_image = fields.Binary(string="托盘二维码", compute='compute_qr_image')
    production_id = fields.Many2one('mrp.production', string='制造订单',
                                    related='workorder_id.production_id'
                                    )
    workorder_id = fields.Many2one('mrp.workorder', string="工单"
                                   )

    @api.onchange('production_id')
    def updateTrayState(self):
        if self.workorder_id != False and self.create_date != False:

            self.state = '占用'
        else:
            self.state = '空闲'

    #解绑托盘
    def unclamp(self):
        self.workorder_id = False
        self.production_id = False
        self.state = '空闲'

    @api.depends('code')
    def compute_qr_image(self):
        for item in self:
            if not item.code:
                item.qr_image = False
                continue
            # 根据code动态生成二维码图片
            # qr = qrcode.QRCode(
            #     version=1,
            #     error_correction=qrcode.constants.ERROR_CORRECT_L,
            #     box_size=10,
            #     border=4,
            # )
            # qr.add_data(item.code)
            # qr.make(fit=True)
            # img = qr.make_image()
            # 生成条形码文件
            # bar = barcode.get("ean13", "123456789102", writer=ImageWriter())
            # a = bar.get_fullcode()
            # b = bar.save('occ')
            # 生成条形码图片
            partner_encoder = Code128Encoder(item.code)
            # 转换bytes流
            temp = BytesIO()
            partner_encoder.save(temp)
            # img.save(temp, format='PNG')
            qr_image = base64.b64encode(temp.getvalue())
            item.qr_image = qr_image
