# encoding: utf8
import sys

import pandas as pd

"""
该代码用于更新funding_repament_record的lkb2_fund_id（对资金方的还款明细进行匹配流水）
"""
reload(sys)
sys.setdefaultencoding("utf-8")

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_transfer_amount = """ SELECT id,transfer_amount FROM lkb_to_fund WHERE transfer_time>='%s' AND  transfer_time<'%s' AND fund_corp = '%s'  ORDER BY transfer_time"""
select_repayment = """ select id,current_repayment from funding_repayment_record   where lkb2fund_id is NULL AND repaid_at >='%s' AND repaid_at<'%s' AND funding_code = %s ORDER BY repaid_at """
select_repayment_js = """ select id,current_repayment from funding_repayment_record   where lkb2fund_id is NULL AND repaid_at >='%s' AND repaid_at<'%s' AND funding_code IN (180,300) ORDER BY repaid_at """
select_repayment_bh = """ select id,current_repayment from funding_repayment_record   where lkb2fund_id is NULL AND repaid_at >='%s' AND repaid_at<'%s' AND funding_code IN (270,310,320) ORDER BY repaid_at """
select_repayment_hubei = """ select id,current_repayment from funding_repayment_record   where lkb2fund_id is NULL AND repaid_at >='%s' AND repaid_at<'%s' AND funding_code=290 AND remark is null ORDER BY repaid_at """
update_repayment = """ update funding_repayment_record set lkb2fund_id=%s where id =%s """
insert_lkb2fund_check = """ insert into  lkb2fund_check(lkb_id,diff_amount) values(%s,%s)  """

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

funding_groups = {
    '150': '华融消费',
    '230': '口袋理财',
    '240': '小赢理财',
    '210': '广源小贷',
    '190': '投之家',
    '220': '新考拉',
    '160': '新马上',
    '180': '晋商',
    '250': '桔子理财',
    '140': '新洋钱罐',
    '141': '洋钱灌_债转',
    '270': '渤海',
    '310': '渤海华瑞二期',
    '320': '渤海-中合',
    '290': '湖北消金',
    '40': '点融',
    '200': '科易小贷',
    '260': '米庄理财',
    '120': '网贷天眼',
    '170': '考拉',
    '5': '融贝',
    '90': '金融圈',
    '280': '阳光保险',
    '110': '青蚨',
    '4': '青蚨自主放贷',
    '29': '马上金融',
    '251': '橘子理财误回购',
    '252': '橘子理财回购资金方',
    '330': '阳光广源',
    '340': '阳光-徽商',
    '350': '众网小贷',
    '360': '随手记',
    '363': '沐金农',
    '415': '听枫雨',
    '365': '真融宝'
}


def fundingRepaymentRecodToLKB():
    for key, value in funding_groups.items():
        result = pd.DataFrame(columns=['record_id', 'lkb_id'])
        if key == '180':
            df_repayment = pd.read_sql(select_repayment_js % (start_time, end_time), con=engine_audit)
        elif key == '270':
            df_repayment = pd.read_sql(select_repayment_bh % (start_time, end_time), con=engine_audit)
        elif key == '290':
            df_repayment = pd.read_sql(select_repayment_hubei % (start_time, end_time), con=engine_audit)
        else:
            df_repayment = pd.read_sql(select_repayment % (start_time, end_time, key), con=engine_audit)
        df_repayment['id'] = df_repayment['id'].astype(int)
        df_repayment['current_repayment'] = df_repayment['current_repayment'].astype(float)
        df_lkb = pd.read_sql(select_transfer_amount % (start_time, end_time, value), con=engine_audit_select)
        df_lkb['id'] = df_lkb['id'].astype(int)
        df_lkb['transfer_amount'] = df_lkb['transfer_amount'].astype(float)
        if len(df_lkb) < 1:
            continue
        for index, row in df_lkb.iterrows():
            transfer_amount = row['transfer_amount']
            lkb_id = int(row['id'])
            if len(df_repayment) < 1:
                break
            for idx, repayment_row in df_repayment.iterrows():
                current_repayment = repayment_row['current_repayment']
                record_id = int(repayment_row['id'])
                if transfer_amount < 10:
                    break
                if idx == (len(df_repayment) - 1):
                    if (transfer_amount - current_repayment) >= 0:
                        transfer_amount = transfer_amount - current_repayment
                        temp = pd.DataFrame([dict(record_id=record_id, lkb_id=lkb_id), ])
                        result = result.append(temp, ignore_index=True)
                        df_repayment = df_repayment.drop(idx)
                    elif abs(transfer_amount - current_repayment) <= 300:
                        transfer_amount = transfer_amount - current_repayment
                        temp = pd.DataFrame([dict(record_id=record_id, lkb_id=lkb_id), ])
                        result = result.append(temp, ignore_index=True)
                        df_repayment = df_repayment.drop(idx)
                    else:
                        break
                else:
                    if (transfer_amount - current_repayment) >= 0:
                        transfer_amount = transfer_amount - current_repayment
                        temp = pd.DataFrame([dict(record_id=record_id, lkb_id=lkb_id), ])
                        result = result.append(temp, ignore_index=True)
                        df_repayment = df_repayment.drop(idx)
                    elif abs(transfer_amount - current_repayment) <= 300:
                        transfer_amount = transfer_amount - current_repayment
                        temp = pd.DataFrame([dict(record_id=record_id, lkb_id=lkb_id), ])
                        result = result.append(temp, ignore_index=True)
                        df_repayment = df_repayment.drop(idx)
                    else:
                        continue
        if len(result) > 0:
            result['record_id'] = result['record_id'].astype(int)
            result['lkb_id'] = result['lkb_id'].astype(int)
            val_list = result[['lkb_id', 'record_id']].values.tolist()
            engine_audit.execute(update_repayment, val_list)


fundingRepaymentRecodToLKB()
