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

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

path = '/home/quant_group/vpants/finance/table/'
engine_audit = sql_engine('audit', 'audit').get_engine()

summary_sql = """
SELECT 
  year(loan.loan_paid_at) 放款年,
  month(loan.loan_paid_at) 放款月,
  f.name 资金方,
  loan.class 风险等级,
  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 not in (590,600,630)
GROUP BY 1, 2, 3, 4 ;
"""

details_sql = """
SELECT 
  f.name 资金方,
  loan.loan_id,
  loan.contract_no 贷款合同号,
  date(loan.loan_paid_at) 放款日期,
  loan.contract_loan_amount 放款金额,
  loan.contract_term 总期数,
  loan.monthly_interest_rate 月利率,
  loan.class 风险等级
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 not in (590,600,630)
"""


class loan_order():
    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 loan_order_details(self):
        df = pd.read_sql(sql=summary_sql.format(self.start, self.end), con=engine_audit)
        df.to_excel(os.path.join(self.dir_path, u'现金贷放款表-新模式-汇总表-{}.xlsx'.format(self.start.strftime('%Y%m'))),
                    index=None)

        df = pd.read_sql(sql=details_sql.format(self.start, self.end), con=engine_audit)
        df.to_excel(os.path.join(self.dir_path, u'现金贷放款表-新模式-明细表-{}.xlsx'.format(self.start.strftime('%Y%m'))),
                    index=None)


if __name__ == '__main__':
    loan_order().loan_order_details()
    print('======================loan_order done===================================')
