# coding: utf-8
import pandas as pd
from sqlalchemy import create_engine
import numpy as np
import datetime
"""
关联还款计划，插入到中间表ref表中

"""
pd.options.mode.chained_assignment = None

engine_audit = create_engine('mysql+mysqldb://yulong:ohVU1nPITynSZwR2@172.16.3.201:3306/audit?charset=utf8', echo=True)
engine_new_transaction = create_engine( 'mysql+mysqldb://yulong_rw:TouBStYwN8wkdxVt@172.16.3.201:3306/new_transaction?charset=utf8',echo=True)
engine_xyqb = create_engine('mysql+mysqldb://syzhu_data_r:ulk0989742097y43@192.168.4.6:8066/xyqb?charset=utf8',echo=True)
engine_offline = create_engine('mysql+mysqldb://syzhu_data_r:ulk0989742097y43@192.168.4.6:8066/offline?charset=utf8',echo=True)
engine_pay_center = create_engine('mysql+mysqldb://syzhu_data_r:ulk0989742097y43@192.168.4.6:8066/payment_center?charset=utf8',echo=True)
insert_service_sql = """ INSERT INTO funding_repayment_record (
	loan_id,
	funding_code,
	term_no,
	deadline,
	principle,
	interest,
	punish_fee,
	funding_service_fee,
	current_repayment,
	AIR,
	repaid_at,
	remark
    )
VALUES
	(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"""


def cal_prin_inst(x):
    fund_code = x['fund_code']
    a = x['contract_loan_amount']
    c = int(x['contract_term'])
    b = x['AIR']
    term = int(x['term_no'])
    result = {}
    if fund_code==290:
        result['inst'] = np.round(np.ipmt(b / 12, term, c, -a), 2)
        if term == c:
            result['prin'] = a
            for i in xrange(1, c):
                result['prin'] -= np.round(np.ppmt(b / 12, i, c, -a), 2)
            result['total'] = result['inst'] + result['prin']
        else:
            result['total'] = np.round(np.pmt(b / 12, c, -a), 2)
            result['prin'] = result['total'] - result['inst']
    elif fund_code==330:
        bath_no = x['bath_no']
        if bath_no in('HZ20170316-055-001-003','HZ20170316-055-001-004','HZ20170316-055-001-002'):
            result['inst'] = np.round(np.ipmt(b / 12, term, c, -a), 2)
            result['total'] = np.round(np.pmt(b / 12, c, -a), 2)
            if term == c:
                result['prin'] = a
                for i in xrange(1, c):
                    result['prin'] -= np.round(np.ppmt(b / 12, i, c, -a), 2)
            else:
                result['prin'] = np.round(np.ppmt(b / 12,term, c, -a), 2)
        elif  bath_no =='HZ20170316-055-001-005':
            result['inst'] = np.round(np.ipmt(b / 12, term, c, -a), 2)
            if term == c:
                result['prin'] = a
                for i in xrange(1, c):
                    result['prin'] -= np.round(np.ppmt(b / 12, i, c, -a), 2)
                result['total'] = result['inst'] + result['prin']
            else:
                result['total'] = np.round(np.pmt(b / 12, c, -a), 2)
                result['prin'] = result['total'] - result['inst']

        elif  bath_no in('HZ20170316-055-001-001','HZ20170316-055-001-006'):

            if term == 1:
                result['inst'] = np.round(35 * a * b / 365, 2)
                result['prin'] = np.round( a/c, 2)
            elif term == 2:
                result['prin'] = a - np.round(a / c, 2)
                result['inst'] = 30 * result['prin'] * b / 365
            elif term == 3:
                result['prin'] = a
                for i in xrange(1, c):
                    result['prin'] -= np.round(a/c, 2)
                result['inst'] = 31*result['prin']*b/365
            result['total'] = result['inst'] + result['prin']

    return result





