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

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):
    """"""
    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.id == args.get('id'),
            FundReportManange.delete_tag == 0,
        )).first()
        if not res:
            return False
        type = res.type
        default_template, default_data = None, None
        if res.default_template:
            default_template = res.default_template
        elif res.custom_template:
            default_template = res.custom_template
        if type == 1:
            default_data = hold_default_data
        elif type == 2:
            default_data = diagnose_default_data
        data = {**json.loads(default_template), **default_data}
        return data

def add_template(args):
    """新建模版"""
    type = args.get('type')
    custom_template = json.loads(args.get('custom_template'))
    with TAMP_SQL(tamp_diagnose_app_engine) as tamp_diagnose_app:
        tamp_diagnose_session = tamp_diagnose_app.session
        args['id'] = str(uuid.uuid4())
        if type == 1:
            allowed_keys = hold_default_template.keys()
            for key in list(custom_template.keys()):
                if key not in allowed_keys:
                    custom_template.pop(key)
        elif type == 2:
            allowed_keys = diagnose_default_template.keys()
            for key in list(custom_template.keys()):
                if key not in allowed_keys:
                    custom_template.pop(key)
        args['custom_template'] = json.dumps(custom_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):
    """更新模版"""
    template_data = json.loads(args.get('template_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.id == args.get('id'),
            FundReportManange.delete_tag == 0,
        ))
        if not res:
            return False
        if res[0].default_template:
            allowed_keys = json.loads(res[0].default_template).keys()
            for key in list(template_data.keys()):
                if key not in allowed_keys:
                    template_data.pop(key)
            # 更新默认模版
            res.update({
                'default_template': json.dumps(template_data),
                'update_by': args.get('ifa_id'),
                'update_time': datetime.datetime.now()
            })
        else:
            allowed_keys = json.loads(res[0].custom_template).keys()
            for key in list(template_data.keys()):
                if key not in allowed_keys:
                    template_data.pop(key)
            # 更新自定义模版
            args['update_by'] = args.get('ifa_id')
            args['update_time'] = datetime.datetime.now()
            res.update({
                'custom_template': json.dumps(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.order_by(FundReportManange.create_time.desc()).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
        type = res.first().type
        tamp_diagnose_session.query(FundReportManange).filter(FundReportManange.type==type).update({
            'default': 0
        })
        r = res.update({
            'default': 1
        })
        if r > 0:
            return True
        return False

