# -*- encoding: utf8 -*-
import sys
import os
import datetime
import numpy as np
import pandas as pd
from sqlalchemy import create_engine
from dateutil.relativedelta import relativedelta
import math
reload(sys)
sys.setdefaultencoding("utf-8")
pd.options.mode.chained_assignment = None

engine_qunaer = create_engine('mysql+mysqldb://linfang.wang:#jkl3453YUGuo99@172.16.3.201:3306/qunaer_new?charset=utf8', echo=False).connect()

engine_btzt = create_engine('mysql+mysqldb://linfang.wang:&*uijknbghyt63er45@172.16.3.184:7306/xyqb_btzt?charset=utf8', echo=False)


'''
注意变量
执行完后，调整一笔的还款计划的应还服务费和实还服务费--为了同银行流水一致
SELECT * FROM `fund_repay_detail` WHERE TYPE=4 AND package_no = '201706' AND repay_fee_amount > 0
'''
# 取小数点 前两位
def get_2_flo(num):
    begin = str(num).find('.')
    if begin == -1:
        return round(begin, 2)
    return float(str(num)[:begin + 3])

# 小数向上取数
def get_2_ceil(num):
    begin = str(num).find('.')
    if begin == -1 :
        return round(begin, 2)
    else:
        if str(num).__len__() - begin > 3:
            return math.ceil(num*100) / 100
        else:
            return float(str(num)[:begin + 3])
#四舍五入
def get_2_round(num):
    begin = str(num).find('.')
    if begin == -1:
        return round(begin, 2)
    else:
        if str(num).__len__() - begin > 3:
            dot_3=int(str(num)[begin+3])
            if dot_3 >= 5:
                return get_2_flo(num)+0.01
            else:
                return get_2_flo(num)
        else:
            return float(str(num)[:begin + 3])


#TODO sql 中的变量注意
sql_plan='''
select product_no,current_stage_no,deadline,principle from qunaer_new.fund_repayment_plan
where date(deadline) = '2017-10-27'  and fund_code = 2
'''
sql_plan_fu='''
select product_no,current_stage_no,repay_principle principle from qunaer_new.fund_repay_detail
where fund_code=2 AND package_no = '2017024' AND TYPE IN (5,7)
'''

df_plan=pd.read_sql(sql_plan,engine_qunaer)
df_plan.deadline=pd.to_datetime(df_plan.deadline).dt.date

df_plan_fu=pd.read_sql(sql_plan_fu,engine_qunaer)

df_plan['repay_fee_amount']=df_plan['principle'].apply(lambda x:get_2_round(x * 0.01))
df_plan['repay_amount'] = np.round(df_plan['repay_fee_amount']+df_plan['principle'],2)
df_plan['repay_principle']=df_plan['principle']

df_plan_fu['repay_principle']=np.round(0-df_plan_fu['principle'],2)
df_plan_fu['repay_fee_amount']=df_plan_fu['principle'].apply(lambda x:-get_2_round(x * 0.01))
df_plan_fu['repay_amount']=np.round(df_plan_fu['repay_fee_amount']+df_plan_fu['repay_principle'],2)


df=pd.concat([df_plan[['product_no','current_stage_no','repay_amount','repay_principle','repay_fee_amount']],
             df_plan_fu[['product_no','current_stage_no','repay_amount','repay_principle','repay_fee_amount']]],ignore_index=True)

df.fillna(0,inplace=True)

#TODO 注意更新为具体的变量
df['repay_time']=datetime.date(2017,10,27)
df['flow_id']='3240791710271014300840'
df['package_time']=datetime.date(2017,9,26)
df['package_no'] = '201724'

df['status'] = 1
df['type'] = 4
df['fund_code'] = 2

# 这个和银行的流水金额进行比较，金额差异在5块内正常，如果金额超，那么数据绝对有问题
print df['repay_amount'].sum(),df['repay_principle'].sum(),df['repay_fee_amount'].sum()



# TODO 这儿一定要注意，数据没有问题在录入
# df.to_sql('fund_repay_detail',engine_qunaer,index=None,chunksize=10000,if_exists='append')
