# -*- coding:utf-8 -*-
#Author: Perry_Zhu
import datetime
import multiprocessing as mtp
import sys
from itertools import product
import pandas as pd
from dateutil.relativedelta import relativedelta
from sqlalchemy import create_engine
import pyexcelerate

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

file_path = u'E:/审计出表/非去哪儿白条-客户实还表-1023版/'

# 注意修改数据源
max_limit = 800000
engine_all_back_0930 = create_engine(
    'mysql+mysqldb://internal_r:ArbNgtvlJzZHXsEu@172.16.3.201:3306/all_back_0930?charset=utf8',
    echo=True)

read_merchant_sql = '''SELECT merchant_id,merchant_name FROM all_back_0930.merchant'''
df_merchant = pd.read_sql(read_merchant_sql, con=engine_all_back_0930)
df_merchant['merchant_id'] = df_merchant['merchant_id'].astype(int)
read_repay_sql = '''
SELECT id,`approach_name` FROM all_back_0930.`repay_channel`
'''
df_approach = pd.read_sql(read_repay_sql, engine_all_back_0930)
df_approach['id'] = df_approach['id'].astype(int)

read_fund_sql = '''
SELECT id,fund_name FROM all_back_0930.`fund_corp`
'''
df_fund = pd.read_sql(read_fund_sql, engine_all_back_0930)
df_fund['id'] = df_fund['id'].astype(int)

'''
白条还款汇总
'''


