# -*- encoding: utf-8 -*-
# -----------------------------------------------------------------------------
# @File Name  : template_manage_service.py
# @Time       : 2021/1/8 下午5:26
# @Author     : X. Peng
# @Email      : acepengxiong@163.com
# @Software   : PyCharm
# -----------------------------------------------------------------------------
import datetime
import json
import time
import uuid

import oss2
from ftfy import fix_text

from sqlalchemy import and_

from app.api.engine import TAMP_SQL, tamp_diagnose_app_engine, config, env
from app.config.default_template_params import hold_default_template, hold_default_data, diagnose_default_data, \
    diagnose_default_template
from app.model.tamp_diagnose_app import *
from app.utils.jinjia2html_v2 import DataIntegrate


def get_default_template(args):
    """"""
    type = args.get('type')
    data = []
    with TAMP_SQL(tamp_diagnose_app_engine) as tamp_diagnose_app:
        tamp_diagnose_session = tamp_diagnose_app.session
        res = tamp_diagnose_session.query(FundReportManange).filter(and_(
            FundReportManange.ifa_id == args.get('ifa_id'),
            FundReportManange.type == type,
            FundReportManange.delete_tag == 0,
            FundReportManange.default_template.isnot(None)
        )).first()
        if not res:
            return False
        default_template, default_data = None, None
        if type == 1:
            args['name'] = '持仓报告默认模版'
            default_template = hold_default_template
            default_data = hold_default_data
        elif type == 2:
            args['name'] = '诊断报告默认模版'
            default_template = diagnose_default_template
            default_data = diagnose_default_data
        if res.default_template:
            data = {'id': res.id, 'template_data': {**json.loads(res.default_template), **default_data}}
        else:
            args['id'] = str(uuid.uuid4())
            args['default_template'] = json.dumps(default_template)
            args['create_by'] = args.get('ifa_id')
            args['create_time'] = datetime.datetime.now()
            new_template = FundReportManange(**args)
            tamp_diagnose_session.add(new_template)
            data = {**default_template, **default_data}
        return data

def add_template(args):
    """新建模版"""
    with TAMP_SQL(tamp_diagnose_app_engine) as tamp_diagnose_app:
        tamp_diagnose_session = tamp_diagnose_app.session
        args['id'] = str(uuid.uuid4())
        args['default_template'] = json.dumps(hold_default_template)
        args['create_by'] = args.get('ifa_id')
        args['create_time'] = datetime.datetime.now()
        fund_report_manange = FundReportManange(**args)
        tamp_diagnose_session.add(fund_report_manange)

def update_template(args):
    """更新模版"""
    with TAMP_SQL(tamp_diagnose_app_engine) as tamp_diagnose_app:
        tamp_diagnose_session = tamp_diagnose_app.session
        res = tamp_diagnose_session.query(FundReportManange).filter(and_(
            FundReportManange.id == args.get('id'),
            FundReportManange.delete_tag == 0,
        ))
        if not res:
            return False
        if res[0].default_template:
            # 更新默认模版
            res.update({
                'default_template': args.get('template_data'),
                'update_by': args.get('ifa_id'),
                'update_time': datetime.datetime.now()
            })
        else:
            # 更新自定义模版
            args['update_by'] = args.get('ifa_id')
            args['update_time'] = datetime.datetime.now()
            res.update({
                'custom_template': args.get('template_data'),
                'update_by': args.get('ifa_id'),
                'update_time': datetime.datetime.now()
            })
    return True


def delete_template(args):
    """."""
    with TAMP_SQL(tamp_diagnose_app_engine) as tamp_diagnose_app:
        tamp_diagnose_session = tamp_diagnose_app.session
        res = tamp_diagnose_session.query(FundReportManange).filter(and_(
            FundReportManange.id == args.get('id'),
            FundReportManange.ifa_id == args.get('ifa_id')
        )).update({
            'delete_tag': 1,
            'update_by': args.get('ifa_id'),
            'update_time': datetime.datetime.now()
        })
        if res > 0:
            return True
        return False


