# coding: utf8
import datetime

import numpy as np
import pandas as pd
import sys
from sqlalchemy import create_engine

reload(sys)
sys.setdefaultencoding('utf8')
"""
关联还款计划，插入到中间表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,
	funding_service_fee,
	punish_fee,
	current_repayment,
	AIR,
	flow_id,
	repaid_at,
	remark
    )
VALUES
	(%s,%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 == 390:
        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']
    return result


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>='%s' and repaid_at<'%s' """
select_divide_info = """
  SELECT repay.merchant_repay_order_no order_no,info.updated_at repaid_at,info.divide_value,
    info.divide_yborder_id flow_id
  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.divide_value>0
  AND info.updated_at >='%s' AND info.updated_at <'%s'  
  AND info.id in (
1735866,1735910,1735834,1784254,1784262,1784278,1784290,1784298,1784306,1784378,1784274,1784226,1784230,1784234,1784242,1784246,1784270,1784322,1784342,1784374
)
"""

start_time = '2017-09-01'
end_time = '2017-10-01'

step = 10000


def update_hbxj(funding_code):
    if funding_code == 290:
        merchant_id = 1001
        file_chongfu_name = u'E:/xyqb/湖北消金/2017-06/湖北消金2017-09代偿且分账重复数据.xlsx'
        file_chenggong_name = u'E:/xyqb/湖北消金/2017-06/湖北消金2017-09已分账数据.xlsx'
    elif funding_code == 330:
        merchant_id = 1002
        file_chongfu_name = u'E:/xyqb/湖北消金/2017-06/阳光广源2017-09代偿且分账重复数据.xlsx'
        file_chenggong_name = u'E:/xyqb/湖北消金/2017-06/阳光广源2017-09已分账数据.xlsx'
    elif funding_code == 390:
        merchant_id = 1003
        file_chongfu_name = u'E:/xyqb/湖北消金/2017-06/渤海宏泰2017-09代偿且分账重复数据.xlsx'
        file_chenggong_name = u'E:/xyqb/湖北消金/2017-06/渤海宏泰2017-09已分账数据.xlsx'
    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), start_time, end_time), 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
    df_simple = pd.read_sql(sql % (int(funding_code), start_time, end_time), 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='已代偿且分账成功',divide_status=2 where loan_id=%s AND term_no=%s AND  funding_code =%s """
        list1 = df_in[['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>=0.01
                """
            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'])
        elif funding_code == 290:
            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)
        elif funding_code == 390:
            df_not_in['deadline'] = pd.to_datetime(df_not_in.deadline).dt.date
            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)
            select_record1 = """
                SELECT
                    (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_record1 % (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'])
            df_not_in['service_fee'] = 0
        df_not_in['current_repayment'] = df_not_in['principle'] + df_not_in['interest'] + df_not_in['punish_fee'] + \
                                         df_not_in['service_fee']
        df_not_in.to_excel(file_chenggong_name, index=None)
        df_out = df_not_in[
            ['loan_id', 'fund_code', 'term_no', 'deadline', 'principle', 'interest', 'service_fee', 'punish_fee',
             'current_repayment', 'AIR', 'flow_id', 'repaid_at', 'remark']]

        df_out.rename(columns={'fund_code': 'funding_code', 'service_fee': 'funding_service_fee'}, inplace=True)
        # df_out.to_excel(file_chenggong_name, index=None)
        df_out['divide_status'] = 1
        df_out.to_sql('funding_repayment_record', con=engine_audit, chunksize=step, if_exists='append', index=None)


update_hbxj(390)
