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


'''
表头：loan_id,ref_id,合同号，放款时间，放款金额，放款账户，渠道流水号，第一期客户应还时间，第一期客户应还金额。。。。。第n期客户应还时间，第n期客户应还金额
'''

path='E:/hk/xjd/'
engine_new_transaction = create_engine('mysql+mysqldb://yulong:ohVU1nPITynSZwR2@172.16.3.201:3306/all_back_0630?charset=utf8', echo=False).connect()


sql_fund='''
select id funding_code,name fund_name from new_transaction.funding_corp
'''
df_fund=pd.read_sql(sql_fund,engine_new_transaction)
df_fund.funding_code=df_fund.funding_code.astype(int)
sql_account='''
select id loan_account_id,accountName from audit.loan_account
'''
df_account=pd.read_sql(sql_account,engine_new_transaction)
df_account.loan_account_id=df_account.loan_account_id.astype(int)
sql_plan='''
select ref_id,term_no,deadline,required_repayment
from user_repayment_plan
where ref_id in %s
'''

def pay_detail(year,month):
    start_time = datetime.date(year,month,1)
    end_time = start_time + relativedelta(months=+1)
    sql_pay='''
    select loan_id,ref_id,loan_paid_at '放款时间',funding_code,contract_loan_amount '合同金额',real_loan_amount '实际放款金额',loan_account_id,batch_no '渠道流水号'
    from loan_manifest
    where is_active in (1,-2) and loan_paid_at >= '%s' and loan_paid_at < '%s'
    ''' % (start_time,end_time)
    sql_contract='''
    select ref_id,contract_no
    from basic.loan_contract
    where ref_id in %s
    '''
    df_pay=pd.read_sql(sql_pay,engine_new_transaction)
    ref_ids=df_pay.ref_id.astype(int)
    df_contract=pd.read_sql(sql_contract % str(tuple(ref_ids)),engine_new_transaction)
    df_pay.ref_id = df_pay.ref_id.astype(int)
    df_contract.ref_id=df_contract.ref_id.astype(int)
    df_pay=pd.merge(df_pay,df_contract,on='ref_id',how='left')
    df_plan=plan_T(ref_ids)
    df_plan.ref_id=df_plan.ref_id.astype(int)
    df_pay=pd.merge(df_pay,df_plan,on='ref_id',how='left')
    #资金方
    df_pay.funding_code=df_pay.funding_code.astype(int)
    df_pay=pd.merge(df_pay,df_fund,on='funding_code',how='left')
    df_pay.loan_account_id=df_pay.loan_account_id.astype(int)
    df_pay=pd.merge(df_pay,df_account,on='loan_account_id',how='left')
    df_pay.drop(['funding_code','loan_account_id'],inplace=True,axis=1)
    df_pay.rename(columns={'fund_name':'资金方','accountName':'放款账户'},inplace=True)
    df_pay.to_excel(path+'xjd_pay_detail_%d_%d.xlsx' % (year,month),index=None)


#还款计划转置
def plan_T(ref_ids):
    df_plan=pd.DataFrame()
    for i in range(0,len(ref_ids),10000):
        ref_id=ref_ids[i:i+10000]
        df_plan=df_plan.append(pd.read_sql(sql_plan % str(tuple(ref_id)).replace(',)',')'),engine_new_transaction))
    df_gp =pd.pivot_table(df_plan,index='ref_id',values=['deadline','required_repayment'],columns='term_no',aggfunc={'deadline':max,'required_repayment':np.sum},fill_value=0).reset_index()
    df_gp.columns=['ref_id','第一期客户应还金额','第二期客户应还金额','第三期客户应还金额','第四期客户应还金额','第五期客户应还金额','第六期客户应还金额',
        '第一期客户应还款日', '第二期客户应还款日', '第三期客户应还款日', '第四期客户应还款日', '第五期客户应还款日', '第六期客户应还款日']
    return df_gp


if __name__ == '__main__':
    year=2016
    month=12
    pay_detail(year,month)

