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

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,repay_app_no,bill_time,principle,interest,punish,breach_overdue,breach_early_settle,
      charge,other_fee,deduct_breach_overdue,deduct_breach_early_settle,deduct_charge,loan_id,ref_id,safe_fee
    from zhongan_repay_record_online where enable=1; 
    
"""
query_repayment_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=590 
group by t1.ref_id
"""


class zhongan_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 zhongan_repay_detail(self):
        df_all = pd.read_sql(sql=query_sql, con=new_transaction_conn)
        df_all['deduct_penalty'] = 0  # todo 给的excel中没有,但是众安的对账文件中存在这个字段,和产品沟通吧
        df_all['fund_name'] = '众安'
        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['sum_amount'] = (df_all['principle'] + df_all['interest'] + df_all['punish'] + df_all['breach_overdue'] + \
                                df_all['breach_early_settle']  + df_all['other_fee'] + df_all[
                                    'safe_fee']) - (df_all['deduct_breach_overdue'] + df_all['deduct_penalty']
                                                    + df_all['deduct_breach_early_settle'] + df_all['deduct_charge'])
        df_all.drop('order_id', axis=1, inplace=True)
        df_all['repay_time'] = df_all['bill_time'].apply(lambda x: pd.datetime.strftime(x, '%Y-%m-%d'))

        df_all_table = df_all.groupby(['year', 'month', 'repay_time'])[[
            'fund_name', 'sum_amount', 'principle', 'interest', 'breach_overdue', 'safe_fee', 'breach_early_settle',
            'punish', 'other_fee', 'deduct_penalty', 'deduct_breach_overdue', 'deduct_breach_early_settle',
            'deduct_charge'
        ]].agg(
            'sum').reset_index().rename(columns={
            'year': '还款年', 'month': '还款月', 'repay_time': '还款成功日期', 'fund_name': '资金方', 'sum_amount': '还款总额',
            'principle': '还款本金', 'interest': '还款利息', 'breach_overdue': '逾期违约金',
            'safe_fee': '账户安全险(意外伤害险)', 'breach_early_settle': '提前结清违约金',  'punish': '罚息',
            'other_fee': '其他费用', 'deduct_penalty': '减免罚息', 'deduct_breach_overdue': '减免逾期违约金',
            'deduct_breach_early_settle': '减免提前结清违约金', 'deduct_charge': '减免服务费'
        })

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

        # 收入确认表-期收
        # 期收收入确认表: 实还总额= 当期实还本金+当期实还利息+实还服务费+实还账户安全险
        df_all['qishou_service_amount'] = np.round(df_all['safe_fee'] * 0.8, 2)
        df_all['qishou_sum_amount'] = df_all['principle'] + df_all['interest'] + df_all['punish'] + df_all['safe_fee']
        df_all_qishou_table = df_all.groupby(['year', 'month'])[[
            'fund_name', 'qishou_sum_amount', 'principle', 'interest',  'safe_fee',
            'qishou_service_amount']].agg(
            'sum').reset_index().rename(columns={
            'year': '实还年', 'month': '实还月', 'fund_name': '资金方', 'term_no': '期数', 'qishou_sum_amount': '实还总额',
            'principle': '当期实还本金', 'interest': '当期实还利息', 'safe_fee': '账户安全险(意外伤害险)',
            'qishou_service_amount': 'QG服务费金额2-期收'
        })

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

        # 还款计划
        df_plan = pd.read_sql(query_repayment_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': '应还款月', 'sumAmount': '应还总额',
            'principle': '应还本金', 'interest': '应还利息', 'service_fee': '应还服务费'
        }, inplace=True)

        df_plan.to_excel(os.path.join(self.dir_path, u'众安-还款计划表-{}.xlsx'.format(self.start.strftime('%Y%m'))), index=None)


if __name__ == '__main__':
    zhongan_repay().zhongan_repay_detail()
    print('======================zhongan_repay done===================================')
