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

from sqlalchemy import and_

from app.api.engine import TAMP_SQL, tamp_diagnose_app_engine
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 *

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 is not None
        )).first()
        default_template, default_data = None, None
        if type == 1:
            default_template = hold_default_template
            default_data = hold_default_data
        elif type == 2:
            default_template = diagnose_default_template
            default_data = diagnose_default_data
        if res:
            data = {**json.loads(res.get('default_template')), **default_data}
        else:
            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
        update_type = args.get('update_type')
        type = args.get('type')
        res = tamp_diagnose_session.query(FundReportManange).filter(and_(
            FundReportManange.ifa_id == args.get('ifa_id'),
            FundReportManange.type == type,
            FundReportManange.delete_tag == 0,
        ))
        if update_type == 1:
            # 更新默认模版
            if type == 1:
                args['name'] = '持仓报告默认模版'
            elif type == 2:
                args['name'] = '诊断报告默认模版'
            if res:
                res.update({
                    'default_template': args.get('default_template'),
                    'update_by': args.get('ifa_id'),
                    'update_time': datetime.datetime.now()
                })
            else:
                args['create_by'] = args.get('ifa_id')
                args['create_time'] = datetime.datetime.now()
                new_template = FundReportManange(**args)
                tamp_diagnose_session.add(new_template)
        elif update_type == 2:
            # 更新自定义模版
            args['update_by'] = args.get('ifa_id')
            args['update_time'] = datetime.datetime.now()
            res.update({
                'name': args.get('name'),
                'custom_template': args.get('custom_template'),
                '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
        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
        }