def get_template_list(args):
    """."""
    pageNumber = args['pageNumber']
    pageSize = args['pageSize']
    offset = (pageNumber - 1) * pageSize
    dtype = args.get('type')
    name = args.get('name', '')
    conditions = [
        FundReportManange.delete_tag == 0,
        FundReportManange.ifa_id == args.get('ifa_id')
    ]
    if name:
        conditions.append(FundReportManange.name.like('%' + name + '%'))
    if dtype != 0:
        conditions.append(FundReportManange.type == args.get('type'))
    with TAMP_SQL(tamp_diagnose_app_engine) as tamp_diagnose_app:
        tamp_diagnose_session = tamp_diagnose_app.session
        # 新增默认模版
        res1 = tamp_diagnose_session.query(FundReportManange).filter(and_(
            FundReportManange.ifa_id == args.get('ifa_id'),
            FundReportManange.delete_tag == 0,
            FundReportManange.default_template.isnot(None)
        ))
        if not res1:
            return False
        need_type = {1, 2}
        exist_type = set()
        for r in res1:
            exist_type.add(r.type)
        add_type = list(need_type - exist_type)
        name, default_template = None, None
        for t in add_type:
            if t == 1:
                name = '持仓报告默认模版'
                default_template = hold_default_template
            elif t == 2:
                name = '诊断报告默认模版'
                default_template = diagnose_default_template
            id = str(uuid.uuid4())
            default_template = json.dumps(default_template)
            create_by = args.get('ifa_id')
            create_time = datetime.datetime.now()
            new_template = FundReportManange(id=id, ifa_id=args.get('ifa_id'), name=name, default_template=default_template, type=t, create_by=create_by, create_time=create_time, default=1)
            tamp_diagnose_session.add(new_template)
        res = tamp_diagnose_session.query(FundReportManange).filter(and_(
                *conditions
            ))
        if not res:
            return False
        totalSize = res.count()
        data = res.offset(offset).limit(pageSize)
        data = [r.to_dict() for r in data]
        return {
            'content': data,
            'pageNum': pageNumber,
            'pageSize': pageSize,
            'totalSize': totalSize
        }


def get_make_report_data(args):
    """获取制作模版数据."""
    id = args.get('id')
    ifa_id = args.get('ifa_id')
    customer_id = args.get('customer_id')
    template = ''
    type = 1
    with TAMP_SQL(tamp_diagnose_app_engine) as tamp_diagnose_app:
        tamp_diagnose_session = tamp_diagnose_app.session
        res = tamp_diagnose_session.query(FundReportManange).filter(and_(
            FundReportManange.id == id,
            FundReportManange.delete_tag == 0
        )).first()
        if not res:
            return False
        type = res.type
        template = res.default_template
        if not template:
            template = res.custom_template
        template = json.loads(template)
    # dt = DataIntegrate(ifa_id=ifa_id, customer_id=customer_id, type=type)
    # data = dt.get_template_data(template)
    data = template
    return data


def set_default_template(args):
    """."""
    with TAMP_SQL(tamp_diagnose_app_engine) as tamp_diagnose_app:
        tamp_diagnose_session = tamp_diagnose_app.session
        res = tamp_diagnose_session.query(FundReportManange).filter(and_(
            FundReportManange.id == args.get('id'),
            FundReportManange.delete_tag == 0,
            FundReportManange.ifa_id == args.get('ifa_id')
        ))
        if not res:
            return False
        tamp_diagnose_session.query(FundReportManange).update({
            'default': 0
        })
        r = res.update({
            'default': 1
        })
        if r > 0:
            return True
        return False


def make_report(args):
    """制作报告."""
    ifa_id = args.get('ifa_id')
    customer_id = args.get('customer_id')
    type = args.get('type')
    name = args.get('name')
    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, type=type)

        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)
