# -*- 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_repay_sql = """
select loan.loan_paid_at,ref.bill_time,plan.repayment_plan_id,t6.approach_name repay_channel   
from new_transaction.xjd_repay_plan_repay_record_ref ref inner join new_transaction.user_repayment_plan plan on plan.id=ref.plan_id 
inner join audit.loan_manifest loan on loan.`loan_id`=plan.`real_loan_id` and loan.`funding_code` in (610,700)  
join new_transaction.repay_channel t6  on t6.id = ref.repay_channel 
where ref.bill_time >= {} and ref.bill_time < {}
"""

query_xiaoying_repay_sql = """
select fc.name fund_name,loan_paid_at,bill_time,plan_id,'repay_channel',principle,interest,'actual_collection_relief',premium from xiaoyingp2p_repay_record_online
  xy inner  join basic.funding_corp fc on fc.id=xy.fund_id
 where product_type in (1,2) and  bill_time >= {} and bill_time < {}
"""

query_repayment_record_sql = """
  select repayment_plan_id,principal,interest,actual_collection_relief,premium from repayment_record where repayment_plan_id in {} ;
"""

# 期收
query_should_repay_sql = """
select year(t1.deadline) as '应还年',month(t1.deadline) as '应还月',t2.funding_corp_name as '资金方', year(t2.loan_paid_at) as '放款年', month(t2.loan_paid_at) as '放款月', 
t2.contract_loan_amount as '放款本金',t2.contract_term as '总期数', t1.term_no as '第几期',0 as '应还总额', t1.principal as '应还本金',t1.interest as '应还利息',t1.premium as '应还保费'
from repayment_record t1 
inner join loan_application_manifest_history t2 on t1.loan_application_manifest_history_id=t2.id and t2.funding_corp_id in (610,700)   and t2.transaction_status in (2,5) and t2.loan_paid_at<'2018-10-19'
where t1.deadline >= {} and t1.deadline < {}
"""


query_qishou2_repay_sql = """
select loan.loan_id, fc.name as '资金方' , 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 
inner join basic.funding_corp fc on fc.id=loan.funding_code
where xrro.product_type in (1,2)
"""
# where xrro.bill_time >= {} and xrro.bill_time < {}


query_behalf_sql = """
select fbp.behalf_at as '代偿时间',CASE fbp.fund_id
    WHEN 610
    THEN fii.xyqb_loan_request_id
    WHEN 700
    THEN fii.funding_assign_request_id 
    END as '合作方订单号', 
 lm.funding_corp_name 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 in (610,700)  
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_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'")
        df_qishou = pd.read_sql(sql=query_should_repay_sql.format(begin_time, end_time), con=xyqb_conn)
        if len(df_qishou) == 0:
            return
        df_qishou[u'应还总额'] = df_qishou[u'应还本金'] + df_qishou[u'应还利息'] + df_qishou[u'应还保费']
        df_qishou[u'小赢14%部分本息'] = np.round(np.pmt(0.011667, df_qishou[u'总期数'], -df_qishou[u'放款本金']), 2)
        df_qishou[u'借款人每期36%部分还款本息'] = np.round(df_qishou[u'放款本金'] * 0.36 / 12 + df_qishou[u'放款本金'] / df_qishou[u'总期数'], 2)
        df_qishou[u'QG服务费金额-期收'] = df_qishou[u'借款人每期36%部分还款本息'] - df_qishou[u'小赢14%部分本息']
        df_qishou.to_csv(os.path.join(self.dir_path, '小赢p2p-期收收入确认表-20181019号之前-{}.csv'.format(self.start.strftime('%Y%m'))), index=None, encoding='gbk')

        # 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-期收收入确认表-20181019号之后-{}.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'合作方订单号'] = df_behalf[u'合作方订单号'].astype(str) + '\t'
        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 repay(self):
        begin_time = self.start.strftime("'%Y-%m-%d'")
        end_time = self.end.strftime("'%Y-%m-%d'")
        df_repay = pd.read_sql(sql=query_repay_sql.format(begin_time, end_time), con=new_transaction_conn)
        df_repay.repayment_plan_id = df_repay.repayment_plan_id.astype(int)

        #查询xyqb repayment_record 的本金,利息,减免利息,保费
        df_repayment_record = pd.read_sql(sql=query_repayment_record_sql.format(str(tuple(df_repay.repayment_plan_id)).replace(',)', ')')), con=xyqb_conn)
        df_repay_all = pd.merge(df_repay, df_repayment_record, how='left', on='repayment_plan_id')

        df_repay_all['fund_name'] = '小赢p2p'
        df_repay_all['repay_year'] = df_repay_all['bill_time'].apply(lambda x: pd.datetime.strftime(x, '%Y'))
        df_repay_all['repay_month'] = df_repay_all['bill_time'].apply(lambda x: pd.datetime.strftime(x, '%m'))
        df_repay_all['loan_year'] = df_repay_all['loan_paid_at'].apply(lambda x: pd.datetime.strftime(x, '%Y'))
        df_repay_all['loan_month'] = df_repay_all['loan_paid_at'].apply(lambda x: pd.datetime.strftime(x, '%m'))

        df_repay_all['sum_amount'] = df_repay_all['principal'] + df_repay_all['interest'] - df_repay_all['actual_collection_relief'] + df_repay_all['premium']

        df_repay_all_table = df_repay_all.groupby(['loan_year', 'loan_month', 'repay_year', 'repay_month' , 'repay_channel'])[[
            'fund_name', 'sum_amount', 'principal', 'interest', 'actual_collection_relief', 'premium'
        ]].agg(
            'sum').reset_index().rename(columns={
            'loan_year':'放款年', 'loan_month':'放款月','repay_year': '还款年', 'repay_month': '还款月', 'fund_name': '资金方',
            'repay_channel':'收款帐户','sum_amount': '实还总额','principal': '本金', 'interest': '利息', 'actual_collection_relief': '减免利息','premium': '实还保费'
        })
        df_repay_all_table.to_excel(os.path.join(self.dir_path, '小赢p2p-还款表-易宝-{}.xlsx'.format(self.start.strftime('%Y%m'))), index=None)

        #还款到小赢的数据
        df_xiaoying_repay = pd.read_sql(sql=query_xiaoying_repay_sql.format(begin_time, end_time), con=new_transaction_conn)
        #df_xiaoying_repay['fund_name'] = '小赢p2p'
        df_xiaoying_repay['repay_channel'] = "小赢p2p"
        df_xiaoying_repay['actual_collection_relief'] = 0

        df_xiaoying_repay['repay_year'] = df_xiaoying_repay['bill_time'].apply(lambda x: pd.datetime.strftime(x, '%Y'))
        df_xiaoying_repay['repay_month'] = df_xiaoying_repay['bill_time'].apply(lambda x: pd.datetime.strftime(x, '%m'))
        df_xiaoying_repay['loan_year'] = df_xiaoying_repay['loan_paid_at'].apply(lambda x: pd.datetime.strftime(x, '%Y'))
        df_xiaoying_repay['loan_month'] = df_xiaoying_repay['loan_paid_at'].apply(lambda x: pd.datetime.strftime(x, '%m'))

        df_xiaoying_repay['sum_amount'] = df_xiaoying_repay['principle'] + df_xiaoying_repay['interest'] - df_xiaoying_repay['actual_collection_relief'] + df_xiaoying_repay['premium']

        df_xiaoying_repay_all_table = df_xiaoying_repay.groupby(['fund_name', 'loan_year', 'loan_month', 'repay_year', 'repay_month'])[[
            'fund_name', 'sum_amount', 'principle', 'interest', 'actual_collection_relief', 'premium'
        ]].agg(
            'sum').reset_index().rename(columns={
            'loan_year': '放款年', 'loan_month': '放款月', 'repay_year': '还款年', 'repay_month': '还款月', 'fund_name': '资金方',
            'repay_channel': '收款帐户', 'sum_amount': '实还总额', 'principle': '本金', 'interest': '利息',
            'actual_collection_relief': '减免利息', 'premium': '实还保费'
        })
        df_xiaoying_repay_all_table.to_excel(os.path.join(self.dir_path, '小赢p2p-还款表-小赢-{}.xlsx'.format(self.start.strftime('%Y%m'))), index=None)

    def xiaoying_repay_detail(self):
        #self.repay()
        self.qishou()


if __name__ == '__main__':
    xiaoying_repay().xiaoying_repay_detail()
    print('======================xiaoying_repay done===================================')