# -*- coding:utf-8 -*-
"""
目标：
    现金贷按照资金方、用户等级、放款时间、deadline统计每月到期本息
数据库：
    all_back_0731
    根据不同时段的需求，选取不同阶段的备份数据库
字段名：
   资金方，风险等级（ABC），放款年，放款月，到期年，到期月，客户应还本金，客户应还利息
注意：
    筛选条件is_active的选择
"""
# Author: Perry_Zhu
from __future__ import unicode_literals

import pandas as pd

from db_con.db_connect import sql_engine

pd.options.mode.chained_assignment = None
import sys

reload(sys)
sys.setdefaultencoding('utf8')
engine_back0731 = sql_engine('all_back_0731').get_engine()
file_path = u'E:/审计出表/现金贷/'

query_sql = """
SELECT
	fund.`name` 资金方,
	class.class 风险等级,
	YEAR (loan.loan_paid_at) 放款年,
	MONTH (loan.loan_paid_at) 放款月,
	YEAR (plan.deadline) 到期年,
	MONTH (plan.deadline) 到期月,
	SUM(plan.principle) 客户应还本金,
	SUM(plan.interest) 客户应还利息
FROM
	user_repayment_plan plan
JOIN loan_manifest loan ON plan.ref_id = loan.ref_id
JOIN basic.loan_class_test class ON class.ref_id = loan.ref_id
JOIN funding_corp fund ON fund.funding_code = loan.funding_code
WHERE loan.is_active in (1,-2)
GROUP BY 1,2,3,4,5,6
"""

df = pd.read_sql(query_sql, engine_back0731)
if len(df) > 0:
    df.to_excel(file_path + '核算还资金方到期本金汇总.xlsx', index=None)
