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

import json
from werkzeug import exceptions, url_decode
from odoo.http import Controller, route, request
from odoo.addons.report.controllers.main import ReportController


class CustomReportController(ReportController):

    #------------------------------------------------------
    # Report controllers
    #------------------------------------------------------
    @route([
        '/report/<converter>/<reportname>',
        '/report/<converter>/<reportname>/<docids>',
    ], type='http', auth='user', website=True)
    def report_routes(self, reportname, docids=None, converter=None, **data):
        report_obj = request.env['report']
        context = dict(request.env.context)

        if docids:
            docids = [int(i) for i in docids.split(',')]
        if data.get('options'):
            data.update(json.loads(data.pop('options')))
        if data.get('context'):
            # Ignore 'lang' here, because the context in data is the one from the webclient *but* if
            # the user explicitely wants to change the lang, this mechanism overwrites it.
            data['context'] = json.loads(data['context'])
            if data['context'].get('lang'):
                del data['context']['lang']
            context.update(data['context'])
        if converter == 'html':
            html = report_obj.with_context(context).get_html(docids, reportname, data=data)
            return request.make_response(html)
        elif converter == 'pdf':
            pdf = report_obj.with_context(context).get_pdf(docids, reportname, data=data)

            res_model = request.env['ir.actions.report.xml'].sudo().search([('report_name', '=', reportname)],
                                                                           limit=1).model
            res_id = docids[0]
            config = request.env['jd.digital.signature.config'].sudo().search([('model_id.model', '=', res_model)])
            if config:
                # 判断当前单据签名是否完成
                # 若所有签名已完成则进行pdf合成
                if request.env['jd.digital.signature.status'].is_signature_upload_finish(res_model, docids[0])[0]:

                    # 带证书的单据 若已生成签名单据则不允许再次生成
                    if config.is_certificate:
                        if not request.env['jd.digital.signature.util'].is_signature_finished(res_model, res_id):
                            request.env['jd.digital.signature.util'].create_signed_pdf(res_model, res_id)
                    else:
                        request.env['jd.digital.signature.util'].create_signed_pdf(res_model, res_id)

            pdfhttpheaders = [('Content-Type', 'application/pdf'), ('Content-Length', len(pdf))]
            return request.make_response(pdf, headers=pdfhttpheaders)
        else:
            raise exceptions.HTTPException(description='Converter %s not implemented.' % converter)