# -*- coding: utf-8 -*-
import os
import sys
import datetime
import threading
from itertools import product
from threading import Thread
import numpy as np
import pandas as pd
from dateutil.relativedelta import relativedelta

from sqlalchemy import create_engine
import multiprocessing as mtp
reload(sys)
sys.setdefaultencoding('utf8')


engine_new_transaction = create_engine(
    'mysql+mysqldb://yulong:ohVU1nPITynSZwR2@172.16.3.201:3306/new_transaction?charset=utf8',
    echo=False)

engine_fs = create_engine(
    'mysql+mysqldb://bowang:in78u6ytgbhj56r@192.168.4.6:8066/financial_system?charset=utf8',
    echo=False)

engine_xyqb = create_engine(
    'mysql+mysqldb://bowang:in78u6ytgbhj56r@192.168.4.6:8066/xyqb?charset=utf8',
    echo=False)

'''
修复问题： 该月以还款但是没有关联上还款记录的数据，这部分数据可能是线下还款,可能是线上还款
'''

start_time='2017-08-01 00:00:00'
end_time='2017-09-01 00:00:00'

sql_1='''
SELECT id plan_id,real_loan_id,term_no FROM `user_repayment_plan` WHERE fund_code NOT IN (340) AND  repay_status = 3 AND xyqb_repaid_at >= '%s' AND xyqb_repaid_at < '%s' AND id NOT IN (SELECT plan_id FROM `xjd_repay_plan_repay_record_ref`)
''' % (start_time,end_time)

sql_3='''
select id record_id ,is_ref, business_flow from offline_alipay_record where business_flow in %s
'''

sql_2='''
  select a.id alipay_id,
  a.businessFlow, a.amount, a.time, r.biz_loan_no, r.curr_term, r.debt_funding_corp, t.transfer_amount
from
  repay_offline_record r
  join repay_offline_transfer_record t on r.id = t.repay_offline_record_id
  join off_line_alipay_order a on a.id = t.alipay_orderid
where  r.biz_type = 0 and  t.enable = 1 and r.enable = 1
  and r.repay_status in (
    'REPAY_BIZ_STATUS_OK',
    'REPAY_FINANCIAL_CONFIRM'
  )
  and r.biz_loan_no in %s
'''
#有还款无关联
df_1=pd.read_sql(sql_1,engine_new_transaction)
loan_ids=df_1.real_loan_id.astype(str).tolist()
df_1['real_loan_id']=df_1['real_loan_id'].astype(int)
df_1['term_no']=df_1['term_no'].astype(int)
#线下还款登记
df_2=pd.read_sql(sql_2 % str(tuple(loan_ids)),engine_fs)
df_2['biz_loan_no']=df_2['biz_loan_no'].astype(int)
df_2['curr_term']=df_2['curr_term'].astype(int)

df=pd.merge(df_1,df_2,left_on=['real_loan_id','term_no'],right_on=['biz_loan_no','curr_term'],how='left')
df.fillna(0,inplace=True)
print '==========未找到的还款====',df.ix[df.transfer_amount == 0]
#TODO===有可能是线上还款

df=df.ix[df.transfer_amount > 0]
business_flows=df.businessFlow.astype(str).tolist()
#还款记录
df_3=pd.read_sql(sql_3 % str(tuple(business_flows)).replace(',)',')'),engine_new_transaction)
df=pd.merge(df,df_3,left_on='businessFlow',right_on='business_flow',how='left')
print '==================已关联的还款===========',df.ix[df['is_ref'] == 1]
df=df.ix[df['is_ref'] == 0]
#
df=df.merge(df.groupby(by='record_id')['transfer_amount'].agg({'sum'}).reset_index().rename(columns={'sum':'sum_by_record_id'}))
df['diff']=np.round(df['amount']-df['sum_by_record_id'],2)

print '=====不一致的金额====',df.ix[df['diff'] != 0]

df_in=df.ix[df['diff'] == 0]
df_in['ref_amount']=df_in['transfer_amount']
df_in=df_in[['plan_id','record_id','ref_amount']]
df_in['repay_channel']=13

# df_in.to_sql('xjd_repay_plan_repay_record_ref', con=engine_new_transaction, if_exists='append', index=None)






