# -*- coding: utf-8 -*-
import pandas as pd
from sqlalchemy import create_engine

pd.options.mode.chained_assignment = None

engine_audit = create_engine('mysql+mysqldb://yulong:ohVU1nPITynSZwR2@172.16.3.201:3306/audit?charset=utf8', echo=True)
engine_audit_select = create_engine('mysql+mysqldb://yulong:ohVU1nPITynSZwR2@172.16.3.201:3306/audit?charset=utf8',
                                    echo=True)
select_sql = '''
  select source_corp,funding_code,ref_id,loan_id,loan_paid_at,contract_loan_amount,loan_paid_at as debt_time 
    from loan_manifest 
    WHERE funding_code in(330,363) 
    AND source_corp!=funding_code 
    AND  loan_paid_at>='%s'
    AND  loan_paid_at<'%s'  '''
insert_sql = '''
  insert into funding_debet_transfer
  (src_funding_code,dest_funding_code,ref_id,loan_id,loan_paid_at,money_value,debt_time) 
  VALUES (%s,%s,%s,%s,%s,%s,%s)'''

select_exist = """select src_funding_code,dest_funding_code,ref_id from funding_debet_transfer WHERE ref_id in %s"""
update_sql = '''
        update funding_debet_transfer 
        set 
          loan_id=%s,loan_paid_at=%s,money_value=%s,debt_time=%s 
        WHERE  ref_id=%s AND src_funding_code=%s AND dest_funding_code=%s '''

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


def insert_debet():
    df1 = pd.read_sql(select_sql % (start_time, engine_audit), con=engine_audit_select, chunksize=1000)
    loop = True
    while loop:
        try:
            df_all = pd.DataFrame()
            df_all = df_all.append(df1.next(), ignore_index=True)
            df_all.ref_id = df_all.ref_id.astype(int)
            va = df_all['ref_id'].tolist()
            df_e = pd.read_sql(select_exist % str(tuple(va), ), engine_audit_select)
            if len(df_e) > 0:
                df_e.ref_id = df_e.ref_id.astype(int)
                df_exist = df_all.merge(df_e, how='inner', on='ref_id')
                if len(df_exist):
                    df_all = df_all.ix[~df_all.ref_id.isin(df_exist.ref_id)]
                    update_values = df_exist[
                        ['loan_id', 'loan_paid_at', 'contract_loan_amount', 'debt_time', 'ref_id', 'source_corp',
                         'funding_code']].values.tolist()
                    engine_audit.execute(update_sql, update_values)
            if len(df_all) > 0:
                data = df_all[
                    ['source_corp', 'funding_code', 'ref_id', 'loan_id', 'loan_paid_at', 'contract_loan_amount',
                     'debt_time']].values.tolist()
                engine_audit.execute(insert_sql, data)
        except StopIteration:
            loop = False


# insert_debet()

step = 10000


def update_debet():
    file_path = u'E:/xyqb/2017年资金方放款-微微提供/201709/放款明细简版/'
    df = pd.read_excel(file_path + u"广源小贷（书桔债转真融宝）放款明细——201709月（简版）.xlsx", converters={'loan_id': int})
    df.to_sql('funding_debet_transfer', con=engine_audit, chunksize=step, if_exists='append', index=None)

update_debet()