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

reload(sys)
sys.setdefaultencoding("utf-8")
pd.options.mode.chained_assignment = None

'''
这个表数据，重点注意一个事： 如果是一个订单是转分期订单，那么未转分期之前的订单的还款计划，也有应还，
'''



path = u'E:/量化派/去哪儿/人工控制/放款表-现金流/'
engine_new_transaction = create_engine('mysql+mysqldb://yulong:ohVU1nPITynSZwR2@172.16.3.201:3306/qunaer_new?charset=utf8', echo=False).connect()


#--还款
def hk(year, month):
    start_time = datetime.date(year, month, 1)
    end_time = start_time + relativedelta(months=+1)
    sql_repay = '''
        select t1.product_no '产品编号' ,t1.current_stage_no '当期期数', t1.repay_principle '实还本金',0 '实还利息-直投模式下'
        from qunaer_new.repay_detail t1
        JOIN qunaer_new.pay_detail t2 on t1.product_no = t2.product_no and t1.repay_status = 1 AND t2.trans_time >= '%s' AND t2.trans_time < '%s'
        group by 1,2
    ''' % (start_time, end_time)
    df_repay = pd.read_sql(sql_repay, engine_new_transaction)
    return df_repay




def fk(year, month):
    start_time = datetime.date(year, month, 1)
    end_time = start_time + relativedelta(months=+1)
    sql_1 = '''
     select product_no 产品编号,fund_name 资金方, loan_time 贷款时间,loan_amount 合同放款金额,stages 分期数,case when is_ptf = 0 THEN FALSE when is_ptf = 1 THEN TRUE end as 是否为转分期订单号
     from pay_detail t1 
     join fund_corp t2 on t1.fund_code = t2.fund_code
     where trans_time >= '%s' and trans_time < '%s'
    ''' % (start_time, end_time)
    df_fk = pd.read_sql(sql_1, engine_new_transaction)
    return df_fk

def tk(year,month):
    start_time = datetime.date(year, month, 1)
    end_time = start_time + relativedelta(months=+1)
    sql_1 = '''
         select t1.product_no 产品编号,t3.fund_name 资金方, t1.refund_time 贷款时间,t1.refund_amount 合同放款金额,t2.stages 分期数,case when t2.is_ptf = 0 THEN FALSE when t2.is_ptf = 1 THEN TRUE end as 是否为转分期订单号
         from refund_detail t1
          JOIN pay_detail t2 on t1.product_no = t2.product_no 
          JOIN fund_corp t3 on t2.fund_code = t3.fund_code
         where t1.refund_time >= '%s' and t1.refund_time < '%s'
        ''' % (start_time, end_time)
    df_tk = pd.read_sql(sql_1, engine_new_transaction)
    return df_tk

def plan(year,month,table_name):
    start_time = datetime.date(year, month, 1)
    end_time = start_time + relativedelta(months=+1)
    sql_1 = '''
        select t1.product_no 产品编号,current_stage_no 应还期数,deadline 应还时间,principle 应还本金,0 `应还利息-直投模式下` 
        from %s t1
        JOIN pay_detail t2 on t1.product_no = t2.product_no and t2.fund_code = 1 
        where trans_time >= '%s' and trans_time < '%s'
    ''' % (table_name,start_time, end_time)
    sql_2='''
    select t1.product_no 产品编号,current_stage_no 应还期数,deadline 应还时间,principle 应还本金,interest `应还利息-直投模式下`
     from fund_repayment_plan t1
     JOIN pay_detail t2 on t1.product_no = t2.product_no 
     where trans_time >= '%s' and trans_time < '%s'
    ''' % (start_time,end_time)
    df_plan_1 = pd.read_sql(sql_1, engine_new_transaction)
    df_plan_2 = pd.read_sql(sql_2,engine_new_transaction)
    df_plan=pd.concat([df_plan_1,df_plan_2])
    return df_plan




def xjl(year, month):
    table_name='repayment_plan_2017%s' % (str(0)+str(month))
    df_fk=fk(year,month)
    df_tk=tk(year,month)
    df_hk=hk(year,month)
    df_plan=plan(year,month,table_name)
    #放款
    df=pd.merge(df_fk,df_plan,on=[u'产品编号'],how='left')
    #实还
    df=pd.merge(df,df_hk,left_on=[u'产品编号',u'应还期数'],right_on=[u'产品编号',u'当期期数'],how='left')
    #追加退款
    df=df.append(df_tk)
    #增加一列
    df[u'应还期数'].fillna(0,inplace=True)
    df[u'应还期数']=df[u'应还期数'].astype(int)
    df[u'唯一值']=df.apply(lambda x:str(x[u'产品编号'])+str(x[u'应还期数']),axis=1)
    df_id=df[u'唯一值']
    df.drop(u'唯一值',axis=1,inplace=True)
    df.insert(0, u'唯一值', df_id)
    df.fillna(0,inplace=True)
    #如果stages > 1 的放款金额为0
    df.ix[df[u'应还期数'] > 1,u'合同放款金额'] = 0
    df.to_csv(path+'qunaer_xjl_%s_%s.csv' % (year,month))


#
years = (2017,)
months = (1, 2, 3, 4, 5, 6, 7)
if __name__ == '__main__':
    # pool = mtp.Pool(processes=2)
    for year, month in product(years, months):
        xjl(year,month)
         # pool.apply_async(xjl, (year, month))
    # pool.close()
    # pool.join()