def update_hbxj(funding_code):
    if funding_code==290:
        merchant_id = 1001
        file_chongfu_name = u'E:/xyqb/湖北消金/湖北消金2017-05代偿且分账重复数据.xlsx'
        file_chenggong_name = u'E:/xyqb/湖北消金/湖北消金2017-05已分账数据.xlsx'
    elif funding_code==330:
        merchant_id = 1002
        file_chongfu_name = u'E:/xyqb/湖北消金/阳光广源2017-05代偿且分账重复数据.xlsx'
        file_chenggong_name = u'E:/xyqb/湖北消金/阳光广源2017-05已分账数据.xlsx'

    sql = """ select id,loan_id,term_no,IFNULL(principle,0) principle,IFNULL(interest,0) interest,IFNULL(punish_fee,0) punish_fee,IFNULL(funding_service_fee,0) funding_service_fee from funding_repayment_record where funding_code=%s and repaid_at>='2017-05-01' and repaid_at<'2017-06-01' """
    select_divide_info = """
      SELECT repay.merchant_repay_order_no order_no,info.updated_at repaid_at,info.divide_amount FROM repay_divide_info  info
      JOIN repay_order repay ON info.repay_order_no=repay.order_id
      WHERE info.divide_merchant_id=%s AND info.divide_status=3  
      AND info.updated_at >='2017-05-01' AND info.updated_at <'2017-06-01'  
    """
    select_repayment_plan = """ 
      SELECT
            plan.pay_center_order_no order_no,
            plan.loan_application_history_id loan_id,
            plan.term_no,
            plan.deadline,
            history.contract_term,
            history.contract_loan_amount,
            history.annual_interest_rate AIR
        
        FROM
            repayment_plan plan
        JOIN loan_application_manifest_history history ON history.id=plan.loan_application_manifest_history_id 
      WHERE plan.pay_center_order_no in %s """
    df_1 = pd.read_sql(select_divide_info % (str(merchant_id),),engine_pay_center)
    df_1.order_no = df_1.order_no.astype(str)
    a = df_1['order_no'].tolist()
    df_2 = pd.read_sql(select_repayment_plan % (str(tuple(a)),),engine_xyqb)
    df_2.order_no = df_2.order_no.astype(str)
    df_all = pd.merge(df_1,df_2,on='order_no')
    df_all.loan_id = df_all.loan_id.astype(str)
    df_all.term_no = df_all.term_no.astype(int)
    df_all['fund_code'] = funding_code
    # 阳光广源的还资金利率与债权包对应
    # if funding_code==330:
    #     df_a1 = pd.read_excel(u'E:/xyqb/湖北消金/阳光广源各批次对应明细及计息公式_1-6批.xlsx',sheetname=u'备注')
    #     df_a2 = pd.read_excel(u'E:/xyqb/湖北消金/阳光广源各批次对应明细及计息公式_1-6批.xlsx',sheetname=u'信用钱包-明细数据',skip_footer=1)
    #     df_a1 = df_a1[['bath_no','term_no','AIR']]
    #     df_a1.bath_no = df_a1.bath_no.astype(str)
    #     df_a1.term_no = df_a1.term_no.astype(int)
    #     df_a1.AIR = df_a1.AIR.astype(float)
    #     df_a2 = df_a2[['loan_id','term_no','bath_no']]
    #     df_a2.bath_no = df_a2.bath_no.astype(str)
    #     df_a2.term_no = df_a2.term_no.astype(int)
    #     df_a2.loan_id = df_a2.loan_id.astype(str)
    #     df_air = pd.merge(df_a1,df_a2,on=['bath_no','term_no'])
    #     df_air = df_air[['loan_id','AIR','bath_no']]
    #     df_air.loan_id = df_air.loan_id.astype(str)
    #     df_air.bath_no = df_air.bath_no.astype(str)
    #     df_air.AIR = df_air.AIR.astype(float)
    #     df_all.drop('AIR', inplace=True, axis=1)
    #     df_all = pd.merge(df_all,df_air,on='loan_id')
    #     df_all['principle'] = df_all.apply(lambda x: cal_prin_inst(x)['prin'], axis=1)
    #     df_all['interest'] = df_all.apply(lambda x: cal_prin_inst(x)['inst'], axis=1)
    df_simple = pd.read_sql(sql %(int(funding_code),), con=engine_audit)
    df_simple['loan_id'] = df_simple['loan_id'].astype(str)
    df_simple['term_no'] = df_simple['term_no'].astype(int)
    df_in = pd.merge(df_all, df_simple, on=['loan_id','term_no'])
    df_not_in = df_all.ix[~df_all.order_no.isin(df_in.order_no)]
    if len(df_in) >0:
        df_in['current_repayment'] = df_in['principle'] + df_in['interest']
        df_in.to_excel(file_chongfu_name, index=None)
        update_sql = """update funding_repayment_record set remark='已代偿且分账成功', current_repayment=%s where loan_id=%s AND term_no=%s AND  funding_code =%s """
        list1 = df_in[['current_repayment', 'loan_id', 'term_no', 'fund_code']].values.tolist()
        engine_audit.execute(update_sql, list1)
    if len(df_not_in)>0:
        df_not_in['remark'] = '已分账'
        if funding_code == 330:
            select_record = """
                SELECT
                    (rf.principle - rf.mitigate_principle) principle,
                    (rf.interest - rf.mitigate_interest) interest ,
                    (rf.service_fee -rf.mitigate_service_fee) service_fee,
                    (rf.punish-rf.mitigate_collection_relief) punish_fee,
                    plan.real_loan_id loan_id,
                    plan.term_no
                FROM
                    xjd_repay_plan_repay_record_ref rf
                JOIN user_repayment_plan plan ON plan.id = rf.plan_id
                WHERE  plan.real_loan_id in %s
                AND rf.principle>=1
                """
            b = df_not_in['loan_id'].tolist()
            df_record = pd.read_sql(select_record %(str(tuple(b)),),engine_new_transaction)
            df_record.loan_id = df_record.loan_id.astype(str)
            df_record.term_no = df_record.term_no.astype(int)
            df_not_in = pd.merge(df_not_in,df_record,on=['loan_id','term_no'])
        else:
            df_not_in['principle'] = df_not_in.apply(lambda x: cal_prin_inst(x)['prin'], axis=1)
            df_not_in['interest'] = df_not_in.apply(lambda x: cal_prin_inst(x)['inst'], axis=1)
            df_not_in['overdays'] = (df_not_in['repaid_at'] - df_not_in['deadline']).apply(lambda x: x.days)
            df_not_in['overdays'] = df_not_in['overdays'].astype(int)
            df_not_in['overdays'] = df_not_in['overdays'] + 1
            df_not_in['interest'] = df_not_in['interest'].astype(float)
            df_not_in['punish_fee'] = 0
            df_not_in['service_fee'] = 0
            df_not_in.ix[df_not_in.overdays > 3, 'punish_fee'] = df_not_in.ix[df_not_in.overdays > 3, 'principle'] * \
                                                                 df_not_in.ix[df_not_in.overdays > 3, 'overdays'] * \
                                                                 df_not_in.ix[df_not_in.overdays > 3, 'AIR'] / 360
            df_not_in['punish_fee'] = df_not_in['punish_fee'].astype(float)
        df_not_in['current_repayment'] = df_not_in['principle'] + df_not_in['interest'] + df_not_in['punish_fee']+ df_not_in['service_fee']
        list1 = df_not_in[
            ['loan_id', 'fund_code', 'term_no', 'deadline', 'principle', 'interest', 'service_fee','punish_fee',
             'current_repayment', 'AIR', 'repaid_at', 'remark']].values.tolist()
        df_not_in.to_excel(file_chenggong_name, index=None)
        engine_audit.execute(insert_service_sql, list1)

update_hbxj(330)