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

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

engine_new_transaction = sql_engine('audit', 'new_transaction').get_engine()

path = '/home/quant_group/vpants/finance/table/'

sql_gd_repay = """
select 
  lm.loan_id,
  lm.contract_loan_amount 放款金额,
  date(lm.loan_paid_at) 放款日期,
  f.name 资金方,
  date(plan.deadline) 应还日期,
  plan.term_no 当前期数,
  date(ref.bill_time) 还款日期,
  rc.approach_name 还款账户,
  ref.ref_amount 还款总额,
  ref.principle 还款本金,
  ref.interest 还款利息,
  ref.service_fee 还款服务费,
  ref.collection_relief 催收减免,
  ref.punish 逾期罚息,
  ref.remain_income 其他收益,
  mitigate_principle 减免本金,
  mitigate_interest 减免利息,
  mitigate_service_fee 减免服务费,
  mitigate_collection_relief 减免罚息,
  ref.residual_service_fee 剩余未还服务费,
  ref.subsidy_fee 还款补贴,
  ref.mitigate_subsidy_fee 还款补贴减免,
  ref.premium 保费,
  ref.mitigate_premium 保费减免 
from
  new_transaction.xjd_repay_plan_repay_record_ref ref 
  join new_transaction.repay_channel rc 
    on ref.repay_channel = rc.id 
    and ref.repay_channel = 25 
    and ref.bill_time >= '{}'
    and ref.bill_time < '{}'
  join new_transaction.user_repayment_plan plan 
    on plan.id = ref.plan_id 
  join audit.loan_manifest lm 
    on lm.ref_id = plan.ref_id 
    and lm.funding_code = 480
    and lm.loan_paid_at < '2018-01-01' 
  join basic.funding_corp f 
    on f.funding_code = lm.funding_code ;
"""


class guangda_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 yeepay_guangda_repay_details(self):
        df = pd.read_sql(sql=sql_gd_repay.format(self.start, self.end), con=engine_new_transaction)
        df.to_excel(os.path.join(self.dir_path, '易宝广达-客户还款表-{}.xlsx'.format(self.start.strftime('%Y%m'))), index=None)


if __name__ == '__main__':
    guangda_repay().yeepay_guangda_repay_details()
    print('======================yeepay_guangda_repay_details done===================================')
