# -*- coding: utf-8 -*-
# Copyright 2018 JDG <www.yunside.com>
# Created by Carmen <carmen.ling@yunside.com> at 2018/7/2
from odoo import models, fields, api
from odoo.exceptions import ValidationError
from odoo.osv import expression
import datetime
import requests
import qrcode
import base64


class WizardQRCode(models.TransientModel):
    _name = 'jd.base.wizard.qr.code'
    _description = u'二维码展示框'
    _order = 'id asc'

    qr_code = fields.Binary('QRCode', readonly=True)

    @api.model
    def default_get(self, fields_list):
        result = {}
        secret_key = self.env.context.get('secret_key', None)
        login = self.env.context.get('login', None)
        system_rec = self.env.user.company_id.name
        if not system_rec:
            system_name = '玉龙微应用'
        else:
            system_name = system_rec
        url_string = 'otpauth://totp/{0}:{1}?secret={2}&issuer=JadeDragonTechnology' \
            .format(system_name, login, secret_key)
        from io import BytesIO
        qr = qrcode.QRCode(
            version=1,
            error_correction=qrcode.constants.ERROR_CORRECT_H,
            box_size=5,
            border=1)
        qr.add_data(url_string)
        img = qr.make_image()
        byte_io = BytesIO()
        img.save(byte_io, 'PNG')
        byte_io.seek(0)
        base64_data = base64.b64encode(byte_io.getvalue())
        result.update({
            'qr_code': base64_data,
        })
        return result

    @api.multi
    def do_confirm(self):
        pass
