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

#test
#query_repay_sql = """
#  select  t8.loan_id,t1.bill_time,year(t8.loan_paid_at) loan_year,month(t8.loan_paid_at) loan_month,year(t1.bill_time) repay_year,month(t1.bill_time) repay_month,
#  t1.ref_amount total_amount,t1.principle act_principle,t1.interest act_interest,t1.service_fee act_punish,t1.collection_relief act_penalty
#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`=600 join audit.loan_manifest t8  on t8.ref_id = t2.ref_id
#  where t1.bill_time >= {} and t1.bill_time < {}
#"""

query_repay_sql = """
    select loan_id,bill_time,year(loan_paid_at) loan_year, month(loan_paid_at) loan_month ,year(bill_time) repay_year, month(bill_time) repay_month, total_amount, act_principle,act_interest,act_punish,act_penalty from xingye_repay_record_online 
    where  bill_time >= {} and bill_time < {}
"""

# 测试 funding_code=420
# funding_code=600
query_loan_count_sql = """
    select count(*) loan_count from audit.loan_manifest where funding_code = 600 and loan_paid_at >= {} and loan_paid_at < {}
"""

query_plan_sql = """
    select t1.loan_id,t1.ref_id,year(loan_paid_at) as fkyear,month(loan_paid_at) as fkmonth,year(max(deadline)) as hkyear,month(max(deadline)) as hkmonth, sum(principle) as principle ,sum(interest) as interest ,sum(service_fee) as service_fee from audit.loan_manifest t1 inner join  new_transaction.user_repayment_plan t2 on t1.ref_id=t2.ref_id  and t1.funding_code=600 
group by t1.ref_id
"""

query_max_deadline_sql = """
select t1.loan_id , DATE_FORMAT(date_add(max(deadline), interval 1 month),'%%Y-%%m-01') deadline from audit.loan_manifest t1 inner join  new_transaction.user_repayment_plan t2 on t1.ref_id=t2.ref_id  and t1.funding_code=600 
where  t1.loan_id 
group by t1.loan_id
"""

class xingye_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)
        ##test##
        #self.start = datetime.date(2018, 9, 1)
        #self.end = datetime.date(2018, 10, 1)
        ##test##

        self.dir_path = path + self.start.strftime('%Y%m')
        if not os.path.exists(self.dir_path):
            os.makedirs(self.dir_path)

    def xingye_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)
        if len(df_repay) == 0:
            return

        #统计当月放款数量
        df_loan = pd.read_sql(sql=query_loan_count_sql.format(begin_time, end_time), con=new_transaction_conn)
        df_repay['loan_count'] = df_loan['loan_count'].tolist()[0]
        df_repay['fund_name'] = '兴业'
        #代收
        df_repay['collection'] = np.round(df_repay['total_amount'] * 0.002, 2)
        #代付
        df_repay['substitute'] = df_repay['loan_count'] * 1
        #期收
        df_repay['qishou'] = np.round((df_repay['act_interest'] + df_repay['act_punish'] + df_repay['act_penalty'] - df_repay['collection'] - df_repay['substitute']) * 0.01, 2)

        #要把还款时间在该笔loan,最后一期deadline + 1个月后的还款排除去,出在另外一张表 '收入确认表-贷后服务费3'
        df_repay.loan_id = df_repay.loan_id.astype(str)
        df_loan_deadline = pd.read_sql(sql=query_max_deadline_sql.format(str(tuple(df_repay.loan_id)).replace(',)', ')')) , con=audit_conn)
        df_loan_deadline['deadline'] = pd.to_datetime(df_loan_deadline['deadline']).dt.date
        df_repay['bill_time'] = pd.to_datetime(df_repay['bill_time']).dt.date

        df_all = pd.merge(df_repay, df_loan_deadline, how='left', on='loan_id')
        df_before_deadline_repay = df_all.ix[df_all['bill_time'] < df_all['deadline']]
        df_after_deadline_repay = df_all.ix[df_all['bill_time'] > df_all['deadline']]

        # 期收1
        df_before_deadline_repay = df_before_deadline_repay[['loan_year','loan_month','repay_year','repay_month','fund_name','total_amount','act_principle','act_interest','act_punish','act_penalty','substitute','collection','qishou']]
        df_before_deadline_repay.rename(columns={
            'loan_year': '放款年', 'loan_month': '放款月', 'repay_year': '还款年', 'repay_month': '还款月',
            'fund_name': '资金方', 'total_amount': '还款总额', 'act_principle':'实还本金', 'act_interest':'实还利息' ,
            'act_punish':'实还罚息', 'act_penalty' :'实还违约金', 'substitute':'代付成本', 'collection':'代收成本', 'qishou':'QG服务费金额1-期收'
        }, inplace=True)

        df_before_deadline_repay.to_excel(os.path.join(self.dir_path, '兴业-收入确认表(期收1-固定可收回)-{}.xlsx'.format(self.start.strftime('%Y%m'))), index=None)
        #期收1


        #逾期期收
        if len(df_after_deadline_repay) == 0:
            return
        #
        df_after_deadline_repay['qishou'] = np.round((df_after_deadline_repay['act_principle'] + df_after_deadline_repay['act_interest'] + df_after_deadline_repay['act_punish']) * 0.5, 2)
        df_after_deadline_repay = df_after_deadline_repay[
            ['loan_year', 'loan_month', 'repay_year', 'repay_month', 'fund_name', 'total_amount', 'act_principle', 'act_interest', 'act_punish', 'act_penalty', 'qishou']]
        df_after_deadline_repay.rename(columns={
            'loan_year': '放款年', 'loan_month': '放款月', 'repay_year': '逾期还款年', 'repay_month': '逾期还款月',
            'fund_name': '资金方', 'total_amount': '还款总额', 'act_principle': '实还本金', 'act_interest': '实还利息',
            'act_punish': '实还罚息', 'act_penalty': '实还违约金', 'qishou': 'QG服务费金额3-贷后服务费'
        }, inplace=True)

        df_after_deadline_repay.to_excel(os.path.join(self.dir_path, '兴业-收入确认表(贷后服务费3)-{}.xlsx'.format(self.start.strftime('%Y%m'))), index=None)
        # 逾期期收




    def xingye_plan(self):
        df_plan = pd.read_sql(query_plan_sql, new_transaction_conn)
        df_plan['sumAmount'] = df_plan['principle'] + df_plan['interest'] + df_plan['service_fee']
        df_plan['sumAmount'] = np.round(df_plan['sumAmount'], 2)

        df_plan.rename(columns={
            'fkyear': '放款年', 'fkmonth': '放款月', 'hkyear': '到期年', 'hkmonth': '到期月',
            'principle': '应还本金', 'interest': '应还利息', 'service_fee': '应还服务费',  'sumAmount': '应还总额'
        }, inplace=True)

        df_plan.to_csv(os.path.join(self.dir_path, '兴业-还款计划表-{}.csv'.format(self.start.strftime('%Y%m'))), index=None, encoding='gbk')

    def xingye_repay_details(self):
        self.xingye_repay()
        self.xingye_plan()

if __name__ == '__main__':
    xingye_repay().xingye_repay_details()
    print('======================xingye_repay done===================================')
