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

import pandas as pd
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_new_transaction = create_engine(
    'mysql+mysqldb://yulong:ohVU1nPITynSZwR2@172.16.3.201:3306/new_transaction?charset=utf8', echo=True)
xyqb_sql = """ 
 SELECT DISTINCT order_no,term_no,red_packet_amount 
 FROM baitiao_bill_repayment_plan 
 WHERE red_packet_amount > 0 AND repaid_at>='%s' AND  repaid_at<'%s'"""

update_sql = """ 
  UPDATE user_bt_repayment_plan 
  SET red_package=%s 
  WHERE order_no=%s AND term_no=%s  AND sys_tag='XYQB_BILL_BT' """

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


def update_red_package():
    df = pd.read_sql(xyqb_sql % (start_time, end_time), engine_xyqb)
    if len(df) > 0:
        df['order_no'] = df['order_no'].astype(str)
        df['term_no'] = df['term_no'].astype(int)
        df['red_packet_amount'] = df['red_packet_amount'].astype(float)
        conditions = df[['red_packet_amount', 'order_no', 'term_no']].values.tolist()
        engine_new_transaction.execute(update_sql, conditions)
        df.to_excel(u'E:/baitiao/红包减免/需要更新的plan2017-09.xlsx')


update_red_package()
