# -*- 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
import pyexcelerate

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

'''
8月份直投上线后，客户的退款退到了还款账户中
还款表中体现这部分退款，这部分退款处理金额为正，数据库中为负。
'''
max_limit = 800000
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):
    #year,month = 2017,9
    start_time = datetime.datetime(year, month, 1, 0, 0, 0)
    end_time = start_time + relativedelta(months=+1)
    # 内保--17年的
    sql_repay_plan_2017 = '''
    	SELECT
    	    concat(t1.product_no,t1.current_stage_no) as '唯一编号',
    	    t1.product_no AS '产品编号',
    	    fc.fund_name as '资金方',
    		pay.stages AS '分期数',
    		t1.current_stage_no AS '当期期数',
    		date(t1.repay_time) '实还款日',
    		t1.repay_amount '还款总额',
    		t1.repay_principle '实还本金',
    		0 as '实还利息-直投',
    		t1.repay_fee_amount '实还服务费',
    		t1.repay_due_amount '实还罚息',
    		t1.remain '其他收益',
    		t1.flow_id '流水号',
    		bf.trans_amount AS '银行金额',
    		plan.principle AS '应还本金',
    		0 AS '应还利息-直投',
    		plan.fee_amount '应还服务费',
    		date(plan.deadline) as '应还时间'
    	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 repayment_plan_2017 plan on plan.product_no = t1.product_no AND plan.current_stage_no = t1.current_stage_no AND t1.fund_code = plan.fund_code
    	LEFT JOIN bank_flow bf on bf.flow_id = t1.flow_id
    	WHERE
    	  t1.fund_code = 1 AND 
    		pay.trans_time >= '%s'
    	AND pay.trans_time < '%s'
    	AND t1. repay_status = 1;
    	''' % (start_time, end_time)

    # 资金方的--
    sql_repay_fund = '''
        	SELECT
        	    concat(t1.product_no,t1.current_stage_no) AS '唯一编号',
        	    t1.product_no AS '产品编号',
        	    fc.fund_name as '资金方',
        		pay.stages AS '分期数',
        		t1.current_stage_no AS '当期期数',
        		date(t1.repay_time) '实还款日',
        		t1.repay_amount '还款总额',
        		t1.repay_principle '实还本金',
        		0 as '实还利息-直投',
        		t1.repay_fee_amount '实还服务费',
        		t1.repay_due_amount '实还罚息',
        		t1.remain '其他收益',
        		t1.flow_id '流水号',
        		bf.trans_amount AS '银行金额',
        		plan.principle AS '应还本金',
        		plan.interest AS '应还利息-直投',
        		plan.fee_amount as '应还服务费',
        		date(plan.deadline) AS '应还时间'
        	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 fund_repayment_plan plan on plan.product_no = t1.product_no AND plan.current_stage_no = t1.current_stage_no AND t1.fund_code=plan.fund_code
        	LEFT JOIN bank_flow bf on bf.flow_id = t1.flow_id
        	WHERE
        		pay.trans_time >= '%s'
        	AND pay.trans_time < '%s'
        	AND t1. repay_status = 1 AND pay.status=1
       ''' % (start_time, end_time)

    # 债转后保理的--
    sql_repay_baoli = '''
            	SELECT
            	    concat(t1.product_no,t1.current_stage_no) AS '唯一编号',
            	    t1.product_no AS '产品编号',
            	    fc.fund_name as '资金方',
            		pay.new_stages AS '分期数',
            		t1.current_stage_no AS '当期期数',
            		date(t1.repay_time) '实还款日',
            		t1.repay_amount '还款总额',
            		t1.repay_principle '实还本金',
            		0 as '实还利息-直投',
            		t1.repay_fee_amount '实还服务费',
            		t1.repay_due_amount '实还罚息',
            		t1.remain '其他收益',
            		t1.flow_id '流水号',
            		bf.trans_amount as '银行金额',
            		plan.principle AS '应还本金',
            		0 AS '应还利息-直投',
            		plan.fee_amount '应还服务费',
            		date(plan.deadline) AS '应还时间'
            	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 baoli_repayment_plan plan on plan.product_no = t1.product_no AND plan.user_current_stage_no = t1.current_stage_no AND t1.fund_code=plan.fund_code
            	left JOIN bank_flow bf on bf.flow_id = t1.flow_id
            	WHERE
            		pay.trans_time >= '%s'
            	AND pay.trans_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 '产品编号',
    		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 '流水号',
    		bf.trans_amount as '银行金额'
    	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
    	left JOIN bank_flow bf on bf.flow_id = t1.flow_id
    	WHERE t1.refund_time >= '%s' and t1.refund_time < '%s' and (t1.flow_id is not NULL or t1.refund_time > '2017-09-01') 
    ''' % (start_time, end_time)
    # 退款
    df_refund = pd.read_sql(sql_refund, 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_2017, df_fund_repay, df_baoli_repay], ignore_index=True)
    df_repay.fillna(0, inplace=True)

    all_wb = pyexcelerate.Workbook()
    df_refund_temp = df_refund.values.tolist()
    df_refund_temp.insert(0,df_refund.columns.tolist())
    all_wb.new_sheet(u'退款到还款账户的表',data=df_refund_temp)

    df_repay.loc[df_repay[[u'资金方',u'产品编号',u'当期期数']].duplicated(),u'应还本金']=0

    df_repay.loc[df_repay[u'资金方'] == u'保理',u'应还利息'] = 0
    df_repay.loc[df_repay[u'资金方'] != u'保理',u'应还利息-直投'] = df_repay[u'应还服务费']

    df_repay[u'应还本息-实还本息']=np.round(df_repay[u'应还本金']-df_repay[u'实还本金'],2)
    df_repay = df_repay[[u'唯一编号', u'产品编号', u'资金方', u'分期数', u'当期期数', u'实还款日', u'还款总额', u'实还本金', u'实还利息-直投'
        , u'实还服务费', u'实还罚息', u'其他收益', u'流水号', u'银行金额', u'应还本金', u'应还利息-直投', u'应还时间', u'应还本息-实还本息']]
    df_repay_temp = df_repay.values.tolist()
    df_repay_temp.insert(0,df_repay.columns.tolist())
    all_wb.new_sheet(u'用户实还表',data=df_repay_temp)

    all_wb.save(file_path+file_name %(year,month))

    # writer = pd.ExcelWriter(file_path + file_name % (year, month))
    # df_refund.to_excel(writer, sheet_name=u'退款到还款账户的表', index=None, encoding='UTF-8')
    # #应还本金重复的
    # df_repay.loc[df_repay[[u'产品编号',u'当期期数']].duplicated(),u'应还本金']=0
    # df_repay[u'应还本息-实还本息']=np.round(df_repay[u'应还本金']-df_repay[u'实还本金'],2)
    # df_repay.to_excel(writer, sheet_name=u'用户实还表', index=None, encoding='UTF-8')
    # writer.save()
    # writer.close()


if __name__ == '__main__':

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