# -*- 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/'
# path = '/Users/chenxiaozhe/Downloads/test/201901'
audit_conn = sql_engine('audit', 'audit').get_engine()
new_transaction_conn = sql_engine('audit', 'new_transaction').get_engine()
xyqb_conn = sql_engine('xyqb', 'xyqb').get_engine()

# loan维度
loan_version_sql = """
select l1.loan_id,l1.yinghuan as should_repay_amount, sum(l1.zc_tq + if(l2.yq is null,0,l2.yq)) as act_repay_amount  from (
  select g1.loan_id,g1.yinghuan, if (g2.zc_tq is null,0,g2.zc_tq) zc_tq from 
  (
  select t2.loan_application_history_id as loan_id, sum(t3.principal+t3.interest+t3.premium) as yinghuan
  from repayment_record t3 
 inner join loan_application_manifest_history t2 on t3.loan_application_manifest_history_id=t2.id and t2.funding_corp_id  in (610,700) and t2.transaction_status in (2,5)
 where (t3.deadline >= {} and t3.deadline < {})  
  group by t2.loan_application_history_id 
  ) g1

  left outer join 
  (
    select t2.loan_application_history_id as loan_id, sum(t3.actual_repayment) as zc_tq 
  from repayment_record t3 
 inner join loan_application_manifest_history t2 on t3.loan_application_manifest_history_id=t2.id and t2.funding_corp_id  in (610,700)  and t2.transaction_status in (2,5)
 where (t3.deadline >= {} and t3.deadline < {})  
and ( date(t3.deadline) = date(t3.repayment_received_at) or date(t3.repayment_received_at) < date(t3.deadline))
group by t2.loan_application_history_id
  ) g2 on g1.loan_id=g2.loan_id

  ) l1  left outer join 

  (
    select t2.loan_application_history_id as loan_id, sum(t3.actual_repayment) as yq
  from repayment_record t3 
 inner join loan_application_manifest_history t2 on t3.loan_application_manifest_history_id=t2.id and t2.funding_corp_id  in (610,700)  and t2.transaction_status in (2,5)
 where ( date(t3.repayment_received_at) > t3.deadline and t3.repayment_received_at >= {} and t3.repayment_received_at < {} ) 
 group by t2.loan_application_history_id 

  ) l2 on l1.loan_id=l2.loan_id  

  group by l1.loan_id 

  union

  select l1.loan_id,0,sum(l1.yq) from (
  select t2.loan_application_history_id as loan_id, sum(t3.actual_repayment) as yq
  from repayment_record t3 
 inner join loan_application_manifest_history t2 on t3.loan_application_manifest_history_id=t2.id and t2.funding_corp_id  in (610,700)  and t2.transaction_status in (2,5)
 where ( date(t3.repayment_received_at) > t3.deadline and  t3.repayment_received_at >= {} and t3.repayment_received_at < {} ) 
 group by t2.loan_application_history_id  
  ) l1 
  left outer  join 
  (

   select g1.loan_id,g1.yinghuan, if (g2.zc_tq is null,0,g2.zc_tq) zc_tq from 
  (
  select t2.loan_application_history_id as loan_id, sum(t3.principal+t3.interest+t3.premium) as yinghuan
  from repayment_record t3 
 inner join loan_application_manifest_history t2 on t3.loan_application_manifest_history_id=t2.id and t2.funding_corp_id  in (610,700)  and t2.transaction_status in (2,5)
 where (t3.deadline >= {} and t3.deadline < {})  
  group by t2.loan_application_history_id 
  ) g1

  left outer join 
  (
    select t2.loan_application_history_id as loan_id, sum(t3.actual_repayment) as zc_tq 
  from repayment_record t3 
 inner join loan_application_manifest_history t2 on t3.loan_application_manifest_history_id=t2.id and t2.funding_corp_id  in (610,700)  and t2.transaction_status in (2,5)
 where (t3.deadline >= {} and t3.deadline < {})  
and ( date(t3.deadline) = date(t3.repayment_received_at) or date(t3.repayment_received_at) < date(t3.deadline))
group by t2.loan_application_history_id
  ) g2 on g1.loan_id=g2.loan_id
  ) l2 on l1.loan_id=l2.loan_id
  where l2.loan_id is null
  group by l1.loan_id
"""
query_loan_sql = """
select
    fc.name as fund_name,
	lm.loan_id,
	lm.ref_id,
	lm.loan_paid_at
from
	loan_manifest lm inner join  basic.funding_corp fc on fc.id=lm.funding_code
where loan_id in {}
"""

