# -*- 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

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, http_dir
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":"请登陆"}
        if '\''in  ifa_id:
            ifa_id = ifa_id.replace('\'', '')
        if '\"'in  ifa_id:
            ifa_id = ifa_id.replace('\"', '')
        customer_id = args['customer_id']
        pdf_name = str(ifa_id) + str(customer_id) + '.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()
        check = 0
        try:
            dt = DataIntegrate(ifa_id=ifa_id, customer_id=customer_id, pdf_name=pdf_name)
            dt.render_data()
            check = 1
        except OSError:
            check = 1
        except:
            check = 0
        print('耗时{}秒'.format(round(time.time() - start, 2)))
        if check == 0:
            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(),
                    0,
                    ifa_id,
                    customer_id
                )
                tamp_diagnose_app_session.execute(sql)
            return {"code":-1, "msg": "内部错误"}

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

        # 生成下载文件的签名URL，有效时间为60s。
        # path = bucket.sign_url('GET', config[env]['oss']['path'] + pdf_name, config[env]['oss']['validtime'])

        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)
        
        with TAMP_SQL(tamp_diagnose_app_engine) as tamp_diagnose_app:
            
            tamp_diagnose_app_session = tamp_diagnose_app.session
            sql = "SELECT id, file, customer_id, ifa_id, update_status, update_time from hold_report where ifa_id='{}' and customer_id='{}'".format(
                ifa_id,
                customer_id,
            )
            ret = tamp_diagnose_app_session.execute(sql).fetchone()

        data = {"id":ret[0],"file": http_dir + ret[1],"customer_id":ret[2],
                        "ifa_id":ret[3],"update_status":ret[4],
                        "update_time":ret[5].strftime("%Y-%m-%d %H:%M:%S")}
        
        resp = {
            "code": 0,
            "data": data,
            "lang": "zh_CN",
            "msg": "成功"
        }
        
        return resp

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

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

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