# -*- 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

year=2017
month = 7
engine_qunaer = create_engine('mysql+mysqldb://yulong:ohVU1nPITynSZwR2@172.16.3.201:3306/qunaer_new?charset=utf8', echo=False).connect()
#流水录入，首先复制录入的数据
#该流水录入的是 merchant_to_qg
def insert_flow():
    df = pd.read_clipboard()
    df.rename(columns={'交易日期': 'trans_time', '贷': 'trans_amount', '用途': 'remark', '交易流水号': 'flow_id'}, inplace=True)
    df['bank_name'] = '平安银行北京德胜门支行'
    df['merchant_name'] = '嘉信浩远'
    df['trans_time'] = df['trans_time'].apply(lambda x: datetime.datetime.strptime(str(x), '%Y%m%d'))
    df['trans_time'] = pd.to_datetime(df['trans_time'])
    df['status'] = 0
    ## 注意 是 merchant_to_qg
    df['trans_type'] = 2
    df = df[['trans_time', 'trans_amount', 'remark', 'flow_id', 'bank_name', 'merchant_name', 'status', 'trans_type']]
    df.to_sql('bank_flow', engine_qunaer, if_exists='append', index=False)

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_flow='''
select id,trans_amount,trans_time,flow_id from bank_flow where trans_time >= '%s' AND status = 0
''' % start_time

update_repay='''
update repay_detail set flow_id = %s where date(repay_time) = %s
'''

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=pd.merge(df_flow,df_repay,left_on='trans_amount',right_on='repay_amount',how='inner')
df.drop_duplicates(['trans_time'],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)
engine_qunaer.execute(update_repay,df[['flow_id','repay_time']].values.tolist())
engine_qunaer.execute(update_flow,df[['id']].values.tolist())




