# -*- encoding: utf8 -*-
import sys
import datetime
import numpy as np
import math
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

'''
资金方，凡是在 pay_detail.fund_code != 1 的均为外保，即需要生成还资金方还款计划
2017.8.22-2017.9.22 惠金所，统一 1 期，30天
'''

engine_qunaer = create_engine('mysql+mysqldb://yulong:ohVU1nPITynSZwR2@172.16.3.201:3306/qunaer_new?charset=utf8', echo=False).connect()

# 取小数点 前两位
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])


#步骤1  首先 放款订单生成还款计划
# product_no , term,deadline,principle,fee_amount status = 0(init)
# 生成还款计划表 repayment_plan_2017
def step_1(year,month,is_ptf=False,product_no='',insert_db=False):
    start_time = datetime.datetime(year, month, 1, 0, 0, 0)
    end_time = start_time + relativedelta(months=+1)
    sql_pay = '''
       select fund_code,product_no,rate,loan_amount,stages,loan_time from pay_detail
          where status = 1 and fund_code != 1 and trans_time >= '%s' and trans_time < '%s'
    ''' % (start_time, end_time)

    if product_no.__len__() > 0 :
        sql_pay = '''
        select fund_code,product_no,rate,loan_amount,stages,loan_time from pay_detail
        where product_no='%s'
        ''' % product_no
    df_pay = pd.read_sql(sql_pay,engine_qunaer,chunksize=5000)
    for df in df_pay:
        df.loan_time = pd.to_datetime(df.loan_time).dt.date
        list_tmp=[]
        # 等本等息--- 目前只有1期，故利息计算统一为 1%
        for index,row in df.iterrows():
            stages=int(row['stages'])
            avg_principle = get_2_flo(row['loan_amount'] / stages)
            first_principle = round(row['loan_amount'] - avg_principle *(stages - 1),2)
            fund_code=int(row['fund_code'])
            # 不使用账单文件中的应还服务费，这个是去哪儿进行了处理的数据
            # 初始化还款计划
            for i in range(1, stages + 1, 1):
                if i==1:
                    #四舍五入
                    interest = get_2_round(stages * row['loan_amount'] * 0.01)
                    deadline = row['loan_time'] + relativedelta(days=+30)
                    list_tmp.append([fund_code,row['product_no'], 1, deadline, first_principle, interest, 1])
                else:
                    print '暂不支持多期数'
        df_tmp = pd.DataFrame(list_tmp,columns=['fund_code','product_no','current_stage_no','deadline','principle','interest'])
        df_tmp['require_fee']=df_tmp['principle']+df_tmp['interest']
        if insert_db:
            df_tmp.to_sql('fund_repayment_plan',engine_qunaer,index=None,chunksize=10000,if_exists='append')
