# -*- 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

'''
这个表--同银行流水是 多对多关系，故出两表显示
表头：loanID，实还时间，期数，实还总额，实还本金，实还利息，流水号，银行打款金额
'''

engine_new_transaction = create_engine(
    'mysql+mysqldb://yulong:ohVU1nPITynSZwR2@172.16.3.201:3306/all_back_0630?charset=utf8', echo=False).connect()
sql_repay_fund = '''
select t1.loan_id,t2.loan_paid_at '放款时间',t1.term_no '期数',date(t1.repaid_at) '实还时间',t1.current_repayment '实还总额',
t1.principle '实还本金',t1.interest '实还利息',t1.lkb2fund_id
from test_linfang.funding_repayment_record t1
join loan_manifest t2 on t1.loan_id=t2.loan_id and t2.is_active = 1
and t1.is_active = 1 and t2.loan_paid_at >= '%s' and t2.loan_paid_at < '%s'
and t1.repaid_at < '2017-07-01' and t1.lkb2fund_id IS not NULL 
'''

sql_flow = '''
SELECT lkb_id,transfer_time '转账时间',ref_amount '转账金额',flow_id '流水号'
FROM basic.lkb_to_fund_ref 
where lkb_id in %s 
'''

sql_lkb_to_fund = '''
SELECT id lkb2fund_id,transfer_time '转账时间',transfer_amount '转账总额' FROM lkb_to_fund WHERE id IN %s 
'''
path = "./"
if __name__ == '__main__':
    year = 2015
    month = 6
    start_time = datetime.date(year, month, 1)
    end_time = start_time + relativedelta(months=+1)
    df_repay = pd.read_sql(sql_repay_fund % (start_time, end_time), engine_new_transaction)
    df_repay.lkb2fund_id = df_repay.lkb2fund_id.astype(int)
    lkb_ids = df_repay.lkb2fund_id.astype(int).tolist()
    df_flow = pd.read_sql(sql_flow % str(tuple(lkb_ids)), engine_new_transaction)
    df_lkb_to_fund = pd.read_sql(sql_lkb_to_fund % str(tuple(lkb_ids)), engine_new_transaction)
    df_lkb_to_fund.lkb2fund_id = df_lkb_to_fund.lkb2fund_id.astype(int)
    df_repay = pd.merge(df_repay, df_lkb_to_fund, on='lkb2fund_id', how='left')
    writer = pd.ExcelWriter(path + u'还资金方表_%s_%s.xlsx' % (start_time, end_time))
    df_repay.to_excel(writer, sheet_name='sheet1', index=False)
    df_flow.to_excel(writer, sheet_name='sheet2', index=False)
    writer.save()
