# coding: utf-8

"""
找出所有 ifa
        找出 ifa 所有的客户
                           进行月报生成
"""

from app.api.engine import tamp_user_engine, tamp_order_engine, TAMP_SQL
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, String, Integer
from app.utils.jinjia2html import DataIntegrate

Base = declarative_base()
class IfaUser(Base):
    __tablename__ = "user_info"

    id = Column(String(64), primary_key=True)
    ui_username = Column(String(64))
    ui_sex = Column(String(64))
        
class Ifa_Customer(Base):
    __tablename__ = "ifa_customer"

    id = Column(String(64), primary_key=True)
    customer_id = Column(String(32))
    ifa_id = Column(String(64))
    
        
class Customer(Base):
    __tablename__ = "customer"

    id = Column(String(64), primary_key=True)
    customer_name = Column(String(128))



def call_month_report(ifauser_id, ifauser_name, customer_id, customer_name):
    print('开始制作IFA: {}, 客户: {}的基金月报'.format(ifauser_name, customer_name))
    try:
        DataIntegrate(ifauser_id, customer_id)
    except:
        print("发生异常，下一个走起！")



with TAMP_SQL(tamp_user_engine) as tamp_user, TAMP_SQL(tamp_order_engine) as tamp_order:
    tamp_user_session = tamp_user.session
    # 获取所有 ifauser
    ifausers = tamp_user_session.query(IfaUser).all()
    
    tamp_order_session = tamp_order.session
    # for ifauser in ifausers:
    for ifauser in ifausers[:5]:
    
        # 获取某个 ifa 的所有 customer
        customers = tamp_order_session.query(Ifa_Customer).\
                        filter_by(ifa_id = ifauser.id).all()
                        
        # 循环这个 ifa 的所有 customer
        for customer in customers:
            customer_full = tamp_order_session.query(Customer).\
                                            get(customer.customer_id)
            call_month_report(ifauser.id, ifauser.ui_username, customer_full.id, customer_full.customer_name)
