# -*- encoding: utf-8 -*-
# -----------------------------------------------------------------------------
# @File Name  : report.py
# @Time       : 2020/11/18 下午3:19
# @Author     : X. Peng
# @Email      : acepengxiong@163.com
# @Software   : PyCharm
# -----------------------------------------------------------------------------
import datetime
import time
import uuid

import oss2
from flask_restful import Resource, reqparse
from flask import request, render_template
from flask import make_response

from app.api.engine import config
from app.utils.html_to_pdf import html_to_pdf
from app.api.engine import pdf_folder, redis, env, TAMP_SQL, tamp_diagnose_app_engine
from app.utils.jinjia2html_v2 import DataIntegrate


class ReportHandlers(Resource):
    """."""

    def __init__(self):
        """."""
        self.parser = reqparse.RequestParser()

    def get(self):
        """."""
        # self.parser.add_argument('ifa_id', type=str, required=True, help='ifa_id不能为空')
        self.parser.add_argument('customer_id', type=str, required=True, help='customer_id不能为空')
        args = self.parser.parse_args()
        token = request.headers.get('Authorization', '')
        token = 's:sid:' + token.split(' ')[1]
        ifa_id = redis.get(token).decode()
        if not ifa_id:
            return {"code":40005,"data":None,"lang":"zh_CN","msg":"请登陆"}
        ifa_id = ifa_id.replace('\'', '')
        customer_id = args['customer_id']
        pdf_name = str(uuid.uuid4()) + '.pdf'

        with TAMP_SQL(tamp_diagnose_app_engine) as tamp_diagnose_app:
            tamp_diagnose_app_session = tamp_diagnose_app.session
            sql = "update hold_report set update_time='{}', update_status='{}' where ifa_id='{}' and customer_id='{}'".format(
                datetime.datetime.now(),
                1,
                ifa_id,
                customer_id
            )
            tamp_diagnose_app_session.execute(sql)
        start = time.time()
        try:
            dt = DataIntegrate(ifa_id=ifa_id, customer_id=customer_id, pdf_name=pdf_name)
            dt.render_data()
        except:
            pass
        print('耗时{}秒'.format(round(time.time() - start, 2)))

        auth = oss2.Auth(config[env]['oss']['account'], config[env]['oss']['password'])
        # Endpoint以杭州为例，其它Region请按实际情况填写。
        bucket = oss2.Bucket(auth, 'http://oss-cn-shanghai.aliyuncs.com', 'tamperdev')

        # 生成下载文件的签名URL，有效时间为60s。
        path = bucket.sign_url('GET', 'productionenv/Start/' + pdf_name, 60)
        with TAMP_SQL(tamp_diagnose_app_engine) as tamp_diagnose_app:
            tamp_diagnose_app_session = tamp_diagnose_app.session
            sql = "update hold_report set update_time='{}', update_status='{}', file='{}' where ifa_id='{}' and customer_id='{}'".format(
                datetime.datetime.now(),
                2,
                pdf_name,
                ifa_id,
                customer_id
            )
            tamp_diagnose_app_session.execute(sql)
        resp = {
            "code": 0,
            "data": {
                "path": path
            },
            "lang": "zh_CN",
            "msg": "成功"
        }
        return resp

    def post(self):
        """."""
        pass

    def put(self, id):
        """."""
        pass

    def delete(self, id):
        """."""
        pass
