# -*- encoding: utf8 -*-
import sys
import datetime
import pandas as pd
from sqlalchemy import create_engine
from dateutil.relativedelta import relativedelta

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

'''
目标 我方的资金方还款计划 VS 审计的资金方还款计划
注意 is_active = 1 的订单
'''
engine_new_transaction = create_engine(
    'mysql+mysqldb://yulong:ohVU1nPITynSZwR2@172.16.3.201:3306/all_back_0630?charset=utf8', echo=False).connect()

path = "./"
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_fund = '''
select id fund_id,name fund_name from new_transaction.funding_corp
'''
df_fund = pd.read_sql(sql_fund, engine_new_transaction)
df_fund.fund_id = df_fund.fund_id.astype(int)


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,funding_code fund_id,DATE(loan_paid_at) loan_paid_at,contract_loan_amount ,loan_account_id,per_term_service_fee*contract_term service_fee
    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_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 = pd.merge(df_pay, df_fund, on='fund_id', how='left')
    df_pay.drop(['ref_id', 'loan_account_id', 'fund_id'], inplace=True, axis=1)
    return df_pay


# 资金方还款计划
def fund_repay_plan_detail(loan_ids):
    df_plan = pd.DataFrame()
    sql_plan = '''
    select loan_id,term_no ,date(deadline) deadline,sum(principle+interest) fund_prin_inst
    from test_linfang.funding_repayment_record 
    where is_active in (1,-1) and loan_id in %s 
    group by 1,2
    '''
    for i in range(0, len(loan_ids), 50000):
        df_plan = df_plan.append(
            pd.read_sql(sql_plan % str(tuple(loan_ids[i:i + 50000])).replace(',)', ')'), engine_new_transaction))
    return df_plan


if __name__ == '__main__':
    year = 2015
    month = 6
    df_pay = pay_detail(year, month)
    loan_ids = df_pay.loan_id.astype(str).tolist()
    df_plan = fund_repay_plan_detail(loan_ids)
    df_pay.loan_id = df_pay.loan_id.astype(str)
    df_plan.loan_id = df_plan.loan_id.astype(str)
    print '-----无还款计划的放款-------------', df_pay.ix[~df_pay.loan_id.isin(df_plan.loan_id)]
    df = pd.merge(df_plan, df_pay, on='loan_id', how='inner')
    df.term_no = df.term_no.astype(int)
    df.loan_id = df.loan_id.astype(str)
    # loan_id,term_no 排序
    df = df.sort_values(by=['loan_id', 'term_no'])
    df.ix[df.term_no != 1, 'contract_loan_amount'] = ''
    df.ix[df.term_no != 1, 'service_fee'] = ''
    # df=pd.pivot_table(df,index=['loan_id','contract_no','loan_paid_at','contract_loan_amount','accountName','service_fee','term_no'],
    #                values=['deadline','fund_prin_inst'],aggfunc={'deadline':max,'fund_prin_inst':sum})
    df['merge'] = df.apply(lambda x: '%s%s%s%s' % (x.loan_id, x.term_no, x.deadline, x.fund_prin_inst), axis=1)
    df.rename(columns={'contract_no': '合同号', 'loan_paid_at': '放款时间', 'contract_loan_amount': '放款金额',
                       'accountName': '放款渠道', 'service_fee': '应收总服务费',
                       'term_no': '应还期数', 'deadline': '应还资金方时间', 'fund_prin_inst': '应还资金方本息', 'fund_name': '资金方'},
              inplace=True)
    df.to_excel(path+'fund_plan_%d_%d.xlsx' % (year, month), index=False)
