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


repay_sql = '''
select 
  t1.bill_time ,
  t6.name funding_name ,
  t7.approach_name ,
  sum(t1.ref_amount) sum_amount
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 
  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;
'''

new_cols = {'bill_time': u'还款时间', 'funding_name': u'资金方', 'approach_name': u'还款渠道', 'sum_amount': u'金额'}

class week_repay():
    def __init__(self,today):
        if not today:
            self.today = datetime.date.today()
        else:
            self.today = today
        self.end = self.today
        self.start = self.today + datetime.timedelta(days=-7)
        self.dir_path = path
        if not os.path.exists(self.dir_path):
            os.makedirs(self.dir_path)

    def week_repay_details(self):
        df_repay = pd.read_sql(sql=repay_sql.format(self.start.strftime("'%Y-%m-%d'"), self.end.strftime("'%Y-%m-%d'")), con=engine_new_transaction)
        df_repay.rename(columns=new_cols, inplace=True)
        df_repay.to_excel(os.path.join(self.dir_path, u'新模式-客户还款表-周({}-{}).xlsx'.format(self.start.strftime("%Y%m%d"), (self.end + datetime.timedelta(days=-1)).strftime("%Y%m%d"))),index=None)



if __name__ == '__main__':
    today = None
    #today = datetime.date(2018, 10, 29)
    week_repay(today).week_repay_details()
    print('======================week_repay done===================================')