# 时间维度本息
time_version_bx_sql = """
select t1.deadline as hk_day ,sum(t1.principal+t1.interest+t1.premium) should_repay_amount from repayment_record t1 
 inner join loan_application_manifest_history t2 on t1.loan_application_manifest_history_id=t2.id and t2.funding_corp_id={}  and t2.transaction_status in (2,5)
 where t1.deadline >={} and  t1.deadline < {}
 group by t1.deadline
"""
# 时间维度正常还款
time_version_zc_sql = """
 select t1.deadline as hk_day, sum(t1.actual_repayment)  zc from repayment_record t1 
 inner join loan_application_manifest_history t2 on t1.loan_application_manifest_history_id=t2.id and t2.funding_corp_id={}  and t2.transaction_status in (2,5)
 where date(t1.deadline)=date(t1.repayment_received_at) and t1.deadline >={} and  t1.deadline < {}
 group by t1.deadline
"""
# 时间维度逾期还款
time_version_yq_sql = """
  select date(t1.repayment_received_at) as hk_day, sum(t1.actual_repayment) yq  from repayment_record t1 
 inner join loan_application_manifest_history t2 on t1.loan_application_manifest_history_id=t2.id and t2.funding_corp_id={}  and t2.transaction_status in (2,5)
 where t1.repayment_received_at >= {} and t1.repayment_received_at < {}  and date(t1.repayment_received_at) > t1.deadline
 group by date(t1.repayment_received_at)
"""
# 时间维度提前还款
time_version_tq_sql = """
 select t1.deadline as hk_day ,sum(t1.actual_repayment) tq from repayment_record t1 
 inner join loan_application_manifest_history t2 on t1.loan_application_manifest_history_id=t2.id and t2.funding_corp_id={}  and t2.transaction_status in (2,5)
 where t1.deadline >={} and  t1.deadline < {}  and date(t1.repayment_received_at) < t1.deadline
 group by t1.deadline
"""

should_baofei_sql = """
select  t1.deadline hk_day,sum(t1.premium) should_amount from repayment_record t1 
inner join loan_application_manifest_history t2 on t1.loan_application_manifest_history_id=t2.id and t2.funding_corp_id={}  and t2.transaction_status in (2,5) and t1.term_no=1 
where t1.deadline >={} and t1.deadline < {}
group by t1.deadline
"""
yq_baofei_sql = """
select date(t1.repayment_received_at) hk_day,sum(t1.premium) yq_amount from repayment_record t1 
inner join loan_application_manifest_history t2 on t1.loan_application_manifest_history_id=t2.id and t2.funding_corp_id={}  and t2.transaction_status in (2,5) and t1.term_no=1 
where t1.repayment_received_at >= {} and t1.repayment_received_at < {} and date(t1.repayment_received_at) > t1.deadline 
group by date(t1.repayment_received_at)
"""


