# encoding: utf8

import pandas as pd
from sqlalchemy import create_engine

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 < '2017-01-01'
  inner join loan_class t3
    on t1.ref_id = t3.ref_id
group by t3.class,
  date_format(t1.loan_paid_at, '%Y-%m'),
  year(t2.deadline),
  month(t2.deadline);
"""

engine_new_transaction = create_engine(
    'mysql+mysqldb://internal_r:ArbNgtvlJzZHXsEu@172.16.3.201:3306/temp?charset=utf8',
    echo=True)

path_out = u'E:/内控/'

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