# -*- coding: utf-8 -*-
import sys
import pandas as pd
import datetime
import os

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'
audit_conn = sql_engine('audit', 'audit').get_engine()
new_transaction_conn = sql_engine('audit', 'new_transaction').get_engine()

summary_sql = """
SELECT 
  year(loan.loan_paid_at) 放款年,
  month(loan.loan_paid_at) 放款月,
  f.name 资金方,
  sum(loan.contract_loan_amount) 放款金额
FROM
  audit.loan_manifest loan 
  JOIN basic.funding_corp f 
    ON f.funding_code = loan.funding_code 
  where loan.loan_paid_at >= '{0}' 
    AND loan.loan_paid_at < '{1}' 
    and loan.funding_code = 620
GROUP BY 1, 2;
"""

details_sql = """
SELECT 
  f.name 资金方,
  loan.loan_id,
  loan.contract_no 贷款合同号,
  date(loan.loan_paid_at) 放款日期,
  loan.contract_loan_amount 放款金额,
  loan.contract_term 总期数
FROM
  audit.loan_manifest loan 
  JOIN basic.funding_corp f 
    ON f.funding_code = loan.funding_code
    AND loan.loan_paid_at >= '{0}' 
    AND loan.loan_paid_at < '{1}'
    and loan.funding_code = 620
"""

repay_sql = """
    select year(loan_paid_at) as '放款年',month(loan_paid_at) as '放款月',loan_id,term_no as '期数', year(bill_time) as '还款年',month(bill_time) as '还款月', principle as '本金',interest as '利息',punish as '罚息',over_due_days as '逾期天数' from minjin_repay_record_online
     where bill_time >= '{0}' and  bill_time < '{1}'; 
"""

repay_sum_sql = """
    select  year(bill_time) as '实还年',month(bill_time) as '实还月', sum(principle) as '当期实还本金',sum(interest) as '当期实还利息', sum(punish) as '当期实还罚息', sum(IF(over_due_days > 90 ,0,round((interest+punish) * 0.25,2))) as 'QG服务费金额2-期收' from minjin_repay_record_online
     group by 1,2

"""

loan_repay_sql = """
     select  year(bill_time) as '实还年',month(bill_time) as '实还月',loan_id, principle as '当期实还本金',interest as '当期实还利息', punish as '当期实还罚息', IF(over_due_days > 90 ,0,round((interest+punish) * 0.25,2)) as 'QG服务费金额2-期收' from minjin_repay_record_online

"""


class minjin_loan_repay():
    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 minjin_loan_repay_detail(self):
        # 放款汇总表
        #df_loan = pd.read_sql(sql=summary_sql.format(self.start, self.end), con=audit_conn)
        #df_loan.to_excel(os.path.join(self.dir_path, u'民金放款-汇总表-{}.xlsx'.format(self.start.strftime('%Y%m'))),index=None)

        # 放款明细表
        #df_detail = pd.read_sql(sql=details_sql.format(self.start, self.end), con=audit_conn)
        #df_detail.to_excel(os.path.join(self.dir_path, u'民金放款-明细表-{}.xlsx'.format(self.start.strftime('%Y%m'))),index=None)

        # 客户还款表
        df_repay = pd.read_sql(sql=repay_sql.format(self.start, self.end), con=new_transaction_conn)
        df_repay['总额'] = round(df_repay['本金'] + df_repay['利息'] + df_repay['罚息'], 2)
        df_repay.to_excel(os.path.join(self.dir_path, '民金-还款-{}.xlsx'.format(self.start.strftime('%Y%m'))),
                          index=None)

        # 收入确认表
        df_qishou = pd.read_sql(sql=repay_sum_sql, con=new_transaction_conn)

        df_qishou['总额'] = round(
            df_qishou['当期实还本金'] + df_qishou['当期实还利息'] + df_qishou['当期实还罚息'], 2)

        df_qishou.to_excel(os.path.join(self.dir_path, '民金-收入确认-{}.xlsx'.format(self.start.strftime('%Y%m'))),
                           index=None)

        df_loan_qishou = pd.read_sql(sql=loan_repay_sql, con=new_transaction_conn)

        df_loan_qishou['总额'] = round(
            df_loan_qishou['当期实还本金'] + df_loan_qishou['当期实还利息'] + df_loan_qishou['当期实还罚息'], 2)

        df_loan_qishou.to_excel(os.path.join(self.dir_path, '民金-结算-{}.xlsx'.format(self.start.strftime('%Y%m'))), index=None)


if __name__ == '__main__':
    minjin_loan_repay().minjin_loan_repay_detail()
    print('======================minjin_loan done===================================')
