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

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

path = '/home/quant_group/vpants/finance/table/'
#path = '/Users/chenxiaozhe/Downloads/test/'
new_transaction_conn = sql_engine('audit', 'new_transaction').get_engine()
xyqb_conn = sql_engine('xyqb', 'xyqb').get_engine()


query_qishou2_repay_sql = """
select xrro.bill_time as '还款时间',xrro.loan_paid_at as '放款时间',xrro.principle as '实还本金',xrro.interest as '实还利息',xrro.premium as '实还保费',
loan.contract_loan_amount as '放款本金',loan.contract_term as '总期数' from xiaoyingp2p_repay_record_online xrro 
inner join audit.loan_manifest loan on loan.loan_id=xrro.loan_id where xrro.product_type=2
"""
# where xrro.bill_time >= {} and xrro.bill_time < {}


query_behalf_sql = """
select fbp.behalf_at as '代偿时间',fii.xyqb_loan_request_id as '合作方订单号', lm.loan_paid_at as '放款时间',lm.contract_loan_amount as '放款本金',lm.contract_term as '总期数',
behalf_principal+behalf_interest+rr.premium as '实还总额', behalf_principal as '实还本金',behalf_interest as '实还利息',rr.premium as '实还保费',rr.term_no as '第几期' from fund_behalf_plan fbp 
INNER JOIN repayment_record rr on rr.repayment_plan_id=fbp.plan_id and fbp.fund_id=640
INNER JOIN loan_application_manifest_history lm on lm.loan_application_history_id=rr.loan_application_history_id
INNER JOIN funding_interaction_info fii on fii.loan_id = lm.loan_application_history_id
"""


class xiaoying_short_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 qishou(self):
        # 2018-10-19号之前
        begin_time = self.start.strftime("'%Y-%m-%d'")
        end_time = self.end.strftime("'%Y-%m-%d'")

        # 2018-10-19号之后
        df_qishou2 = pd.read_sql(sql=query_qishou2_repay_sql, con=new_transaction_conn)
        if len(df_qishou2) == 0:
            return

        df_qishou2[u'资金方'] = '小赢p2p'
        df_qishou2[u'实还总额'] = df_qishou2[u'实还本金'] + df_qishou2[u'实还利息'] + df_qishou2[u'实还保费']
        df_qishou2[u'小赢14%部分本息'] = np.round(np.pmt(0.011667, df_qishou2[u'总期数'], -df_qishou2[u'放款本金']), 2)
        df_qishou2[u'借款人每期36%部分还款本息'] = np.round(df_qishou2[u'放款本金'] * 0.36 / 12 + df_qishou2[u'放款本金'] / df_qishou2[u'总期数'], 2)
        df_qishou2[u'QG服务费金额-期收'] = df_qishou2[u'借款人每期36%部分还款本息'] - df_qishou2[u'小赢14%部分本息']
        df_qishou2.to_csv(os.path.join(self.dir_path, '小赢p2p-短期-期收收入确认表-{}.csv'.format(self.start.strftime('%Y%m'))), index=None, encoding='gbk')

        #代偿
        df_behalf = pd.read_sql(sql=query_behalf_sql, con=xyqb_conn)
        if len(df_behalf) == 0:
            return
        df_behalf[u'资金方'] = '小赢p2p'
        df_behalf[u'小赢14%部分本息'] = np.round(np.pmt(0.011667, df_behalf[u'总期数'], -df_behalf[u'放款本金']), 2)
        df_behalf[u'借款人每期36%部分还款本息'] = np.round(df_behalf[u'放款本金'] * 0.36 / 12 + df_behalf[u'放款本金'] / df_behalf[u'总期数'], 2)
        df_behalf[u'QG服务费金额-期收'] = df_behalf[u'借款人每期36%部分还款本息'] - df_behalf[u'小赢14%部分本息']
        df_behalf.to_csv(os.path.join(self.dir_path, '小赢p2p-短期-代偿表-{}.csv'.format(self.start.strftime('%Y%m'))),index=None, encoding='gbk')





    def xiaoying_short_repay_detail(self):
        self.qishou()


if __name__ == '__main__':
    xiaoying_short_repay().xiaoying_short_repay_detail()
    print('======================xiaoying_short_repay done===================================')