# -*- encoding: utf8 -*-
import sys
import os
from datetime import *
import numpy as np
import pandas as pd
from dateutil.relativedelta import relativedelta
from sqlalchemy import create_engine

reload(sys)
sys.setdefaultencoding("utf-8")
pd.options.mode.chained_assignment = None
# 去哪儿源文件
path = u'E:/量化派/去哪儿/去哪儿账单文件/201709'
# 当前月份
this_month = '2017-09'
engine_qunaer = create_engine('mysql+mysqldb://yulong:ohVU1nPITynSZwR2@172.16.3.201:3306/qunaer_new?charset=utf8', echo=False).connect()
'''
@author linfang
计算去哪儿在9月份的还款中，放款是保理的金额，按天进行统计
不计算债转后的保理的还款。
'''

#还款记录
def convert_repay():
    df=pd.DataFrame()
    for filename in os.listdir(path):
        f = os.path.join(path, filename)
        if os.path.isfile(f) and this_month in f and f.endswith('_LIANGHP_repaymentInfo.txt'):
            ff = file(f).readlines()
            while len(ff[-1]) == 0 or ff[-1].startswith('F|'):
                del ff[-1]
            if ff[0].startswith('H|'):
                del ff[0]
            df_tmp=pd.DataFrame(ff,columns=['Line'])
            df_tmp['产品编号']=df_tmp['Line'].apply(lambda x:x.strip().split('|')[1])
            df_tmp['还款编号'] = df_tmp['Line'].apply(lambda x: x.strip().split('|')[2])
            df_tmp['还款时间'] = df_tmp['Line'].apply(lambda x: x.strip().split('|')[3])
            df_tmp['还款期数'] = df_tmp['Line'].apply(lambda x: x.strip().split('|')[5])
            df_tmp['还款总额'] = df_tmp['Line'].apply(lambda x: x.strip().split('|')[6])
            df_tmp['实还本金'] = df_tmp['Line'].apply(lambda x: x.strip().split('|')[10])
            df_tmp['实还服务费'] = df_tmp['Line'].apply(lambda x: x.strip().split('|')[11])
            df_tmp['实还罚息'] = df_tmp['Line'].apply(lambda x: x.strip().split('|')[12])
            df=df.append(df_tmp)
    df['还款期数'] = df['还款期数'].astype(int)
    df.drop_duplicates(subset=['还款编号'], inplace=True)
    df.drop('Line',inplace=True)
    print '-------去哪儿还款总额----------',df['还款总额'].astype(float).sum()
    return df




if __name__ == '__main__':
    #还款记录
    df_repay=convert_repay()
    #放款记录---保理的放款
    sql_1='''
    SELECT product_no from qunaer_new.pay_detail where fund_code = 1 and product_no in %s
    '''
    df_1=pd.read_sql(sql_1 % str(tuple(df_repay['产品编号'].astype(str).tolist())).replace(',)',')'),engine_qunaer)

    df_repay = df_repay.ix[df_repay['产品编号'].isin(df_1.product_no)]
    #按天统计还款金额
    df_repay['还款时间'] = pd.to_datetime(df_repay['还款时间']).dt.date
    df_repay['还款总额']=df_repay['还款总额'].astype(float)
    df_repay=df_repay.groupby(['还款时间'])['还款总额'].sum().reset_index()
    df_repay.to_excel(u'E:/保理还款.xlsx',index=None,encoding='UTF-8')