# -*- coding:utf-8 -*-
# Author: Perry_Zhu

import datetime

import numpy as np
import pandas as pd
from sqlalchemy import create_engine

pd.options.mode.chained_assignment = None

engine_pay_center = create_engine(
    'mysql+mysqldb://syzhu_data_r:ulk0989742097y43@192.168.4.6:8066/payment_center?charset=utf8', echo=True)
engine_audit = create_engine(
    'mysql+mysqldb://yulong:ohVU1nPITynSZwR2@172.16.3.201:3306/test_shiyao?charset=utf8', echo=True)
engine_financial = create_engine(
    'mysql+mysqldb://bowang:in78u6ytgbhj56r@192.168.4.6:8066/financial_system?charset=utf8', echo=True)
query_bath = """
SELECT t1.channel_number flow_id,t2.order_id,t2.merchant_repay_order_no pay_order_no,
  t2.amount current_repayment,t2.merchant_order_no as loan_id 
FROM withdrawals_batch_order t1
JOIN withdrawals_order t2 ON t1.order_id=t2.batch_order_id
WHERE 
t1.is_success=1
AND t1.channel_number in %s
"""
query_daichang = """
SELECT
    t1.repayment_plan_id pay_order_no,
     t1.loan_id,
    t2.term_no,
     t2.deadline,
     t1.repayment_plan_id,
     t2.principal principle,
     t2.interest
FROM
	xjd_repayment_plan_status t1
JOIN xyqb_user_repayment_plan t2 ON t1.repayment_plan_id = t2.plan_id
WHERE
	t1.funding_compensation_status = 1
AND t1.funding_compensation_date>='%s'
AND t1.funding_compensation_date < '%s'
"""
query_ref_id = """
select loan_id,ref_id,funding_code from audit.loan_manifest WHERE is_active=1 AND loan_id in %s
"""
query_record = """
SELECT 
t1.order_id,
plan.ref_id,
plan.real_loan_id loan_id,
plan.term_no,
plan.fund_code funding_code,
plan.deadline,
(IFNULL(rf.principle,0)-IFNULL(rf.mitigate_principle,0))principle,
(IFNULL(rf.interest,0)-IFNULL(rf.mitigate_interest,0))interest ,
(IFNULL(rf.punish,0)-IFNULL(rf.mitigate_collection_relief,0))punish_fee 
FROM new_transaction.xjd_repay_plan_repay_record_ref rf
JOIN new_transaction.repay_record_online t1 ON rf.record_id=t1.id
JOIN new_transaction.user_repayment_plan plan ON plan.id=rf.plan_id
WHERE rf.repay_channel=20
AND t1.order_id in %s
"""

file_path = u'E:/数据汇总/现金贷/恒丰分账/'
year_begin = 2017
year_end = 2017
month_begin = 9
month_end = 10
begin_time = '2017-09-01'
end_time = '2017-10-01'


def HF_fenzhang():
    df = pd.read_excel(file_path + u'恒丰分账201709.xlsx')
    df.repaid_at = pd.to_datetime(df.repaid_at).dt.date
    df = df.ix[(df.repaid_at >= datetime.date(year_begin, month_begin, 1)) & (
        df.repaid_at < datetime.date(year_end, month_end, 1))]
    df = df[['flow_id', 'repaid_at']]
    df.flow_id = df['flow_id'].astype(str)
    flow_ids = df['flow_id'].unique().tolist()
    df_bath = pd.read_sql(query_bath % (str(tuple(flow_ids)).replace(',)', ')')), engine_pay_center)
    df_bath.current_repayment = df_bath['current_repayment'].apply(lambda x: np.round(x, 2))
    df_bath.flow_id = df_bath['flow_id'].astype(str)
    df_loan = pd.merge(df_bath, df, on='flow_id')
    df_loan.order_id = df_loan['order_id'].astype(str)
    order_ids = df_loan['order_id'].tolist()
    df_re = pd.read_sql(query_record % (str(tuple(order_ids)).replace(',)', ')')), engine_audit)
    df_out = pd.merge(df_loan, df_re, on=['order_id', 'loan_id'], how='left')
    # df_out.to_excel(u'E:/数据汇总/现金贷/恒丰分账/恒丰批次分账还资金方.xlsx', index=None)
    df_out['punish_fee'].fillna(0, inplace=True)
    df_1 = df_out.loc[df_out['ref_id'].notnull()]
    df_2 = df_out.loc[df_out['ref_id'].isnull()]
    df_1 = df_1[
        ['loan_id', 'repaid_at', 'ref_id', 'term_no', 'funding_code', 'deadline', 'principle', 'interest', 'punish_fee',
         'flow_id', 'current_repayment']]
    df_2 = df_2[['flow_id', 'repaid_at', 'pay_order_no', 'current_repayment']]
    df_2.pay_order_no = df_2['pay_order_no'].astype(str)
    df_d = pd.read_sql(query_daichang % (begin_time, end_time), engine_financial)
    df_d.pay_order_no = df_d.pay_order_no.astype(str)
    df_d1 = pd.merge(df_2, df_d, on='pay_order_no')
    df_d1.loan_id = df_d1.loan_id.astype(str)
    loan_ids = df_d1['loan_id'].tolist()
    df_ref = pd.read_sql(query_ref_id % (str(tuple(loan_ids)).replace(',)', ')')), engine_audit)
    df_ref.loan_id = df_ref.loan_id.astype(str)
    df_d2 = pd.merge(df_d1, df_ref, on='loan_id')
    df_d2['punish_fee'] = 0.00
    df_d2.to_excel(u'E:/数据汇总/现金贷/恒丰分账/恒丰批次代偿还资金方.xlsx', index=None)
    df_d2 = df_d2[
        ['loan_id', 'repaid_at', 'ref_id', 'term_no', 'funding_code', 'deadline', 'principle', 'interest', 'punish_fee',
         'flow_id', 'current_repayment']]
    df_ref_all = pd.concat([df_1, df_d2], axis=0, ignore_index=True)
    df_num = df_ref_all.groupby(['ref_id', 'term_no'])['loan_id'].agg(['count']).reset_index().rename(
        columns={'count': 'num'})
    df_d2 = pd.merge(df_d2, df_num, on=['ref_id', 'term_no'])
    # QG代偿后用户还款，QG将用户罚息分账给资金方，本息已经代偿，不用再次分账。
    df_d2.ix[(df_d2['num'] > 1) & (df_d2['punish_fee'] > 0), ['principle', 'interest']] = 0.00
    df_d2.drop(['num'], axis=1, inplace=True)
    df_d2['punish_fee'] = df_d2['current_repayment'] - df_d2['principle'] - df_d2['interest']
    df_d2.to_sql('funding_repayment_record', con=engine_audit, if_exists='append', index=None)
    df_1 = pd.merge(df_1, df_num, on=['ref_id', 'term_no'])
    df_1.ix[(df_1['num'] > 1) & (df_1['punish_fee'] > 0), ['principle', 'interest']] = 0.00
    df_1.drop(['num'], axis=1, inplace=True)
    df_1['punish_fee'] = df_1['current_repayment'] - df_1['principle'] - df_1['interest']
    df_1.to_sql('funding_repayment_record', con=engine_audit, if_exists='append', index=None)


HF_fenzhang()
