# -*- coding: utf-8 -*-

import datetime
import pandas as pd
from dateutil.relativedelta import relativedelta
import numpy as np
from sqlalchemy import create_engine

'''
@author linfang
1、针对每月支付宝钩稽完后，支付宝每笔流水校验
'''


#---------------配置变量项begin-----------------
#指定月份的支付宝流水
year = 2017
month = 7
#---------------配置变量项end-----------------


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

def get_zfb_data(year,month):
    start_time = datetime.datetime(year, month, 1, 0, 0, 0)
    end_time = start_time + relativedelta(months=+1)
    sql_zfb = '''
    select id record_id ,income from new_transaction.offline_alipay_record
    where transfer_time >= '%s' and transfer_time < '%s'
    ''' % (start_time,end_time)
    return  pd.read_sql(sql_zfb,engine_new_transaction)

# record_ids 列表形式，支付宝流水记录
def get_xjd_ref(record_ids):
    sql_xjd_ref = '''
    select record_id,ref_amount from new_transaction.xjd_repay_plan_repay_record_ref
    where repay_channel = 13 and record_id in %s
    ''' % str(tuple(record_ids)).replace(',)',')')
    return pd.read_sql(sql_xjd_ref,engine_new_transaction)

# record_ids  列表形式，支付宝流水记录
def get_bt_ref(record_ids):
    sql_bt_ref = '''
    select record_id,ref_amount from new_transaction.baitiao_repay_plan_repay_record_ref
    where repay_channel = 13 and record_id in %s
    ''' % str(tuple(record_ids)).replace(',)',')')
    return pd.read_sql(sql_bt_ref,engine_new_transaction)



if __name__ == '__main__':
    df_zfb=get_zfb_data(year,month)
    if len(df_zfb) > 0:
        df_zfb.record_id = df_zfb.record_id.astype(int)
        record_ids = df_zfb.record_id.tolist()
        df_xjd = get_xjd_ref(record_ids)
        df_bt = get_bt_ref(record_ids)
        df_all = pd.concat([df_xjd,df_bt],axis=0,ignore_index=True)
        df_all.record_id = df_all.record_id.astype(int)
        df_all = df_all.groupby('record_id')['ref_amount'].sum().reset_index()
        df_zfb = pd.merge(df_zfb,df_all,on='record_id',how='left')
        df_zfb.fillna(0,inplace=True)
        df_zfb=df_zfb.ix[df_zfb.ref_amount !=0]
        df_zfb['diff']=np.round(df_zfb['income'] - df_zfb['ref_amount'],2)
        print '-----异常的的数据-----\n',df_zfb.ix[df_zfb['diff'] != 0]
