# -*- encoding: utf8 -*-
import sys
import datetime
import pandas as pd
import numpy as np
from sqlalchemy import create_engine
from dateutil.relativedelta import relativedelta
reload(sys)
sys.setdefaultencoding("utf-8")
pd.options.mode.chained_assignment = None


'''
1、注意检查是否有流水未勾稽上
2、如果流水能对上，那么 bank_flow.status = 1 对不上，则 bank_flow.status=0
3、这个目标是核对用户的还款和退款金额 一定可以同 资金流对上；一般偶尔会出现 少打款或者 多打款，基本就是1,2笔的情况
   出现差异的情况，可以同都江堰库进行比较下，后续可以加入白条直投进行比较（后续主要是哈银）
'''


year=2017
month = 10
engine_qunaer = create_engine('mysql+mysqldb://linfang.wang:#jkl3453YUGuo99@172.16.3.201:3306/qunaer_new?charset=utf8', echo=False).connect()

start_time =datetime.datetime(year,month,1,0,0,0)

sql_repay='''
select date(repay_time) repay_time,sum(repay_amount) repay_amount 
from repay_detail 
 WHERE repay_time >= '%s' AND flow_id is NULL 
 group by 1
''' % start_time

sql_refund='''
select date(refund_time) repay_time,-sum(refund_amount) repay_amount
from qunaer_new.refund_detail
where refund_time >= '%s' and flow_id is NULL AND refund_status=1
group by 1
''' % start_time

sql_flow='''
select id,trans_amount,trans_time,flow_id from bank_flow where trans_time >= '%s' AND status = 0 AND trans_type = 2
''' % start_time

update_repay='''
update repay_detail set flow_id = %s where date(repay_time) = %s
'''
update_refund='''
update refund_detail set flow_id = %s where date(refund_time) = %s and refund_status=1
'''
update_flow='''
update bank_flow set status = 1 where id = %s
'''

df_flow=pd.read_sql(sql_flow,engine_qunaer)
df_repay=pd.read_sql(sql_repay,engine_qunaer)
df_refund=pd.read_sql(sql_refund,engine_qunaer)
df_repay=pd.concat([df_repay,df_refund],ignore_index=True)
df_repay=df_repay.groupby('repay_time')['repay_amount'].sum().reset_index()

df=pd.merge(df_flow,df_repay,left_on='trans_amount',right_on='repay_amount',how='inner')
df.drop_duplicates(['flow_id'],inplace=True)
df['repay_time'] = pd.to_datetime(df['repay_time']).dt.date
df['repay_time']=df['repay_time'].astype(str)
df['flow_id']=df['flow_id'].astype(str)
df['diff']=np.round(df['trans_amount'] - df['repay_amount'],2)
df=df.ix[df['diff'] == 0]
engine_qunaer.execute(update_repay,df[['flow_id','repay_time']].values.tolist())
engine_qunaer.execute(update_refund,df[['flow_id','repay_time']].values.tolist())
engine_qunaer.execute(update_flow,df[['id']].values.tolist())
