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

query_sql = """
    select order_id,term_no,principle,interest,punish,bill_time,ref_id,loan_id from zhongwang_repay_record_online; 
"""


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['qishou_service_amount'] = np.round(df_all['interest'] * 0.18, 2)
        df_all['qishou_sum_amount'] = df_all['principle'] + df_all['interest'] + df_all['punish']
        df_all_qishou_table = df_all.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-期收表-{}.xlsx'.format(self.start.strftime('%Y%m'))), index=None)


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