################################################
# 收客户还款汇总
def hk_hz(year,month):

    start_time = datetime.datetime(year, month, 1, 0, 0, 0)
    end_time = start_time + relativedelta(months=+1)

    sql_alipay = """
    SELECT
        t8.fund_name 资金方,
        t5.order_no 产品编号,
        t5.contract_term 放款期数,
        t2.term_no 当前期数,
        t6.merchant_name 白条商家,
        date(t3.transfer_time) 客户实还时间,
        ifnull(t1.ref_amount,0) 总额,
        ifnull(t1.principle,0) - ifnull(t1.mitigate_principle,0)本金,
        ifnull(t1.interest,0)-ifnull(t1.mitigate_interest,0)利息,
        ifnull(t1.service_fee,0) - ifnull(t1.mitigate_service_fee,0) 服务费,
        ifnull(t1.punish,0) - ifnull(t1.mitigate_collection_relief,0) 逾期罚款收益,
        ifnull(t1.remain_income,0) 其他收益,
        t7.approach_name 收款账户,
        t3.business_flow 流水号
    FROM
        baitiao_repay_plan_repay_record_ref t1
    JOIN user_bt_repayment_plan t2 ON t2.id = t1.plan_id
    JOIN offline_alipay_record t3 ON t1.repay_channel = 13 AND t3.id = t1.record_id AND  t3.is_ref=1 AND t3.enable=1
    JOIN all_back_0930.baitiao_order t5 ON t2.ref_id = t5.ref_id
    JOIN all_back_0930.merchant t6 ON t6.`merchant_id` = t5.`merchantId`
    JOIN new_transaction.repay_channel t7 ON t1.repay_channel = t7.id
    JOIN all_back_0930.fund_corp t8 ON  t5.funding_corp_id=t8.id
    where t3.transfer_time>='%s' and t3.transfer_time <'%s'
	""" %(start_time,end_time)
    df_alipay = pd.read_sql(sql=sql_alipay, con=engine_all_back_0930)

    sql_bank = """
      SELECT
        t8.fund_name 资金方,
        t5.order_no 产品编号,
        t5.contract_term 放款期数,
        t2.term_no 当前期数,
        t6.merchant_name 白条商家,
        date(t3.transfer_time) 客户实还时间,
        ifnull(t1.ref_amount,0) 总额,
        ifnull(t1.principle,0) - ifnull(t1.mitigate_principle,0) 本金,
        ifnull(t1.interest,0) - ifnull(t1.mitigate_interest,0) 利息,
        ifnull(t1.service_fee,0) - ifnull(t1.mitigate_service_fee,0)  服务费,
        ifnull(t1.punish,0) - ifnull(t1.mitigate_collection_relief,0) 逾期罚款收益,
        ifnull(t1.remain_income,0) 其他收益,
        t7.approach_name 收款账户,
        t3.serial_number 流水号
    FROM
        baitiao_repay_plan_repay_record_ref t1
    JOIN user_bt_repayment_plan t2 ON t2.id = t1.plan_id
    JOIN offline_bank_repay_record t3 ON t1.repay_channel IN (14, 15, 16) AND t3.id = t1.record_id
    JOIN all_back_0930.baitiao_order t5 ON t2.ref_id = t5.ref_id
    JOIN all_back_0930.merchant t6 ON t6.`merchant_id` = t5.`merchantId`
    JOIN new_transaction.repay_channel t7 ON t1.repay_channel = t7.id
    JOIN all_back_0930.fund_corp t8 ON  t5.funding_corp_id=t8.id
    where t3.transfer_time>='%s' and t3.transfer_time <'%s'
	"""%(start_time,end_time)
    df_bank = pd.read_sql(sql=sql_bank, con=engine_all_back_0930)

    sql_online = """
        SELECT
            t8.fund_name 资金方,
            t5.order_no 产品编号,
            t5.contract_term 放款期数,
            t2.term_no 当前期数,
            t6.merchant_name 白条商家,
            date(t3.bill_time) 客户实还时间,
            ifnull(t1.ref_amount,0) 总额,
            ifnull(t1.principle,0) - ifnull(t1.mitigate_principle,0) 本金,
            ifnull(t1.interest,0) - ifnull(t1.mitigate_interest,0) 利息,
            ifnull(t1.service_fee,0) - ifnull(t1.mitigate_service_fee,0)  服务费,
            ifnull(t1.punish,0) - ifnull(t1.mitigate_collection_relief,0) 逾期罚款收益,
            ifnull(t1.remain_income,0) 其他收益,
            t7.approach_name 收款账户,
            t3.order_id 流水号
        FROM
            baitiao_repay_plan_repay_record_ref t1
        JOIN repay_record_online t3 ON t1.repay_channel in(1,2,3,4,5,6,7,8,9,10,11,12,22,23,24) AND t3.id = t1.record_id
        JOIN user_bt_repayment_plan t2 ON t2.id = t1.plan_id
        JOIN all_back_0930.baitiao_order t5 ON t2.ref_id = t5.ref_id
        JOIN all_back_0930.merchant t6 ON t6.`merchant_id` = t5.`merchantId`
        JOIN new_transaction.repay_channel t7 ON t1.repay_channel = t7.id
        JOIN all_back_0930.fund_corp t8 ON  t5.funding_corp_id=t8.id
        WHERE t3.bill_time is not NULL 
        and t3.bill_time>='%s' and t3.bill_time<'%s'
	"""%(start_time,end_time)
    df_online = pd.read_sql(sql=sql_online, con=engine_all_back_0930)

    sql_cash_online = """
    SELECT
        t8.fund_name 资金方,
        t5.order_no 产品编号,
        t5.contract_term 放款期数,
        t5.contract_term 当前期数,
        t6.merchant_name 白条商家,
        date(t3.bill_time) 客户实还时间,
        ifnull(t1.ref_amount,0) 总额,
        ifnull(t5.real_loan_amount,0) 本金,
        0.0 利息,
        0.0 服务费,
        0.0 逾期罚款收益,
        0.0 其他收益,
        '白条现金支付' 收款账户,
        0 流水号
    FROM
        (SELECT repay_id,record_id,repay_channel,SUM(ifnull(ref_amount,0))ref_amount FROM 
				baitiao_cash_record_ref WHERE  repay_channel !=13 GROUP BY 1) t1
    JOIN baitiao_cash_repay t2 ON t2.id = t1.repay_id
    JOIN repay_record_online t3 ON t3.id = t1.record_id 
    JOIN all_back_0930.baitiao_order t5 ON t2.order_no = t5.order_no AND t2.real_order_amount=t5.real_loan_amount
    JOIN all_back_0930.merchant t6 ON t6.`merchant_id` = t5.`merchantId`
    JOIN all_back_0930.fund_corp t8 ON  t5.funding_corp_id=t8.id
    WHERE t3.bill_time is not NULL 
    and t3.bill_time>='%s' and t3.bill_time<'%s' 
    """%(start_time,end_time)

    sql_cash_alipay = """
        SELECT
            t8.fund_name 资金方,
            t5.order_no 产品编号,
            t5.contract_term 放款期数,
            t5.contract_term 当前期数,
            t6.merchant_name 白条商家,
            date(t3.transfer_time) 客户实还时间,
            ifnull(t1.ref_amount,0) 总额,
            ifnull(t5.real_loan_amount,0) 本金,
            0.0 利息,
            0.0 服务费,
            0.0 逾期罚款收益,
            0.0 其他收益,
            '支付宝线下还款' 收款账户,
            t3.business_flow 流水号 
        FROM
           (SELECT repay_id,record_id,repay_channel,SUM(ifnull(ref_amount,0))ref_amount 
              FROM 
			baitiao_cash_record_ref 
			GROUP BY 1) t1
        JOIN baitiao_cash_repay t2 ON t2.id = t1.repay_id
        JOIN offline_alipay_record t3 ON  t3.id = t1.record_id AND t1.repay_channel=13
        JOIN all_back_0930.baitiao_order t5 ON t2.order_no = t5.order_no AND t2.real_order_amount=t5.real_loan_amount
        JOIN all_back_0930.merchant t6 ON t6.`merchant_id` = t5.`merchantId`
        JOIN new_transaction.repay_channel t7 ON t1.repay_channel = t7.id
        JOIN all_back_0930.fund_corp t8 ON  t5.funding_corp_id=t8.id
        where t3.transfer_time>='%s' and t3.transfer_time <'%s'
        """%(start_time,end_time)
    df_cash_onlie = pd.read_sql(sql=sql_cash_online, con=engine_all_back_0930)
    df_cash_alipay = pd.read_sql(sql=sql_cash_alipay, con=engine_all_back_0930)
    df = pd.concat([df_alipay, df_bank, df_online, df_cash_onlie, df_cash_alipay], ignore_index=True)
    df = df[
        [u'资金方',u'产品编号',u'放款期数',u'当前期数',u'白条商家',u'客户实还时间', u'总额', u'本金', u'利息', u'服务费', u'逾期罚款收益',
         u'其他收益',u'收款账户',u'流水号']]

    # all_wb = pyexcelerate.Workbook()
    # for i in xrange(0, len(df), max_limit):
    #     temp = df[i:i + max_limit]
    #     temp_list = temp.values.tolist()
    #     temp_list.insert(0, temp.columns.tolist())
    #     all_wb.new_sheet(str(int(i / max_limit + 1)), data=temp_list)
    # all_wb.save(file_path + u'白条还款明细表_%s_%s.xlsx' % (year, month))

    df.to_csv(file_path + u'白条还款汇总表_%s_%s.csv' %(year,month), index=None,encoding='gb18030')


if __name__ == '__main__':
    # 还款汇总
    years = [2017]
    months = [7,8,9]
    for year, month in product(years, months):
        print('-----%s--%s') % (year, month)
        hk_hz(year, month)