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

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

'''
8月份直投上线后，客户的退款退到了还款账户中
还款表中体现这部分退款，这部分退款处理金额为正，数据库中为负。
'''

file_path = u'E:/审计出表/去哪儿1005/'
file_name = u'核算还款表_%s_%s.xlsx'
engine_qunaer = create_engine('mysql+mysqldb://internal_r:ArbNgtvlJzZHXsEu@172.16.3.201:3306/qunaer_new?charset=utf8',
                              echo=False).connect()


def hk_detail(year, month):
    start_time = datetime.datetime(year, month, 1, 0, 0, 0)
    end_time = start_time + relativedelta(months=+1)
    # 实还表====内保的plan_16
    sql_repay = '''
	SELECT
	    fc.fund_name as '资金方',
		t1.product_no AS '产品编号',
		pay.stages AS '分期数',
		date(t1.repay_time) '还款时间',
		t1.repay_amount '还款总额',
		t1.repay_principle '实还本金',
		t1.repay_fee_amount '实还服务费',
		t1.repay_due_amount '实还罚息',
		t1.remain '其他收益',
		t1.flow_id '流水号'
	FROM
		qunaer_new.repay_detail t1
	JOIN qunaer_new.fund_corp fc on fc.fund_code = t1.fund_code
	JOIN qunaer_new.pay_detail pay on t1.product_no = pay.product_no and pay.fund_code = 1
	WHERE
	  t1.fund_code = 1 AND 
		t1.repay_time >= '%s'
	AND t1.repay_time < '%s'
	AND t1. repay_status = 1;
	''' % ( start_time, end_time)


    # 资金方的--
    sql_repay_fund = '''
        	SELECT
        	    fc.fund_name as '资金方',
        		t1.product_no AS '产品编号',
        		pay.stages AS '分期数',
        		date(t1.repay_time) '还款时间',
        		t1.repay_amount '还款总额',
        		t1.repay_principle '实还本金',
        		t1.repay_fee_amount '实还服务费',
        		t1.repay_due_amount '实还罚息',
        		t1.remain '其他收益',
        		t1.flow_id '流水号'
        	FROM
        		qunaer_new.repay_detail t1
        	JOIN qunaer_new.fund_corp fc on fc.fund_code = t1.fund_code
        	JOIN qunaer_new.fund_pay_detail pay on t1.product_no = pay.product_no AND t1.fund_code = pay.fund_code
        	WHERE
        	    t1.fund_code != 1
        	AND 
        		t1.repay_time >= '%s'
        	AND t1.repay_time < '%s'
        	AND t1. repay_status = 1 AND pay.status=1;
       ''' % ( start_time, end_time)

    # 债转后保理的--
    sql_repay_baoli = '''
            	SELECT
					fc.fund_name as '资金方',
					t1.product_no AS '产品编号',
					pay.stages AS '分期数',
					date(t1.repay_time) '还款时间',
					t1.repay_amount '还款总额',
					t1.repay_principle '实还本金',
					t1.repay_fee_amount '实还服务费',
					t1.repay_due_amount '实还罚息',
					t1.remain '其他收益',
					t1.flow_id '流水号'
            	FROM
            		qunaer_new.repay_detail t1
            	JOIN qunaer_new.fund_corp fc on fc.fund_code = t1.fund_code
            	JOIN qunaer_new.baoli_pay_detail pay on t1.product_no = pay.product_no AND t1.fund_code = pay.fund_code
            	WHERE
            	    t1.fund_code = 1
            	AND 
            		t1.repay_time >= '%s'
            	AND t1.repay_time < '%s'
            	AND t1. repay_status = 1 AND pay.status=1;
           ''' % (start_time, end_time)
    # 退款退到还款账户
    sql_refund = '''
    	SELECT
    	    t2.fund_name as '资金方',
    		t1.product_no '产品编号',
    		t3.stages '分期数',
    		date(t1.refund_time) '还款时间',
    		-t1.refund_amount as '还款总额',
    		-t1.refund_principle as '实还本金',
    		-t1.refund_due_amount as '实还罚息',
    		-t1.refund_fee_amount as '实还服务费',
    		0 '其他收益',
    		t1.flow_id '流水号'
    	FROM
    		qunaer_new.refund_detail t1
    	JOIN fund_corp t2 ON t2.fund_code = t1.fund_code
    	JOIN pay_detail t3 on t1.product_no = t3.product_no and t3.status = 1
    	WHERE t1.refund_time >= '%s' and t1.refund_time < '%s' and t1.flow_id is not NULL 
    ''' % (start_time, end_time)
    # 退款
    df_refund = pd.read_sql(sql_refund, engine_qunaer)
    # 还款计划合并
    df_repay = pd.read_sql(sql_repay, engine_qunaer)

    df_fund_repay = pd.read_sql(sql_repay_fund, engine_qunaer)
    df_baoli_repay = pd.read_sql(sql_repay_baoli, engine_qunaer)

    df_repay = pd.concat([df_repay, df_fund_repay, df_baoli_repay], ignore_index=True)

    df_repay.fillna(0, inplace=True)
    writer = pd.ExcelWriter(file_path + file_name % (year, month))
    df_refund.to_excel(writer, sheet_name=u'退款到还款账户的表', index=None, encoding='UTF-8')
    # # df_repay 中如果有df_refund退款的，则标志出退款
    # df_refund[u'是否有退款'] = 'TRUE'
    # df_refund.drop_duplicates([u'资金方', u'产品编号'], inplace=True)
    # df_repay = pd.merge(df_repay, df_refund[[u'资金方', u'产品编号', u'是否有退款']], on=[u'资金方', u'产品编号'], how='left')
    # df_repay[u'是否有退款'].fillna('FALSE', inplace=True)
    df_repay.to_excel(writer, sheet_name=u'用户实还表', index=None, encoding='UTF-8')
    writer.save()
    writer.close()


if __name__ == '__main__':

    # 还款明细
    years = [2017]
    months = [8,9]
    for year, month in product(years, months):
        print('-----%s--%s') % (year, month)
        hk_detail(year, month)

print '-----------------------main done---------------------------------------'
