# -*- coding:utf-8 -*-
# Author: Perry_Zhu
import numpy as np
import pandas as pd
import sys
from sqlalchemy import create_engine

pd.options.mode.chained_assignment = None

reload(sys)
sys.setdefaultencoding('utf8')
engine_new_transaction = create_engine(
    'mysql+mysqldb://yulong:ohVU1nPITynSZwR2@172.16.3.201:3306/new_transaction?charset=utf8',
    echo=True)
engine_pay_center = create_engine(
    'mysql+mysqldb://syzhu_data_r:ulk0989742097y43@192.168.4.6:8066/payment_center?charset=utf8', echo=True)

bill_start_time = '2017-08-01'
bill_end_time = '2017-09-01'
path = "E:/baitiao/baitiao_cash/2017-08/"

sql_record = """
  select DISTINCT order_id 
  from repay_record_online 
  where pay_approach = 18
    and enable = 1 and is_ref = 0 
    AND  bill_time>='%s' 
    AND bill_time<'%s'
    AND id in (
    19360735,19360737,19360813,19360815,19360843,19360851,19360853,19360855,19360885,19360889,19360891,19360893,19360895,19360897,19360903,19360905,19360907,19360909,19360911,19360913,19360915,19360917,19360921,19360943,19360945,19360947,19360955,19360957,19360959,19360961,19360963,19360965,19360967,19360977
    )
    GROUP BY order_id
    HAVING sum(amount)!=0
"""
select_repay = """
 select id record_id,amount ref_amount,order_id ,bill_time
  from repay_record_online 
  where pay_approach = 18
    and enable = 1 and is_ref = 0 
    AND  bill_time>='%s' 
    AND bill_time<'%s'
    AND order_id in %s
"""

sql_pay_center = """
  select order_id, merchant_order_no order_no, merchant_id 
  from repay_order t 
  where t.repay_status = 3
  -- and merchant_id=10
   AND pay_approach = 6
   and t.order_id in %s
"""
sql_order = """
SELECT t1.id repay_id, t1.order_no,t2.real_loan_amount ref_amount
FROM baitiao_cash_repay t1 
JOIN baitiao_audit.baitiao_order t2 ON t1.ref_id =t2.ref_id
WHERE t2.is_active in(1,-2)
AND t2.order_no in %s
"""

update_is_ref = """update repay_record_online set is_ref =1 WHERE id in %s """


def refund_online():
    df_record = pd.read_sql(sql=sql_record % (bill_start_time, bill_end_time), con=engine_new_transaction)

    # for df_record in df_all:
    if len(df_record) > 0:
        df_record.order_id = df_record.order_id.astype(str)
        order_id_list = df_record.order_id.unique().tolist()
        df_real = pd.read_sql(
            select_repay % (bill_start_time, bill_end_time, str(tuple(order_id_list)).replace(',)', ')')),
            con=engine_new_transaction)
        df_pay_center = pd.read_sql(sql=sql_pay_center % str(tuple(order_id_list)).replace(',)', ')'),
                                    con=engine_pay_center)
        df_pay_center.order_id = df_pay_center.order_id.astype(str)
        df_record = pd.merge(df_real, df_pay_center, on='order_id')
        df_record_not = df_real.ix[~df_real['order_id'].isin(df_record['order_id'])]
        df_record.order_no = df_record.order_no.astype(str)
        if len(df_record_not) > 0:
            with open(path + 'record_not_in_pay_center.csv', 'a') as f:
                df_record_not.to_csv(f, index=None)
        if len(df_record) > 0:
            with open(path + 'record_is_in_pay_center.csv', 'a') as f:
                df_record.to_csv(f, index=None)
            df_record['ref_amount'] = df_record['ref_amount'].apply(lambda x: np.round(x, 2))
            df_record = df_record[['bill_time', 'record_id', 'ref_amount', 'order_no']]
            order_no_list = df_record.order_no.astype(str).unique().tolist()
            df_plan = pd.read_sql(sql=sql_order % str(tuple(order_no_list)).replace(',)', ')'),
                                  con=engine_new_transaction)
            if len(df_plan) > 0:
                df_plan.order_no = df_plan.order_no.astype(str)
                df_plan.repay_id = df_plan.repay_id.astype(int)
                df_plan['ref_amount'] = df_plan['ref_amount'].apply(lambda x: np.round(x, 2))
                df_1 = pd.merge(df_plan, df_record, on=['order_no', 'ref_amount'])
                df_n = df_record.ix[~df_record['record_id'].isin(df_1['record_id'])]
                if len(df_n) > 0:
                    # df_n.drop(['ref_amount_str', 'uniqueness_no'], axis=1, inplace=True)
                    with open(path + u'not_in_repay.csv', 'a') as f:
                        df_n.to_csv(f, index=None)
                if len(df_1) > 0:
                    df_i = df_1[['repay_id', 'record_id', 'ref_amount']]
                    df_i['repay_channel'] = 7
                    df_i.to_sql('baitiao_cash_record_ref', con=engine_new_transaction, if_exists='append', index=None)
                    record_ids = df_i['record_id'].astype(int).tolist()
                    # pd.read_sql(update_is_ref % (str(tuple(record_ids)).replace(',)', ')'),), con=engine_new_transaction)
                    engine_new_transaction.execute(update_is_ref % (str(tuple(record_ids)).replace(',)', ')'),))
            else:
                with open(path + u'no_baitiao_cash_record.csv', 'a') as f:
                    df_record.to_csv(f, index=None)


