# -*- coding: utf-8 -*-

import os
import sys
import datetime
import numpy as np
import pandas as pd

sys.path.append('../../../finance_out_table')

from db_con.db_connect import sql_engine

pd.options.mode.chained_assignment = None
pd.set_option('display.float_format', lambda x: '%.5f' % x)
res_sum = []
path = '/home/quant_group/vpants/finance/table/'
step = 10000
max_limit = 900000
source_path = '/home/quant_group/vpants/finance/resources'
audit_conn = sql_engine('audit', 'audit').get_engine()
new_transaction_conn = sql_engine('audit', 'new_transaction').get_engine()

ratio_sql = 'SELECT class 风险等级, year 年, month 月, bad_debt_ratio 计提风险金比例 FROM test_mzh.service_fee_ratio'

query_ref_sql = """
    select 
      urp.ref_id, 
      xrprrr.ref_amount, 
      xrprrr.principle - xrprrr.mitigate_principle paid_prin, 
      xrprrr.interest - xrprrr.mitigate_interest paid_inst, 
      xrprrr.service_fee - xrprrr.mitigate_service_fee paid_fee, 
      xrprrr.punish - xrprrr.mitigate_collection_relief paid_punish, 
      xrprrr.remain_income remain, 
      date(xrprrr.bill_time) bill_time 
    from 
      new_transaction.xjd_repay_plan_repay_record_ref xrprrr 
      join new_transaction.user_repayment_plan urp 
        on urp.id = xrprrr.plan_id 
      join audit.loan_manifest lm 
        on lm.ref_id = urp.ref_id 
    where lm.loan_paid_at < '2018-01-03' 
      and lm.funding_code not in (160, 340) 
      and xrprrr.bill_time < {};
"""

yghs_sql = """
SELECT
  t.ref_id,
  t.actual_repay_amount                                         实还总额,
  t.actual_principle                                            实还本金,
  t.actual_interest                                             实还利息,
  t.actual_qg_service_fee                                       `实还服务费（减免后）`,
  t.actual_qg_overdue_interest + t.actual_fund_overdue_interest 实还罚息,
  t.actual_compound_interest                                    实还复利,
  date(t.repay_date)                                            repaid_at
FROM new_transaction.yg_huishang_repay_term t

union all

select 
  urp.ref_id, 
  xrprrr.ref_amount as 实还总额, 
  xrprrr.principle - xrprrr.mitigate_principle as 实还本金, 
  xrprrr.interest - xrprrr.mitigate_interest as 实还利息, 
  xrprrr.service_fee - xrprrr.mitigate_service_fee as `实还服务费（减免后）`, 
  xrprrr.punish - xrprrr.mitigate_collection_relief as 实还罚息, 
  0  as 实还复利, 
  date(xrprrr.bill_time)  as repaid_at
from 
  new_transaction.xjd_repay_plan_repay_record_ref xrprrr 
  join new_transaction.user_repayment_plan urp 
    on urp.id = xrprrr.plan_id 
  join audit.loan_manifest lm 
    on lm.ref_id = urp.ref_id 
where lm.loan_paid_at < '2018-01-03' 
  and lm.funding_code = 340 
  and xrprrr.bill_time>='2018-06-01' and xrprrr.bill_time < {};

"""

loan_col = [u'loan_id', u'ref_id', u'风险等级', u'funding_code', u'资金方', u'is_active', u'本金债权',
            u'qg_one_time_service_fee', u'放款日期', u'总服务费', u'计提风险金比例']

res_cols = [u'loan_id', u'风险等级', u'资金方', u'本金债权', u'qg_one_time_service_fee', u'放款日期', u'总服务费', u'计提风险金比例',
            u'计提风险金',
            u'实还服务费（减免后）', u'趸交服务费', u'实还服务费（减免后、含一次性服务费、趸交服务费）', u'asset余额', u'收入确认金额']


