# -*- coding:utf-8 -*-
# Author: Perry_Zhu
from __future__ import unicode_literals

import pandas as pd
from sqlalchemy import create_engine

pd.options.mode.chained_assignment = None
import sys

reload(sys)
sys.setdefaultencoding('utf8')
engine_xyqb = create_engine('mysql+mysqldb://syzhu_data_r:ulk0989742097y43@192.168.4.6:8066/xyqb?charset=utf8',
                            echo=True)
engine_audit = create_engine('mysql+mysqldb://internal_r:ArbNgtvlJzZHXsEu@172.16.3.201:3306/test_shiyao?charset=utf8',
                             echo=True)

sql = """
  SELECT
    YEAR (t1.repaid_at) 打款年份,
        MONTH (t1.repaid_at) 打款月份,
        fc.`name` 资金方,
        sum(IFNULL(t1.current_repayment, 0)) 当期总额,
        sum(IFNULL(t1.principle, 0)) 当期本金,
        sum(IFNULL(t1.interest, 0)) 当期利息,
        sum(IFNULL(t1.prepay_fee, 0)) 提前还款服务费,
        sum(IFNULL(t1.funding_service_fee, 0)) 资金方服务费,
        sum(IFNULL(t1.punish_fee, 0)) 逾期罚息
    FROM
        funding_repayment_record t1
     JOIN basic.funding_corp fc ON t1.funding_code = fc.funding_code
    WHERE
        t1.repaid_at>='2015-01-01'
    AND t1.divide_status in(0,2)
    GROUP BY 1, 2, 3
"""
sql_yeepay_fenzhang = """
  SELECT
    YEAR (t1.repaid_at) 打款年份,
    	MONTH (t1.repaid_at) 打款月份,
    	concat(fc.`name`,'-易宝分账') 资金方,
        sum(IFNULL(t1.current_repayment, 0)) 当期总额,
    	sum(IFNULL(t1.principle, 0)) 当期本金,
    	sum(IFNULL(t1.interest, 0)) 当期利息,
    	sum(IFNULL(t1.prepay_fee, 0)) 提前还款服务费,
    	sum(IFNULL(t1.funding_service_fee, 0)) 资金方服务费,
    	sum(IFNULL(punish_fee, 0)) 逾期罚息

    FROM
    	funding_repayment_record t1
     JOIN basic.funding_corp fc ON t1.funding_code = fc.funding_code
    WHERE
    	t1.repaid_at>='2015-01-01'
    AND t1.divide_status in(1,2)
    AND t1.funding_code IN (290,330,390)
    GROUP BY 1, 2, 3
"""


def repay_funding_excel():
    df_yeepay = pd.read_sql(sql=sql_yeepay_fenzhang, con=engine_audit)
    df = pd.read_sql(sql=sql, con=engine_audit)
    df = df.append(df_yeepay)
    df.sort_values([u'打款年份', u'打款月份'])
    df.to_excel(u'E:/数据汇总/现金贷/还资金方表汇总2017-09_1027new.xlsx', index=None)


repay_funding_excel()