select_alipay = """
select id record_id,outcome ref_amount,business_flow  
FROM offline_alipay_record WHERE outcome<0 AND business_flow in %s 
"""
select_cash_repay = """
select id repay_id,order_no financial_flow from baitiao_cash_repay WHERE  order_no in %s AND real_order_amount<0
"""
update_off_ali_ref = """update offline_alipay_record set is_ref =1 WHERE id in %s """


def refund_offline():
    df = pd.read_excel(u'E:/baitiao/易联易宝退款/退款数据-7月份.xlsx',
                       converters={u'电话': str, u'订单号': str, u'流水号/银行订单号': str, u'退款金额': float})
    df.rename(columns={u'姓名': 'user_name',
                       u'支付宝账号/银行账户': 'alipay_account',
                       u'电话': 'phone_no_remark',
                       u'实际退款日期（流水日期）': 'transfer_time',
                       u'退款金额': 'outcome',
                       u'还款计划ID/期数': 'remark',
                       u'业务类型': 'repay_type',
                       u'流水号/银行订单号': 'business_flow',
                       u'订单号': 'financial_flow'
                       }, inplace=True)
    df = df.ix[df['repay_type'] == '现金支付']
    df = df[['business_flow', 'financial_flow']]
    if len(df) > 0:
        flow_ids = df.business_flow.astype(str).unique().tolist()
        order_nos = df.financial_flow.astype(str).unique().tolist()
        df_record = pd.read_sql(select_alipay % str(tuple(flow_ids)).replace(',)', ')'), engine_new_transaction)
        df_plan = pd.read_sql(select_cash_repay % str(tuple(order_nos)).replace(',)', ')'), engine_new_transaction)
        df_1 = pd.merge(df, df_record, on='business_flow')
        df_2 = pd.merge(df_1, df_plan, on='financial_flow')
        df_2['ref_amount'] = df_2['ref_amount'].apply(lambda x: np.round(x, 2))
        df_3 = df_2[['repay_id', 'record_id', 'ref_amount']]
        with open(path + u'refund.csv', 'a') as f:
            df_3.to_csv(f, index=None)
        df_3.to_sql('baitiao_cash_record_ref', con=engine_new_transaction, if_exists='append', index=None)
        record_ids = df_3['record_id'].astype(int).unique().tolist()
        print record_ids
        engine_new_transaction.execute(update_off_ali_ref % (str(tuple(record_ids)).replace(',)', ')'),))


# refund_offline()
refund_online()
