# -*- coding: utf-8 -*-
import datetime
import sys
import pandas as pd
import os

sys.path.append('../../../finance_out_table')
from db_con.db_connect import sql_engine

path = '/home/quant_group/vpants/finance/table/'
engine_audit = sql_engine('audit', 'audit').get_engine()

sql = """
  SELECT
        year(lm.loan_paid_at) 放款年,
   		month(lm.loan_paid_at) 放款月,
        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
     join audit.loan_manifest lm on lm.ref_id=t1.ref_id
    WHERE
        t1.repaid_at>='2015-01-01'
    AND t1.divide_status in(0,2)
    GROUP BY 1, 2, 3,4,5
"""
sql_yeepay_fenzhang = """
  SELECT
        year(lm.loan_paid_at) 放款年,
   		month(lm.loan_paid_at) 放款月,
        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
     join audit.loan_manifest lm on lm.ref_id=t1.ref_id
    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,4,5
"""
sql_huijinsuo = """
  SELECT
        year(lm.loan_paid_at) 放款年,
   		month(lm.loan_paid_at) 放款月,
        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
     join audit.loan_manifest lm on lm.ref_id=t1.ref_id
    WHERE
    	t1.repaid_at>='2015-01-01'
    AND t1.divide_status=-1
    AND t1.funding_code =420
    GROUP BY 1, 2, 3,4,5
"""


class fund_repay():
    def __init__(self):
        today = datetime.date.today()
        self.end = datetime.date(today.year, today.month, 1)
        last_day = self.end + datetime.timedelta(days=-1)
        self.start = datetime.date(last_day.year, last_day.month, 1)
        self.dir_path = path + self.start.strftime('%Y%m')
        if not os.path.exists(self.dir_path):
            os.makedirs(self.dir_path)

    def fund_repay_details(self):
        df_yeepay = pd.read_sql(sql=sql_yeepay_fenzhang, con=engine_audit)
        df_com = pd.read_sql(sql=sql, con=engine_audit)
        df_hjs = pd.read_sql(sql=sql_huijinsuo, con=engine_audit)
        df = pd.concat([df_com, df_yeepay, df_hjs], ignore_index=True, axis=0)
        df.sort_values([u'打款年份', u'打款月份'])
        df.to_excel(os.path.join(self.dir_path, u'还资金方汇总表-{}.xlsx'.format(self.start.strftime('%Y%m'))), index=None)



if __name__ == '__main__':
    fund_repay().fund_repay_details()
    print('======================fund_repay done===================================')
