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

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

query_sql = """
    select lm.contract_term,order_id,term_no,principle,interest,punish,bill_time,zrro.ref_id,zrro.loan_id from zhongwang_repay_record_online zrro
inner join audit.loan_manifest lm on lm.loan_id=zrro.loan_id
"""


query_loan_sql = """
     select year(loan_paid_at) as '放款年',month(loan_paid_at) as '放款月', contract_term as '期数' ,sum(contract_loan_amount) as '放款金额' from  audit.loan_manifest 
    where funding_code=560 group by 1,2,3 

"""


class zhongwang2_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 zhongwang2_repay_detail(self):
        df_all = pd.read_sql(sql=query_sql, con=new_transaction_conn)
        df_all['fund_name'] = '众网小贷2'
        df_all['bill_time'] = pd.to_datetime(df_all['bill_time'])
        df_all['year'] = df_all['bill_time'].apply(lambda x: pd.datetime.strftime(x, '%Y'))
        df_all['month'] = df_all['bill_time'].apply(lambda x: pd.datetime.strftime(x, '%m'))

        df_all.drop('order_id', axis=1, inplace=True)

        # 客户还款表
        df_all['sum_amount'] = df_all['principle'] + df_all['interest'] + df_all['punish']
        df_all_table = df_all.groupby(['year', 'month'])[[
            'fund_name', 'sum_amount', 'principle', 'interest', 'punish'
        ]].agg(
            'sum').reset_index().rename(columns={
            'year': '实还年', 'month': '实还月', 'fund_name': '资金方', 'sum_amount': '实还总额',
            'principle': '当期实还本金', 'interest': '当期实还利息', 'punish': '实还罚息'
        })

        df_all_table.to_excel(os.path.join(self.dir_path, u'众网小贷2-还款表-{}.xlsx'.format(self.start.strftime('%Y%m'))), index=None)

        # 收入确认表-期收
        df_all_3 = df_all.loc[df_all['contract_term'] == 3]
        df_all_not_3 = df_all.loc[df_all['contract_term'] != 3]

        if len(df_all_3) > 0:
            df_all_3['qishou_service_amount'] = np.round(df_all_3['interest'] * 0.078, 2)
            df_all_3['qishou_sum_amount'] = df_all_3['principle'] + df_all_3['interest'] + df_all_3['punish']
            df_all_qishou_table = df_all_3.groupby(['year', 'month'])[[
                'fund_name', 'qishou_sum_amount', 'principle', 'interest', 'punish', 'qishou_service_amount']].agg(
                'sum').reset_index() \
                .rename(columns={
                'year': '实还年', 'month': '实还月', 'fund_name': '资金方', 'qishou_sum_amount': '实还总额',
                'principle': '当期实还本金', 'interest': '当期实还利息', 'punish': '当期实还罚息', 'qishou_service_amount': 'QG服务费金额2-期收'
            })

            df_all_qishou_table.to_excel(
                os.path.join(self.dir_path, u'众网小贷2-期收表(3期)-{}.xlsx'.format(self.start.strftime('%Y%m'))), index=None)

        if len(df_all_not_3) > 0:
            df_all_not_3['qishou_service_amount'] = np.round(df_all_not_3['interest'] * 0.18, 2)
            df_all_not_3['qishou_sum_amount'] = df_all_not_3['principle'] + df_all_not_3['interest'] + df_all_not_3['punish']
            df_all_qishou_table = df_all_not_3.groupby(['year', 'month'])[[
                'fund_name', 'qishou_sum_amount', 'principle', 'interest', 'punish', 'qishou_service_amount']].agg(
                'sum').reset_index() \
                .rename(columns={
                'year': '实还年', 'month': '实还月', 'fund_name': '资金方', 'qishou_sum_amount': '实还总额',
                'principle': '当期实还本金', 'interest': '当期实还利息', 'punish': '当期实还罚息', 'qishou_service_amount': 'QG服务费金额2-期收'
            })

            df_all_qishou_table.to_excel(os.path.join(self.dir_path, u'众网小贷2-期收表(非3期)-{}.xlsx'.format(self.start.strftime('%Y%m'))), index=None)


        #趸收
        df_ds_all = pd.read_sql(sql=query_loan_sql, con=new_transaction_conn)

        df_ds_3_all = df_ds_all.loc[df_ds_all[u'期数'] == 3]
        df_ds_3_all[u'趸收'] = np.round(df_ds_3_all[u'放款金额'] * 0.016, 2)

        df_ds_not_3_all = df_ds_all.loc[df_ds_all[u'期数'] != 3]
        df_ds_not_3_all[u'趸收'] = np.round(df_ds_not_3_all[u'放款金额'] * 0.03, 2)

        df_dunshou_all = pd.concat([df_ds_3_all, df_ds_not_3_all], axis=0)
        df_dunshou_all.to_excel(os.path.join(self.dir_path, u'众网小贷2-趸收-{}.xlsx'.format(self.start.strftime('%Y%m'))), index=None)




if __name__ == '__main__':
    zhongwang2_repay().zhongwang2_repay_detail()
    print('======================zhongwang2_repay done===================================')
