# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
import sys
import multiprocessing as mtp
from itertools import product
import numpy as np
import pandas as pd
from sqlalchemy import create_engine
from dateutil.relativedelta import relativedelta

reload(sys)
sys.setdefaultencoding('utf8')

'''
目标  放款统计（is_active in (1,-2)） + 放款明细
表头： loan_id,放款日期,放款金额,本金（债权）,一次性手续费（QG）,一次性手续费（点滴）,贷款总期数,每期手续费,月利率,资金方,放款渠道
'''

#----------------变量配置开始---------------------------
# 文件生成路劲
path = 'E:/hk/xjd/'
#TODO 是否输出放款统计表---
# 1: 只输出 统计表； 2：只输出明细表；  3：统计表+明细表
fk_flag=1
engine_new_transaction = create_engine(
    'mysql+mysqldb://internal_r:ArbNgtvlJzZHXsEu@172.16.3.201:3306/all_back_0430?charset=utf8',
    echo=True)
#----------------变量配置结束---------------------------


df_fund_corp = pd.read_sql(sql="select funding_code, name '资金方' from audit.funding_corp", con=engine_new_transaction)
df_loan_account = pd.read_sql(sql="select id loan_account_id, accountName '放款账户' from audit.loan_account",con=engine_new_transaction)
df_repay_channel = pd.read_sql(sql="select id repay_channel_id, approach_name '收款账户' from new_transaction.repay_channel", con=engine_new_transaction)
#放款表统计
def fk_tj():
    excel_file = pd.ExcelWriter(path+'放款数据汇总核对表.xlsx')
    ################################################
    # 放款表汇总
    sql = """
    select year(t1.loan_paid_at) '年', month(t1.loan_paid_at) '月', funding_code , loan_account_id , sum(t1.real_loan_amount) '放款金额', sum(t1.contract_loan_amount) '本金债权',
    sum(t1.qg_one_time_service_fee) '一次性扣除手续费QG', sum(t1.funding_one_time_service_fee) ' 一次性扣除手续费点滴' from loan_manifest t1  where t1.is_active in (1,-2)
    group by 1,2,3,4;
    """
    df = pd.read_sql(sql=sql, con=engine_new_transaction)
    df['funding_code'] = df['funding_code'].astype(int)
    df['loan_account_id'] = df['loan_account_id'].astype(int)
    df = df.merge(df_fund_corp, on='funding_code', how='left').merge(df_loan_account, on='loan_account_id', how='left')
    df.drop(['funding_code', 'loan_account_id'], axis=1, inplace=True)
    df.to_excel(excel_file, '放款表汇总', columns=['年', '月', '资金方', '放款账户', '放款金额', '本金债权', '一次性扣除手续费QG', '一次性扣除手续费点滴'],
                index=None)
    excel_file.save()

#放款明细
def fk_detail():
    years = (2015, 2016)
    months = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
    fundcodes = (
        1, 0, 3, 2, 5, 29, 4, 141, 50, 70, 80, 90, 100, 120, 110, 130, 150, 170, 180, 140, 190, 200, 160, 210, 135, 230,
        240,
        250, 251, 260, 300, 290, 270, 330, 310, 320, 350, 340)
    sql_loan = """SELECT lm.funding_code 'funding_code',lm.loan_id 'loan_id',loan_paid_at '放款日期',lm.real_loan_amount '放款金额',lm.loan_account_id 'loan_account_id',lm.contract_loan_amount '本金（债权）',lm.qg_one_time_service_fee '一次性手续费（QG）',lm.funding_one_time_service_fee '一次性手续费（点滴）',lm.contract_term '贷款总期数',lm.per_term_service_fee '每期手续费',lm.monthly_interest_rate '月利率'
        FROM loan_manifest lm
        WHERE lm.loan_paid_at>="%d-%d-01" AND lm.loan_paid_at<"%d-%d-01" AND lm.funding_code=%d AND lm.is_active in (1,-2);"""
    chunksize = 10000
    step = 3000
    for fund_code in fundcodes:
        print sql_loan % (2015, 1, 2017, 1, fund_code)
        df_loan_gen = pd.read_sql(sql=sql_loan % (2015, 1, 2017, 1, fund_code), con=con_audit_audit,
                                  chunksize=chunksize)
        df_loan = pd.DataFrame()
        for tmp in df_loan_gen:
            df_loan = df_loan.append(tmp, ignore_index=True)
        if len(df_loan) < 1:
            continue
        df_loan['loan_id'] = df_loan['loan_id'].astype(str)
        df_loan['funding_code'] = df_loan['funding_code'].astype(int)
        df_loan['loan_account_id'] = df_loan['loan_account_id'].astype(int)
        df_loan = df_loan.merge(df_fund_corp, on='funding_code', how='left').merge(df_loan_account,
                                                                                   on='loan_account_id', how='left')
        df_loan.drop(['funding_code', 'loan_account_id'], axis=1, inplace=True)
        df_loan[u'放款日期'] = df_loan[u'放款日期'].apply(lambda x: pd.datetime.strftime(x, '%Y-%m-%d %H:%M'))
        header_line = ','.join(df_loan.columns)
        # loan_id,放款日期,放款金额,本金（债权）,一次性手续费（QG）,一次性手续费（点滴）,贷款总期数,每期手续费,月利率,资金方,放款渠道
        np.savetxt(file_path + 'xjd_loan_2015-2016_' + str(fund_code) + '.txt', X=df_loan.values,
                   fmt='%s|%s|%f|%f|%.2f|%.2f|%d|%.2f|%f|%s|%s|', header=header_line, delimiter='|')


