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

import sys

import pandas as pd
import numpy as np
import re
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/test_linfang?charset=utf8',
                             echo=True)

record_info = """
SELECT DISTINCT t1.flow_id 
FROM audit.funding_repayment_record t1
-- join audit.loan_manifest t3 ON  t3.ref_id= t1.ref_id
WHERE  LOCATE(',',t1.flow_id)>0
AND t1.repaid_at>='%s'
AND t1.repaid_at<'%s'
-- AND (t3.loan_paid_at<'2016-12-01' OR t3.loan_paid_at>='2017-01-01')
"""

select_ref_amount = """
SELECT ref_amount,flow_id 
FROM basic.lkb_to_fund_ref 
WHERE flow_id='%s'
AND created_at >='%s'
AND is_mutil in(1,2)
"""

record_detail = """
SELECT id record_id,current_repayment 
FROM audit.funding_repayment_record WHERE LOCATE('%s',flow_id)>0
AND  id not in (
select record_id FROM  test_linfang.funding_repayment_record_temp
)"""
update_sql = """
update audit.funding_repayment_record t1
JOIN test_linfang.funding_repayment_record_temp t2 ON t1.id=t2.record_id
SET t1.flow_id=t2.flow_id;
"""
start_time = '2017-09-01'
end_time = '2017-10-01'

df_flows = pd.read_sql(record_info % (start_time, end_time), engine_audit)

if len(df_flows) > 0:
    for index, row in df_flows.iterrows():
        flows = row['flow_id'].split(',')
        for idx in xrange(len(flows)):
            f = flows[idx]
            ref_amount = 0
            df_ref = pd.read_sql(select_ref_amount % (f, end_time), engine_audit)
            df_detail = pd.read_sql(record_detail % f, engine_audit)
            df_detail.record_id = df_detail.record_id.astype(str)
            df_ref.ref_amount = df_ref['ref_amount'].apply(lambda x: np.round(x, 2))
            df_detail.current_repayment = df_detail['current_repayment'].apply(lambda x: np.round(x, 2))
            if len(df_ref) < 1:
                continue
            ref_amount = df_ref.loc[0]['ref_amount']
            result = pd.DataFrame(columns=['record_id', 'flow_id'])
            for i, repayment_row in df_detail.iterrows():
                current_repayment = repayment_row['current_repayment']
                p = re.compile('\d+(\.\d+)?')
                record_id = repayment_row['record_id']
                if p.match(record_id) is None:
                    continue
                else:
                    record_id = int(record_id)
                if ref_amount < 10:
                    break
                if i == (len(df_detail) - 1):
                    if (ref_amount - current_repayment) >= 0:
                        ref_amount = ref_amount - current_repayment
                        temp = pd.DataFrame([dict(record_id=record_id, flow_id=f), ])
                        result = result.append(temp, ignore_index=True)
                        df_detail.drop(i, inplace=True)
                    elif abs(ref_amount - current_repayment) <= 500:
                        ref_amount = ref_amount - current_repayment
                        temp = pd.DataFrame([dict(record_id=record_id, flow_id=f), ])
                        result = result.append(temp, ignore_index=True)
                        df_detail.drop(i, inplace=True)
                    else:
                        break
                else:
                    if (ref_amount - current_repayment) >= 0:
                        ref_amount = ref_amount - current_repayment
                        temp = pd.DataFrame([dict(record_id=record_id, flow_id=f), ])
                        result = result.append(temp, ignore_index=True)
                        df_detail.drop(i, inplace=True)
                    elif abs(ref_amount - current_repayment) <= 500:
                        ref_amount = ref_amount - current_repayment
                        temp = pd.DataFrame([dict(record_id=record_id, flow_id=f), ])
                        result = result.append(temp, ignore_index=True)
                        df_detail.drop(i, inplace=True)
                    else:
                        continue

            result.record_id = result.record_id.astype(int)
            result.to_sql('funding_repayment_record_temp', con=engine_audit, if_exists='append', index=None)
            engine_audit.execute(update_sql)
