# -*- 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:/量化派/去哪儿/常规出账/'
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, user_16_plan='repayment_plan_2016', user_17_plan='repayment_plan_2017',
              fund_plan='fund_repayment_plan', baoli_plan='baoli_repayment_plan'):
    start_time = datetime.datetime(year, month, 1, 0, 0, 0)
    end_time = start_time + relativedelta(months=+1)
    # 实还表====内保的plan_16
    sql_repay_plan_2016 = '''
	SELECT
	    fc.fund_name as '资金方',
		t1.product_no AS '产品编号',
		pay.loan_amount AS '放款金额',
		pay.stages AS '放款期数',
		t1.current_stage_no AS '当期期数',
		DATE(plan.deadline) AS '应还款日',
		plan.principle+plan.fee_amount+plan.due_amount AS '应还款金额',
		plan.principle AS '应还本金',
		0 AS '应还利息-直投',
		plan.fee_amount AS '应还服务费',
		plan.due_amount AS '应还罚息',
		date(t1.repay_time) '实还款日',
		'去那儿' as '收款账户',
		t1.flow_id '收款流水号',
		t1.repay_amount '实还金额',
		t1.repay_principle '实还本金',
		0 as '实还利息-直投模式下',
		t1.repay_fee_amount '实还服务费',
		t1.repay_due_amount '实还罚息',
		t1.remain '其他收益'
	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
	JOIN %s plan on plan.product_no = t1.product_no AND plan.current_stage_no = t1.current_stage_no
	WHERE
	  t1.fund_code = 1 AND 
		t1.repay_time >= '%s'
	AND t1.repay_time < '%s'
	AND t1. repay_status = 1;
	''' % (user_16_plan, start_time, end_time)
    # 内保--17年的
    sql_repay_plan_2017 = '''
    	SELECT
    	    fc.fund_name as '资金方',
    		t1.product_no AS '产品编号',
    		pay.loan_amount AS '放款金额',
    		pay.stages AS '放款期数',
    		t1.current_stage_no AS '当期期数',
    		DATE(plan.deadline) AS '应还款日',
    		plan.principle+plan.fee_amount+plan.due_amount AS '应还款金额',
    		plan.principle AS '应还本金',
    		0 AS '应还利息-直投',
    		plan.fee_amount AS '应还服务费',
    		plan.due_amount AS '应还罚息',
    		date(t1.repay_time) '实还款日',
    		'去那儿' as '收款账户',
    		t1.flow_id '收款流水号',
    		t1.repay_amount '实还金额',
    		t1.repay_principle '实还本金',
    		0 as '实还利息-直投模式下',
    		t1.repay_fee_amount '实还服务费',
    		t1.repay_due_amount '实还罚息',
    		t1.remain '其他收益'
    	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
    	JOIN %s plan on plan.product_no = t1.product_no AND plan.current_stage_no = t1.current_stage_no
    	WHERE
    	  t1.fund_code = 1 AND 
    		t1.repay_time >= '%s'
    	AND t1.repay_time < '%s'
    	AND t1. repay_status = 1;
    	''' % (user_17_plan, start_time, end_time)

    # 资金方的--
    sql_repay_fund = '''
        	SELECT
        	    fc.fund_name as '资金方',
        		t1.product_no AS '产品编号',
        		pay.loan_amount AS '放款金额',
        		pay.stages AS '放款期数',
        		t1.current_stage_no AS '当期期数',
        		DATE(plan.deadline) AS '应还款日',
        		plan.principle+plan.interest+plan.fee_amount+plan.due_amount AS '应还款金额',
        		plan.principle AS '应还本金',
        		plan.interest AS '应还利息-直投',
        		plan.fee_amount AS '应还服务费',
        		plan.due_amount AS '应还罚息',
        		date(t1.repay_time) '实还款日',
        		'去那儿' as '收款账户',
        		t1.flow_id '收款流水号',
        		t1.repay_amount '实还金额',
        		t1.repay_principle '实还本金',
        		0 as '实还利息-直投模式下',
        		t1.repay_fee_amount '实还服务费',
        		t1.repay_due_amount '实还罚息',
        		t1.remain '其他收益'
        	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
        	JOIN %s plan on plan.product_no = t1.product_no AND plan.current_stage_no = t1.current_stage_no
        	WHERE
        		t1.repay_time >= '%s'
        	AND t1.repay_time < '%s'
        	AND t1. repay_status = 1 AND pay.status=1;
       ''' % (fund_plan, start_time, end_time)

    # 债转后保理的--
    sql_repay_baoli = '''
            	SELECT
            	    fc.fund_name as '资金方',
            		t1.product_no AS '产品编号',
            		pay.loan_amount AS '放款金额',
            		pay.new_stages AS '放款期数',
            		t1.current_stage_no AS '当期期数',
            		DATE(plan.deadline) AS '应还款日',
            		plan.principle+plan.fee_amount+plan.due_amount AS '应还款金额',
            		plan.principle AS '应还本金',
            		0 AS '应还利息-直投',
            		plan.fee_amount AS '应还服务费',
            		plan.due_amount AS '应还罚息',
            		date(t1.repay_time) '实还款日',
            		'去那儿' as '收款账户',
            		t1.flow_id '收款流水号',
            		t1.repay_amount '实还金额',
            		t1.repay_principle '实还本金',
            		0 as '实还利息-直投模式下',
            		t1.repay_fee_amount '实还服务费',
            		t1.repay_due_amount '实还罚息',
            		t1.remain '其他收益'
            	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
            	JOIN %s plan on plan.product_no = t1.product_no AND plan.user_current_stage_no = t1.current_stage_no
            	WHERE
            		t1.repay_time >= '%s'
            	AND t1.repay_time < '%s'
            	AND t1. repay_status = 1 AND pay.status=1;
           ''' % (baoli_plan, start_time, end_time)
    # 退款退到还款账户
    sql_refund = '''
    	SELECT
    	    t2.fund_name as '资金方',
    		t1.product_no '产品编号',
    		'去那儿' as '收款账户',
    		date(t1.refund_time) '还款时间',
    		-t1.refund_amount as '还款金额',
    		-t1.refund_principle as '还款本金',
    		-t1.refund_due_amount as '还款逾期费',
    		-t1.refund_fee_amount as '还服务费',
    		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 !=0
    	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_plan_2016 = pd.read_sql(sql_repay_plan_2016, engine_qunaer)
    df_repay_plan_2017 = pd.read_sql(sql_repay_plan_2017, 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_plan_2016, df_repay_plan_2017, 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]
    for year, month in product(years, months):
        print('-----%s--%s') % (year, month)
        hk_detail(year, month,user_16_plan='repayment_plan_2016_201708',
                  user_17_plan='repayment_plan_201708',fund_plan='fund_repayment_plan_201708',
                  baoli_plan='baoli_repayment_plan_201708')

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