# -*- 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:/核对账单/去哪儿/去哪儿账单文件/2017'
# 去哪儿还款输出文件
out =  u'E:/核对账单/去哪儿/res/'
# 当前月份
this_month = '2017-05'
engine_qunaer = create_engine('mysql+mysqldb://yulong:ohVU1nPITynSZwR2@172.16.3.201:3306/qunaer_new?charset=utf8', echo=False).connect()
'''
@author linfang
1、去哪儿还款表
根据账单文件出表
'''

#还款记录
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)
    print '-------去哪儿还款总额----------',df['还款总额'].astype(float).sum()
    return df




if __name__ == '__main__':
    #还款记录
    df_repay=convert_repay()
    #放款记录---当月的放款+转分期+之前的数据
    sql_1='''
    SELECT product_no,loan_time,loan_amount,stages FROM `pay_detail` WHERE product_no in %s
    '''
    df_1=pd.read_sql(sql_1 % str(tuple(df_repay['产品编号'].astype(str).tolist())).replace(',)',')'),engine_qunaer)
    #每一笔的放款金额是不一致的,是需要判断是否发生了退款
    #这一块的放款金额有空再更新。
    df_1.rename(columns={'product_no':'产品编号','loan_time':'贷款时间','stages':'分期数'},inplace=True)
    #合并还款
    df_repay= pd.merge(df_repay, df_1[['产品编号', '贷款时间', '分期数']], on='产品编号', how='left')
    #输出
    df_repay[['产品编号', '贷款时间', '分期数','还款编号','还款时间','还款期数','还款总额','实还本金','实还服务费','实还罚息']].to_csv(os.path.join(out, 'repay_%s.csv' % this_month))