class income_confirm():
    def __init__(self):
        self.today = datetime.date.today()
        self.end = datetime.date(self.today.year, self.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 handler(self, watch_date):
        loan = self.df_loan_ratio.loc[self.df_loan_ratio[u'放款日期'] < watch_date]
        loan.loc[~loan.is_active.isin([1, -2]), u'本金债权'] = 0

        loan_other = loan.loc[~loan[u'funding_code'].isin([160, 340])]
        loan_ms = loan.loc[loan[u'funding_code'] == 160]
        loan_yghs = loan.loc[loan[u'funding_code'] == 340]

        loan_other_unique = loan_other[loan_col]
        loan_ms_unique = loan_ms[loan_col]
        loan_yghs_unique = loan_yghs[loan_col]

        ref = self.df_ref.loc[self.df_ref.repaid_at < watch_date]
        gp_other = ref.groupby('ref_id')[u'实还服务费（减免后）'].agg(sum).reset_index()
        loan_other_result = pd.merge(loan_other_unique, gp_other, how='left')
        loan_other_result.fillna(0, inplace=True)
        loan_result = loan_other_result

        print('非新马上: %f' % (loan_result[u'实还服务费（减免后）'].sum(),))
        ms = self.df_ms.loc[self.df_ms.repaid_at < watch_date]
        if len(ms) > 0:
            gp_ms = ms.groupby('loan_id')[u'实还服务费（减免后）'].agg(sum).reset_index()
            loan_ms_result = pd.merge(loan_ms_unique, gp_ms, how='left')
            loan_ms_result.fillna(0, inplace=True)
            print('新马上: %f' % (loan_ms_result[u'实还服务费（减免后）'].sum(),))
            loan_result = loan_result.append(loan_ms_result)
        else:
            loan_ms_unique[u'实还服务费（减免后）'] = 0
            loan_result = loan_result.append(loan_ms_unique)

        yghs = self.df_yghs.loc[self.df_yghs.repaid_at < watch_date]
        if len(yghs) > 0:
            gp_yghs = yghs.groupby('ref_id')[u'实还服务费（减免后）'].agg(sum).reset_index()
            loan_yghs_result = pd.merge(loan_yghs_unique, gp_yghs, how='left')
            loan_yghs_result.fillna(0, inplace=True)
            print('阳光徽商: %f' % (loan_yghs_result[u'实还服务费（减免后）'].sum(),))
            loan_result = loan_result.append(loan_yghs_result)
        else:
            loan_yghs_unique[u'实还服务费（减免后）'] = 0
            loan_result = loan_result.append(loan_yghs_unique)

        dj = self.df_dunjiao.loc[self.df_dunjiao.repaid_at < watch_date, [u'ref_id', u'趸交服务费']]
        if len(dj) > 0:
            loan_result = pd.merge(loan_result, dj, on='ref_id', how='left')
            loan_result.fillna(0, inplace=True)
        else:
            loan_result[u'趸交服务费'] = 0
        print('趸交服务费: %f' % (loan_result[u'趸交服务费'].sum(),))
        loan_result[u'计提风险金'] = np.round(loan_result[u'本金债权'] * loan_result[u'计提风险金比例'], 2)
        loan_result.loc[loan_result.funding_code.isin([270, 310, 320, 390, 410, 490]), u'计提风险金'] = 0

        loan_result[u'实还服务费（减免后、含一次性服务费、趸交服务费）'] = np.round(
            loan_result[u'实还服务费（减免后）'] + loan_result[u'qg_one_time_service_fee'] + loan_result[u'趸交服务费'], 2)
        loan_result[u'asset余额'] = np.maximum(
            np.round(loan_result[u'计提风险金'] - loan_result[u'实还服务费（减免后、含一次性服务费、趸交服务费）'], 2),
            0)
        loan_result[u'收入确认金额'] = np.minimum(
            np.round(loan_result[u'计提风险金'] - loan_result[u'实还服务费（减免后、含一次性服务费、趸交服务费）'], 2),
            0)
        print(
            loan_result[
                [u'本金债权', u'计提风险金', u'qg_one_time_service_fee', u'总服务费', u'实还服务费（减免后）', u'趸交服务费',
                 u'实还服务费（减免后、含一次性服务费、趸交服务费）',
                 u'asset余额',
                 u'收入确认金额']].sum())
        tmp_sum = loan_result[
            [u'本金债权', u'计提风险金', u'qg_one_time_service_fee', u'总服务费', u'实还服务费（减免后）', u'趸交服务费',
             u'实还服务费（减免后、含一次性服务费、趸交服务费）',
             u'asset余额',
             u'收入确认金额']].sum().to_frame().T

        v_day = watch_date + datetime.timedelta(days=-1)
        tmp_sum[u'截止时间'] = v_day
        res_sum.append(tmp_sum)

    def income_confirm_details(self):
        df_ratio = pd.read_sql(sql=ratio_sql, con=audit_conn)
        self.df_yghs = pd.read_sql(sql=yghs_sql.format(self.end.strftime("'%Y-%m-%d'")), con=new_transaction_conn)
        self.df_ref = pd.read_sql(query_ref_sql.format(self.end.strftime("'%Y-%m-%d'")), con=new_transaction_conn)
        self.df_ms = pd.read_csv(open(os.path.join(source_path, 'ms.csv'), 'rb'), encoding='utf8', low_memory=False)
        self.df_dunjiao = pd.read_csv(open(os.path.join(source_path, 'dunjiao.csv'), 'rb'), encoding='utf8',
                                      low_memory=False)
        self.df_service_fee = pd.read_csv(open(os.path.join(source_path, 'loan_service_fee.csv'), 'r'))
        self.df_loan = pd.read_csv(open(os.path.join(source_path, 'all_loan.csv'), 'rb'), encoding='utf8',
                                   low_memory=False)

        self.df_service_fee.columns = [u'ref_id', u'总服务费']
        self.df_ms[u'repaid_at'] = pd.to_datetime(self.df_ms[u'repaid_at']).dt.date
        self.df_yghs[u'repaid_at'] = pd.to_datetime(self.df_yghs[u'repaid_at']).dt.date
        self.df_dunjiao[u'repaid_at'] = pd.to_datetime(self.df_dunjiao[u'repaid_at']).dt.date
        self.df_ms.loan_id = self.df_ms.loan_id.astype(str)

        self.df_ref.columns = [u'ref_id', u'实还总额', u'实还本金', u'实还利息', u'实还服务费（减免后）', u'实还罚息', u'其他收益', u'repaid_at']
        self.df_ref['year-month'] = self.df_ref[u'repaid_at'].str[:7]

        self.df_loan[u'放款日期'] = pd.to_datetime(self.df_loan[u'放款日期']).dt.date
        self.df_loan.loc[self.df_loan[u'风险等级'] == 'D', u'风险等级'] = 'C'
        self.df_ref[u'repaid_at'] = pd.to_datetime(self.df_ref[u'repaid_at']).dt.date

        self.df_loan.loan_id = self.df_loan.loan_id.astype(str)
        self.df_loan_ratio = pd.merge(self.df_loan, df_ratio, on=[u'风险等级', u'年', u'月'], how='left')
        self.df_loan_ratio.loc[self.df_loan_ratio.funding_code.isin([270, 310, 320, 390, 410, 490]), u'计提风险金比例'] = 0
        self.df_loan_ratio = pd.merge(self.df_loan_ratio, self.df_service_fee, on='ref_id', how='left')


        self.handler(self.end)
        df_sum = pd.concat(res_sum)
        df_sum.to_excel(os.path.join(self.dir_path, u'旧模式收入确认表-{}.xlsx'.format(self.start.strftime('%Y%m'))), index=None)


if __name__ == '__main__':
    income_confirm().income_confirm_details()
    print('======================old_income_confirm done===================================')