# -*- coding: utf-8 -*-
import os
import sys
import datetime
import threading
from itertools import product
from threading import Thread

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 = engine_new_transaction = create_engine(
    'mysql+mysqldb://yulong_rw:TouBStYwN8wkdxVt@172.16.3.201:3306/new_transaction?charset=utf8',
    echo=True)

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

'''
前提：还款计划已完成录入
1、xyqb库获取红包数据
2、红包导入red_packet_detail
3、如果是备份库，则红包表名字要改动；不同的库名字不一样，相应的sql 中涉及的表名查看对应的要改动
'''

sql_xyqb='''
select t1.plan_id ,t1.coupon_amount,t2.loan_application_history_id,term_no xyqb_term_no
from repayment_plan_coupon t1
join repayment_plan t2 on t1.plan_id = t2.id
where t1.status = 1 and t1.updated_at >= '2017-04-01 00:00:00' and t1.updated_at < '2017-05-01 00:00:00'
'''

sql_plan='''
select real_loan_id,ref_id,term_no,repayment_plan_id from new_transaction.user_repayment_plan where sys_tag='XYQB' and  repayment_plan_id in %s
'''

df=pd.read_sql(sql_xyqb,engine_xyqb)

plan_ids=df.plan_id.astype(int).tolist()

df_plan=pd.read_sql(sql_plan % str(tuple(plan_ids)),engine_new_transaction)

df['plan_id']=df['plan_id'].astype(int)
df['loan_application_history_id']=df['loan_application_history_id'].astype(int)
df['xyqb_term_no']=df['xyqb_term_no'].astype(int)

df_plan['repayment_plan_id']=df_plan['repayment_plan_id'].astype(int)
df_plan['real_loan_id']=df_plan['real_loan_id'].astype(int)
df_plan['term_no']=df_plan['term_no'].astype(int)

if len(df) != len(df_plan):
    print '红包数据量 与还款计划数量不等'

df_new=pd.merge(df,df_plan,left_on='plan_id',right_on='repayment_plan_id',how='outer')

df_new.fillna(0,inplace=True)

df_new['diff']=df_new['loan_application_history_id'] -df_new['real_loan_id']
df_new['diff2']=df_new['xyqb_term_no'] - df_new['term_no']

print '未找到匹配的数据=====',df_new.ix[df_new['diff'] != 0]
print '未找到匹配的数据======',df_new.ix[df_new['diff2'] != 0]

df_in=df_new.ix[(df_new['diff'] ==0) & (df_new['diff2'] ==0)]
df_in=df_in[['real_loan_id','term_no','ref_id','coupon_amount']]
df_in.rename(columns={'real_loan_id':'loan_id','coupon_amount':'amount'},inplace=True)
print '红包总额===',df_in.amount.sum()
#TODO 注意插入的红包表名字  engine_new_transaction 注意这个变量库的名字
df_in.to_sql(name='red_packet_detail',con=engine_new_transaction,if_exists='append',index=None)









