# encoding: utf8

import pandas as pd
from sqlalchemy import create_engine

engine_financial = create_engine(
    'mysql+mysqldb://mazhen:mazhen8uiplm091@172.20.4.13:3306/financial?charset=utf8',
    echo=True)

loan_start = '2015-01-01 00:00:00'
loan_end = '2017-01-01 00:00:00'
date_format = '%y-%m'

# sql = """
# select
#   t3.class 类别,
#   year(t1.loan_paid_at) 放款日期（年）,
#   month(t1.loan_paid_at) 放款日期（月）,
#   year(t2.deadline) 应还日期（年）,
#   month(t2.deadline) 应还日期（月）,
#   sum(t2.principle) 应还本金,
#   sum(t2.interest) 应还利息
# from
#   loan_manifest t1
#   inner join user_repayment_plan t2
#     on t1.ref_id = t2.ref_id
#     and t1.is_active in (1, - 2)
#     and t1.loan_paid_at >= '%s'
#     and t1.loan_paid_at < '%s'
#   inner join loan_class t3
#     on t1.ref_id = t3.ref_id
# group by t3.class,
#   date_format(t1.loan_paid_at, '%s'),
#   year(t2.deadline),
#   month(t2.deadline);
# """ % (loan_start, loan_end, date_format)

sql = """
select t3.class, year(t1.loan_paid_at),  month(t1.loan_paid_at),
year(t2.deadline),month(t2.deadline),sum(t2.principle),sum(t2.interest)
 from loan_manifest t1
inner join user_repayment_plan t2
on t1.loanid = t2.loanid and t1.is_active in (1,-2) and t1.loan_paid_at<'2017-01-01'
inner join loan_class t3
on t1.loanid = t3.loanid
group by t3.class,date_format(t1.loan_paid_at, '%%y-%%m'),year(t2.deadline),month(t2.deadline) 
"""

path_out = u'E:/财务/'

df = pd.read_sql(sql=sql, con=engine_financial)
df.to_excel(path_out + u'现金贷应收本金利息汇总_15_16.xlsx', index=None)