# -*- coding: utf-8 -*-
import sys
import pandas as pd
import datetime
import os
import numpy as np
# 小赢期收10月19号之后的放款且还款至众信利民统计#

sys.path.append('../../../finance_out_table')
from db_con.db_connect import sql_engine

# path = '/home/quant_group/vpants/finance/table/'
path = '/Users/chenxiaozhe/Downloads/test/201901'
xyqb_conn = sql_engine('xyqb', 'xyqb').get_engine()
payment_center_conn = sql_engine('paycenter', 'payment_center').get_engine()

query_xyqb_sql = """
select  rr.deadline as '应还时间',rr.repayment_received_at as '实还时间',lamh.loan_paid_at as '放款时间', rr.actual_repayment as '实还总额',rr.pay_center_order_no,lamh.loan_application_history_id,fii.xyqb_loan_request_id,
rr.principal as '实还本金',rr.interest as '实还利息',rr.premium as '实还保费',lamh.contract_loan_amount as '放款本金',lamh.contract_term as '总期数',rr.term_no as '期数' from repayment_record rr 
inner join loan_application_manifest_history lamh on lamh.loan_application_history_id=rr.loan_application_history_id and lamh.funding_corp_id=610 and lamh.transaction_status=2 and lamh.loan_paid_at >='2018-10-19' 
inner join funding_interaction_info fii on fii.loan_id=lamh.loan_application_history_id
where rr.updated_at>='2019-01-01' and  rr.updated_at <= '2019-01-22 11:22:51' and rr.repayment_status=3 and rr.overdue_days = 0
"""

query_paycenter_sql = """
select merchant_repay_order_no as pay_center_order_no ,amount from repay_order where repay_status=3 and merchant_id=3 and merchant_repay_order_no in {}
"""


class xiaoying_zxlm():
    def __init__(self):
        today = datetime.date.today()
        self.end = datetime.date(today.year, today.month, 1)
        last_day = self.end + datetime.timedelta(days=-1)
        self.start = datetime.date(last_day.year, last_day.month, 1)
        self.dir_path = path + self.start.strftime('%Y%m')
        if not os.path.exists(self.dir_path):
            os.makedirs(self.dir_path)


    def xiaoying_zxlm_detail(self):
        df_xyqb = pd.read_sql(sql=query_xyqb_sql, con=xyqb_conn)
        df_xyqb.pay_center_order_no = df_xyqb.pay_center_order_no.astype(str)

        df_repay_order = pd.read_sql(
            sql=query_paycenter_sql.format(str(tuple(df_xyqb.pay_center_order_no)).replace(',)', ')')),
            con=payment_center_conn)

        df_repay_all = pd.merge(df_xyqb, df_repay_order, how='inner', on='pay_center_order_no')
        df_repay_all[u'小赢14%部分本息'] = np.round(np.pmt(0.011667, df_repay_all[u'总期数'], -df_repay_all[u'放款本金']), 2)
        df_repay_all[u'借款人每期36%部分还款本息'] = np.round(
            df_repay_all[u'放款本金'] * 0.36 / 12 + df_repay_all[u'放款本金'] / df_repay_all[u'总期数'], 2)
        df_repay_all[u'QG服务费金额-期收'] = df_repay_all[u'借款人每期36%部分还款本息'] - df_repay_all[u'小赢14%部分本息']
        df_repay_all.to_csv(os.path.join(path, '小赢期收10月19号之后的放款且还款至众信利民统计new-{}.csv'.format(self.start.strftime('%Y%m'))),index=None,encoding='gbk')





if __name__ == '__main__':
    xiaoying_zxlm().xiaoying_zxlm_detail()
    print('==================================xiaoying_zxlm done===================================')
