# -*- coding:utf-8 -*-
# Author: Perry_Zhu
import sys

import pandas as pd
from sqlalchemy import create_engine

pd.options.mode.chained_assignment = None
reload(sys)
sys.setdefaultencoding('utf8')
engine_audit = create_engine('mysql+mysqldb://yulong:ohVU1nPITynSZwR2@172.16.3.201:3306/audit?charset=utf8',
                             echo=True)
select_record_ref = """
select t1.id record_id ,t2.flow_id
from funding_repayment_record t1 
JOIN basic.lkb_to_fund_ref t2 ON  t2.lkb_id=t1.lkb2fund_id
WHERE t2.created_at >='%s'
AND t1.repaid_at>='%s'
AND t1.repaid_at<'%s'
AND t2.is_mutil in(1,2)
-- join audit.loan_manifest t3 ON  t3.ref_id= t1.ref_id
-- WHERE  t2.is_mutil in(1,2)
 
"""
update_single = """
UPDATE audit.funding_repayment_record t1
JOIN basic.lkb_to_fund_ref ref ON t1.lkb2fund_id=ref.lkb_id 
SET t1.flow_id=ref.flow_id
WHERE t1.repaid_at>='%s'
AND t1.repaid_at<'%s'
AND ref.is_mutil=0
AND ref.created_at>='%s'
AND t1.lkb2fund_id is not NULL
"""

update_record = """update funding_repayment_record set flow_id=%s WHERE id =%s"""

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


def insert_flow_id():
    engine_audit.execute(update_single % (start_time, engine_audit, engine_audit))
    df_all = pd.read_sql(select_record_ref % (end_time, start_time, end_time), engine_audit, chunksize=5000)
    loop = True
    df_t = pd.DataFrame()
    while loop:
        try:
            df_t = df_t.append(df_all.next(), ignore_index=True)
            df_t = df_t.ix[df_t.flow_id.notnull()]
            df_t.record_id = df_t.record_id.astype(int)
            df_t.flow_id = df_t.flow_id.astype(str)
        except StopIteration:
            loop = False
    flow = df_t.groupby('record_id')['flow_id'].agg(lambda x: ','.join(set(x))).reset_index()
    flow.record_id = flow.record_id.astype(int)
    flow.flow_id = flow.flow_id.astype(str)
    update_values = flow[['flow_id', 'record_id']].values.tolist()
    engine_audit.execute(update_record, update_values, chunksize=5000)


insert_flow_id()