class xiaoying_peifu():
    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 loan_peifu(self):
        begin_time = self.start.strftime("'%Y-%m-%d'")
        end_time = self.end.strftime("'%Y-%m-%d'")
        df_peifu = pd.read_sql(sql=loan_version_sql.format(begin_time, end_time, begin_time, end_time,
                                                           begin_time, end_time, begin_time, end_time,
                                                           begin_time, end_time, begin_time, end_time), con=xyqb_conn)
        if len(df_peifu) == 0:
            return

        df_peifu.loan_id = df_peifu.loan_id.astype(str)

        df_loan = pd.read_sql(sql=query_loan_sql.format(str(tuple(df_peifu.loan_id)).replace(',)', ')')),
                              con=audit_conn)
        df_peifu_all = pd.merge(df_peifu, df_loan, how='left', on='loan_id')
        #df_peifu_all['fund_name'] = '小赢p2p'
        df_peifu_all['peifu_amount'] = df_peifu_all['should_repay_amount'] - df_peifu_all['act_repay_amount']

        df_peifu_all.rename(columns={
            'ref_id': 'ref_id', 'loan_id': 'loan_id', 'fund_name': '资金方', 'loan_paid_at': '放款时间',
            'act_repay_amount': '客户实还可用', 'should_repay_amount': '应还资金方', 'peifu_amount': '赔付'
        }, inplace=True)

        df_peifu_all.to_csv(os.path.join(self.dir_path, '小赢-loan维度赔付表-{}.csv'.format(self.start.strftime('%Y%m'))),
                            index=None, encoding='gbk')

    def time_peifu(self, fund_id, fund_name):
        begin_time = self.start.strftime("'%Y-%m-%d'")
        end_time = self.end.strftime("'%Y-%m-%d'")
        df_bx = pd.read_sql(sql=time_version_bx_sql.format(fund_id,begin_time, end_time), con=xyqb_conn)
        df_zc = pd.read_sql(sql=time_version_zc_sql.format(fund_id,begin_time, end_time), con=xyqb_conn)
        df_yq = pd.read_sql(sql=time_version_yq_sql.format(fund_id,begin_time, end_time), con=xyqb_conn)
        df_tq = pd.read_sql(sql=time_version_tq_sql.format(fund_id,begin_time, end_time), con=xyqb_conn)
        df_peifu_all = pd.merge(df_bx, df_zc, how='outer', on='hk_day')
        df_peifu_all = pd.merge(df_peifu_all, df_yq, how='outer', on='hk_day')
        df_peifu_all = pd.merge(df_peifu_all, df_tq, how='outer', on='hk_day')
        df_peifu_all.sort_values(by=['hk_day'], ascending=True)
        df_peifu_all['should_repay_amount'].fillna(value=0, inplace=True)
        df_peifu_all['zc'].fillna(value=0, inplace=True)
        df_peifu_all['yq'].fillna(value=0, inplace=True)
        df_peifu_all['tq'].fillna(value=0, inplace=True)
        df_peifu_all['peifu_amount'] = df_peifu_all['should_repay_amount'] - df_peifu_all['zc'] - df_peifu_all['yq'] - \
                                       df_peifu_all['tq']
        #df_peifu_all['fund_name'] = '小赢p2p'
        df_peifu_all['fund_name'] = fund_name
        df_peifu_all['month'] = df_peifu_all['hk_day'].apply(lambda x: pd.datetime.strftime(x, '%m'))

        df_peifu_all.rename(columns={
            'fund_name': '资金方', 'hk_day': '日期', 'should_repay_amount': '应还金额', 'zc': '正常还款金额',
            'yq': '逾期还款金额', 'tq': '提前还款可用金额', 'peifu_amount': '赔付金额', 'month': '月份'
        }, inplace=True)

        df_peifu_all.to_excel(os.path.join(self.dir_path, u'{}-时间维度赔付表-{}.xlsx'.format(fund_name,self.start.strftime('%Y%m'))), index=None)

    def baofei_peifu(self,fund_id,fund_name):
        df_should_peifu = pd.read_sql(
            sql=should_baofei_sql.format(fund_id,self.start.strftime("'%Y-%m-%d'"), self.end.strftime("'%Y-%m-%d'")),
            con=xyqb_conn)
        df_yq_peifu = pd.read_sql(
            sql=yq_baofei_sql.format(fund_id,self.start.strftime("'%Y-%m-%d'"), self.end.strftime("'%Y-%m-%d'")), con=xyqb_conn)
        df_peifu_all = pd.merge(df_should_peifu, df_yq_peifu, how='left', on='hk_day')
        df_yq_peifu_not_in_should = df_yq_peifu.loc[~df_yq_peifu['hk_day'].isin(df_should_peifu['hk_day'])]
        df_yq_peifu_not_in_should['should_amount'] = 0
        df_peifu_all = pd.concat([df_peifu_all, df_yq_peifu_not_in_should], ignore_index=True, axis=0)
        df_peifu_all['peifu_amount'] = df_peifu_all['should_amount'] - df_peifu_all['yq_amount']
        #df_peifu_all['fund_name'] = '小赢p2p'
        df_peifu_all['fund_name'] = fund_name

        df_peifu_all = df_peifu_all.sort_values(by=['hk_day'])

        df_peifu_all.rename(columns={
            'fund_name': '资金方', 'hk_day': '日期', 'should_amount': '应还保费', 'yq_amount': '逾期还款保费', 'peifu_amount': '赔付金额'
        }, inplace=True)

        df_peifu_all.to_excel(os.path.join(self.dir_path, u'{}-保费赔付表-{}.xlsx'.format(fund_name,self.start.strftime('%Y%m'))),index=None)

    def xiaoying_peifu_detail(self):
        self.loan_peifu()
        self.time_peifu(610, '小赢p2p')
        self.time_peifu(700, '小赢4')
        self.baofei_peifu(610, '小赢p2p')
        self.baofei_peifu(700, '小赢4')


if __name__ == '__main__':
    xiaoying_peifu().xiaoying_peifu_detail()
    print('======================xiaoying_peifu done===================================')