# -*- 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://bo.wang:#mn89453YU9io80@172.16.3.201:3306/new_transaction?charset=utf8',
    echo=True)

engine_financial = 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)

'''
1、financial_system库获取策略红包数据
2、红包导入red_packet_detail
3、如果是备份库，则红包表名字要改动；不同的库名字不一样，相应的sql 中涉及的表名查看对应的要改动
'''

# 2615135

sql_xyqb = '''
SELECT t1.loan_application_history_id,t2.id plan_id, t1.curr_term_no xyqb_term_no,discount
FROM repay_xyqb_detail t1 JOIN  repayment_plan t2 ON t1.loan_application_history_id=t2.loan_application_history_id AND t1.curr_term_no=t2.term_no
 WHERE pay_center_repay_at>='2017-10-01' AND pay_center_repay_at<'2017-11-01' AND discount>0
'''

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
'''

sql_query_exist_plan = """
SELECT t2.repayment_plan_id red_plan_id,amount red_amount FROM red_packet_detail t1 JOIN user_repayment_plan t2 ON t1.ref_id=t2.ref_id AND t1.term_no=t2.term_no WHERE t2.repayment_plan_id in %s
"""

# 查询优惠劵金额
sql_query_coupon = '''
select t1.plan_id red_plan_id ,t1.coupon_amount coupon_amount
from repayment_plan_coupon t1
join repayment_plan t2 on t1.plan_id = t2.id
where t1.status = 1 AND t1.plan_id IN %s
'''
sql_update_red_package = """
UPDATE red_packet_detail SET amount=%s WHERE ref_id=%s AND loan_id="%s" AND term_no=%d LIMIT 1;
"""


def gen_update_sql(amount,ref_id,loan_id,term_no):
    print sql_update_red_package % (amount, ref_id, loan_id, term_no)
    return sql_update_red_package % (amount, ref_id, loan_id, term_no)


df = pd.read_sql(sql_xyqb, engine_financial)

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

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

df_red_exist_plan = pd.read_sql(sql_query_exist_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)

# 和已经录入的优惠劵相同
df_red_exist_plan['red_plan_id'] = df_red_exist_plan['red_plan_id'].astype(int)

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

df_new = pd.merge(df, df_plan, left_on='plan_id', right_on='repayment_plan_id', how='left')
df_new = pd.merge(df_new, df_red_exist_plan, left_on='plan_id', right_on='red_plan_id', how='left')
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']
df_new['diff_exist_red'] = df_new['plan_id'] - df_new['red_plan_id']

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

# 查询已经存在优惠劵的红包，同时把两项累加，防止重复执行，从线上取数据
diff_exist_red = df_new.ix[df_new['diff_exist_red'] == 0]
if len(diff_exist_red) > 0:
    print '已经录入优惠劵红包====== 数量 %s, 总金额 %s, plan_ids %s' % (
        len(diff_exist_red), diff_exist_red.discount.sum(),
        str(tuple(diff_exist_red['red_plan_id'].astype(int).tolist())))
    df_coupon_exist = pd.read_sql(sql=sql_query_coupon % str(tuple(diff_exist_red['red_plan_id'].astype(int).tolist())),
                                  con=engine_xyqb)
    df_coupon_exist.red_plan_id = df_coupon_exist.red_plan_id.astype(int)
    diff_exist_red = pd.merge(diff_exist_red, df_coupon_exist, how='inner', on='red_plan_id')
    diff_exist_red['discount'] = diff_exist_red['discount'] + diff_exist_red['coupon_amount']
    diff_exist_red = diff_exist_red[['real_loan_id', 'term_no', 'ref_id', 'discount']]
    diff_exist_red.rename(columns={'real_loan_id': 'loan_id', 'discount': 'amount'}, inplace=True)
    diff_exist_red.ref_id = diff_exist_red.ref_id.astype(int)
    diff_exist_red.loan_id = diff_exist_red.loan_id.astype(str)
    # diff_exist_red.apply(lambda row : gen_update_sql(row['amount'],row['ref_id'],row['loan_id'],row['term_no']),axis=1)


df_in = df_new.ix[(df_new['diff'] == 0) & (df_new['diff2'] == 0) & (df_new['diff_exist_red'] != 0)]
df_in = df_in[['real_loan_id', 'term_no', 'ref_id', 'discount']]
df_in.rename(columns={'real_loan_id': 'loan_id', 'discount': '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, chunksize=10000)
