# -*- 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_new_transaction = sql_engine('audit', 'new_transaction').get_engine()

sql_repay = """
select 
  t8.ref_id,
  year(t8.loan_paid_at) l_year,
  month(t8.loan_paid_at) l_month,
  year(t1.bill_time) r_year,
  month(t1.bill_time) r_month,
  t2.deadline '应还日期',
  t6.name funding_name,
  t7.approach_name,
  sum(t1.ref_amount) 总额,
  sum(t1.principle) 本金,
  sum(t1.interest) 利息,
  sum(t1.service_fee) 服务费,
  sum(t1.collection_relief) 催收减免,
  sum(t1.punish) 逾期罚款收益,
  sum(t1.remain_income) 其他收益,
  sum(mitigate_principle) 减免本金,
  sum(mitigate_interest) 减免利息,
  sum(mitigate_service_fee) 减免服务费,
  sum(mitigate_collection_relief) 减免罚息,
  sum(t1.residual_service_fee) 剩余未还服务费,
  sum(t1.subsidy_fee) 还款补贴,
  sum(t1.mitigate_subsidy_fee) 还款补贴减免,
  sum(t1.premium) 保费,
  sum(t1.mitigate_premium) 保费减免 
from
  new_transaction.xjd_repay_plan_repay_record_ref t1 
  join new_transaction.user_repayment_plan t2 
    on t2.id = t1.plan_id 
  join basic.funding_corp t6 
    on t2.fund_code = t6.funding_code and t6.`funding_code`=420
  join new_transaction.repay_channel t7 
    on t1.repay_channel = t7.id 
  join audit.loan_manifest t8 
    on t8.ref_id = t2.ref_id 
    and t8.loan_paid_at <  '2018-01-03' 
  where t1.bill_time >= {} and t1.bill_time < {}
group by 1, 2, 3, 4, 5, 6;
"""

sql_dunjiao_serivce_fee = """
select 
  year (t3.loan_paid_at) l_year,
  month (t3.loan_paid_at) l_month,
  year (t4.bill_time) r_year,
  month (t4.bill_time) r_month,
  t5.NAME funding_name,
  t6.approach_name,
  sum(t1.ref_amount) "实还趸收服务费" 
from
  new_transaction.xjd_dunjiao_plan_ref t1 
  join new_transaction.xjd_dunjiao_plan t2 
    on t1.plan_id = t2.id 
  join audit.loan_manifest t3 
    on t2.ref_id = t3.ref_id 
  join repay_record_online t4 
    on t1.record_id = t4.id 
  join basic.funding_corp t5 
    on t5.funding_code = 150 
  join new_transaction.repay_channel t6 
    on t6.id = t1.repay_channel 
    and t4.pay_approach = t1.repay_channel 
group by 1, 2, 3, 4, 5, 6 
"""
sort_cols = ['l_year', 'l_month', 'r_year', 'r_month', 'funding_name', 'approach_name']
new_cols = {'l_year': u'放款年', 'l_month': u'放款月', 'r_year': u'还款年', 'r_month': u'还款月', 'funding_name': u'资金方',
            'approach_name': u'收款账户'}

out_cols = ['ref_id', u'放款年', u'放款月', u'还款年', u'还款月',u'应还日期', u'资金方', u'收款账户', u'总额', u'本金', u'利息', u'服务费', u'催收减免', u'逾期罚款收益', u'其他收益',
            u'减免本金', u'减免利息', u'减免服务费', u'减免罚息', u'剩余未还服务费', u'实还趸收服务费', u'还款补贴', u'还款补贴减免', u'保费', u'保费减免']


class huijinsuo_loan_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 huijinsuo_loan_repay_details(self):
        begin_time = self.start.strftime("'%Y-%m-%d'")
        end_time = self.end.strftime("'%Y-%m-%d'")
        df_old = pd.read_sql(sql=sql_repay.format(begin_time, end_time), con=engine_new_transaction)
        df_dunjiao = pd.read_sql(sql=sql_dunjiao_serivce_fee, con=engine_new_transaction)

        df_old = pd.merge(df_old, df_dunjiao, how='left',
                          on=['l_year', 'l_month', 'r_year', 'r_month', 'funding_name', 'approach_name'])
        df_old[u'实还趸收服务费'].fillna(value=0, inplace=True)
        df_old[u'总额'] = df_old[u'总额'] + df_old[u'实还趸收服务费']
        df_old.sort_values(sort_cols, inplace=True)
        df_old.rename(columns=new_cols, inplace=True)


        excel_file = pd.ExcelWriter(os.path.join(self.dir_path , u'惠金所还款表汇总-{}.xlsx'.format(self.start.strftime('%Y%m'))))

        df_old.to_excel(excel_file, u'旧模式', columns=out_cols, index=None)
        excel_file.save()


if __name__ == '__main__':
    huijinsuo_loan_repay().huijinsuo_loan_repay_details()
    print('======================huijinsuo_loan_repay done===================================')
