# -*- coding: utf-8 -*-
"""
    出白条还资金方汇明细
"""
import pandas as pd
import multiprocessing as mtp
pd.options.mode.chained_assignment = None
import sys
from sqlalchemy import create_engine

reload(sys)
sys.setdefaultencoding('utf8')
engine_baitiao_audit = create_engine('mysql+mysqldb://yulong:ohVU1nPITynSZwR2@172.16.3.201:3306/baitiao_audit?charset=utf8', echo=True)
select_detail = """
SELECT 
loan_no,
total_term_no 总分期数,
order_amount 订单金额,
current_amount 给资金方兑换前的金额,
term_no 对应期数,
CASE package_type
WHEN 2
THEN '质押'
ELSE  '债转'
END
 类型,
package_id,
package_name,
fund_name,
transfer_amount,
repaid_total_amount 还资金方总额,
repaid_principal_amount 还资金方本金,
interest 还资金方利息,
service_pay 服务费
FROM baitiao_fund_repayment_record 
WHERE fund_name = '%s'
"""

select_service_sql = """
SELECT  
	YEAR(tfq.service_fee_time) repay_time_year,
	MONTH(tfq.service_fee_time) repay_time_month,
    tfq.fund_name fund_corp,
	IFNULL(frr.service_pay,0) 服务费
FROM
	baitiao_fund_repayment_record frr
JOIN fund_qg_detail tfq ON tfq.package_name = frr.package_name
WHERE tfq.fund_name='%s'
"""


select_fund_qg_detail_sql = """
SELECT  

	tfq.repay_time 打款时间,
    frr.fund_name 资金方,
    IFNULL(frr.repaid_principal_amount,0)本金,
    IFNULL(frr.interest,0)利息
FROM
	baitiao_fund_repayment_record frr
JOIN fund_qg_detail tfq ON tfq.package_name = frr.package_name
WHERE frr.fund_name ='%s'
AND YEAR (tfq.repay_time)=%s
AND MONTH(tfq.repay_time)=%s
"""

jinrongquan_sql = """SELECT
	tfq.transfer_time 打款时间,
	IFNULL(total_amount,0) 本息和,
	IFNULL(order_amount,0) 本金,
	IFNULL(interest,0) 利息
FROM
	jinrongquan_order t1
JOIN qg_to_fund tfq ON tfq.package_names = t1.package_name
WHERE  YEAR (tfq.transfer_time)=%s
AND MONTH(tfq.transfer_time)=%s
"""


def baitiao_detail_to_excel(fund_name, year,month):
    df = pd.read_sql(sql=select_fund_qg_detail_sql % (str(fund_name), int(year), int(month),), con=engine_baitiao_audit)
    # df_service = pd.read_sql(sql=select_service_sql, con=engine_baitiao_audit)
    # df_service = df_service.ix[~df_service.repay_time_year.isnull()]
    # df_service['fund_corp'] = df_service['fund_corp'].astype(str)
    # df_service['repay_time_year'] = df_service['repay_time_year'].astype(int)
    # df_service['repay_time_month'] = df_service['repay_time_month'].astype(int)
    # df = pd.merge(df, df_service, how='left', on=['fund_corp', 'repay_time_year', 'repay_time_month'])
    if len(df)>0:
        df = df[[u'打款时间', u'资金方', u'本金', u'利息']]
        df.fillna(0, inplace=True)
        df.to_excel(u"E:/数据汇总/还资金方明细表/白条/%s白条%s-%s还资金方明细.xlsx" %(fund_name, year, month,), index=None)

def jinrongquan(fund_name,year, month):
    df_jinrongquan = pd.read_sql(sql=jinrongquan_sql % (int(year), int(month),), con=engine_baitiao_audit)
    # df_jinrongquan[u'打款账户'] = '去哪儿代收账户'
    if len(df_jinrongquan) > 0:
        df_jinrongquan[u'资金方'] = '金融圈'
        df_jinrongquan[u'服务费'] = 0
        df_jinrongquan = df_jinrongquan[[u'打款时间', u'资金方', u'本金', u'利息']]
        df_jinrongquan.to_excel(u"E:/数据汇总/还资金方明细表/白条/%s白条%s-%s还资金方明细.xlsx" %(fund_name, year, month,), index=None)

funds = [u'善水融', u'好规划', u'安爱华', u'惠金所', u'曾思成', u'笑脸金融', u'金融圈', u'金融界']

# for fund_name in funds:
#     jinrongquan(u'金融圈',2016,7)
if __name__ == '__main__':
    years = [2015, 2016, 2017]
    months = range(1, 13)
    import itertools
    con = itertools.product(years, months)
    pool = mtp.Pool(processes=8)
    for (year, month) in con:
        for fund_name in funds:
            if fund_name==u'金融圈':
                pool.apply_async(jinrongquan, (fund_name,year, month))
            else:
                pool.apply_async(baitiao_detail_to_excel, (fund_name, year,month))
    pool.close()
    pool.join()

