# -*- 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)

query_repay = """
select  h.channel_serial_number flow_id,t.order_id,h.merchant_order_no as loan_id from repay_order t
join hf_event_status_history h ON  h.order_id = t.order_id
where t.merchant_id =12 
and t.repay_status=3 
AND h.is_success=1
AND h.event_status=4
"""
query_bath = """
SELECT t1.channel_number flow_id,t2.order_id,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_repay = """
select  h.channel_serial_number flow_id,t.order_id,h.merchant_order_no as loan_id 
from repay_order t
join hf_event_status_history h ON  h.order_id = t.order_id
where t.merchant_id =12 
and t.repay_status=3 
AND h.is_success=1
AND h.event_status=4
AND h.channel_serial_number 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


def HF_fenzhang():
    # df = pd.read_excel(file_path + u'恒丰分账201709.xlsx')
    df = pd.read_excel(file_path + u'恒丰9月缺失2笔.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.current_repayment = df['current_repayment'].astype(float)
    df.current_repayment = df['current_repayment'].apply(lambda x: np.round(x, 2))
    df.flow_id = df['flow_id'].astype(str)
    flow_ids = df['flow_id'].unique().tolist()
    df_repay = pd.read_sql(query_repay % (str(tuple(flow_ids)).replace(',)', ')')), engine_pay_center)
    # df_repay = pd.read_sql(query_repay, engine_pay_center)
    df_repay.flow_id = df_repay['flow_id'].astype(str)
    # df_bath = pd.read_sql(query_bath % (str(tuple(flow_ids)).replace(',)', ')')), engine_pay_center)
    # df_loan = pd.concat([df_repay, df_bath], ignore_index=True, axis=0)
    df_loan = pd.merge(df_repay, df, on='flow_id')
    # df_loan.to_excel(u'E:/数据汇总/现金贷/恒丰分账/恒丰非批次分账还资金方.xlsx', index=None)
    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 = pd.merge(df_loan, df_re, on=['order_id', 'loan_id'])
    df_out = df[
        ['loan_id', 'repaid_at', 'ref_id', 'term_no', 'funding_code', 'deadline', 'principle', 'interest', 'punish_fee',
         'flow_id', 'current_repayment']]
    df_out.to_excel(u'E:/数据汇总/现金贷/恒丰分账/恒丰非批次分账还资金方.xlsx', index=None)
    df_out.to_sql('funding_repayment_record', con=engine_audit, if_exists='append', index=None)

HF_fenzhang()
