# encoding: utf8
"""
    根据线上xyqb库的baitiao_bill_repayment_plan表中的红包值，更新new_transaction库user_bt_repayment_plan表中的红包金额
"""

import sys

import pandas as pd

reload(sys)
sys.setdefaultencoding("utf-8")
from sqlalchemy import create_engine

pd.options.mode.chained_assignment = None

engine_xyqb = create_engine('mysql+mysqldb://syzhu_data_r:ulk0989742097y43@192.168.4.6:8066/xyqb?charset=utf8',
                            echo=True)
engine_offline = create_engine('mysql+mysqldb://syzhu_data_r:ulk0989742097y43@192.168.4.6:8066/offline?charset=utf8',
                               echo=True)
engine_new_transaction = create_engine(
    'mysql+mysqldb://yulong:ohVU1nPITynSZwR2@172.16.3.201:3306/new_transaction?charset=utf8', echo=True)
engine_audit = create_engine('mysql+mysqldb://yulong:ohVU1nPITynSZwR2@172.16.3.201:3306/audit?charset=utf8', echo=True)
engine_xyqb_offline = create_engine('mysql+mysqldb://zhling_ofl_r:jiyng987ujki8@192.168.4.253:3306/xyqb?charset=utf8',
                                    echo=True)

user_bt_sql = """ 
  SELECT id plan_id,order_no,term_no,red_package 
  FROM user_bt_repayment_plan 
  WHERE sys_tag='XYQB_BILL_BT' AND red_package>0 
  AND biz_repaid_at>='%s' AND  biz_repaid_at<'%s'"""
ref_sql = """select plan_id ,collection_relief from baitiao_repay_plan_repay_record_ref WHERE  plan_id in %s """

update_ref_sql = """
update baitiao_repay_plan_repay_record_ref 
set mitigate_all=%s ,red_package_fee=%s 
WHERE  plan_id = %s """

start_time = '2017-09-01'
end_time = '2017-10-01'


# 主要用于更新baitiao_repay_plan_repay_record_ref关联
def udpate_ref():
    df = pd.read_sql(user_bt_sql % (start_time, end_time), engine_new_transaction)
    df['plan_id'] = df['plan_id'].astype(int)
    df['red_package'] = df['red_package'].astype(float)
    plan_ids = df['plan_id'].tolist()
    df_2 = pd.read_sql(ref_sql % (str(tuple(plan_ids)),), engine_new_transaction)
    df_2['plan_id'] = df_2['plan_id'].astype(int)
    df_2['collection_relief'] = df_2['collection_relief'].astype(float)
    df = pd.merge(df, df_2, on='plan_id')
    df['diff'] = df['collection_relief'] - df['red_package']
    df_not = df[df['diff'] < 0]
    df_good = df[df['diff'] >= 0]
    if len(df_not) > 0:
        df_not.to_excel(u"E:/baitiao/红包减免/不符合减免条件2017-08.xlsx", index=None)
        df_not['plan_id'] = df_not['plan_id'].astype(int)
        update_plan = """update new_transaction.user_bt_repayment_plan set red_package=0 WHERE  id = %s"""
        plan_ids = df_not[['plan_id']].values.tolist()
        engine_new_transaction.execute(update_plan, plan_ids)

    if len(df_good) > 0:
        df_good.to_excel(u"E:/baitiao/红包减免/符合减免条件2017-08.xlsx", index=None)
        values_list = df_good[['diff', 'red_package', 'plan_id']].values.tolist()
        engine_new_transaction.execute(update_ref_sql, values_list)


udpate_ref()