# -*- 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/'
audit_conn = sql_engine('audit', 'audit').get_engine()

query_loan_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 
  AND loan.loan_paid_at >= '{0}' 
    AND loan.loan_paid_at < '{1}' 
    AND loan.funding_code = 600
GROUP BY 1, 2, 3, 4 ;
"""

count_loan_sql = """
SELECT 
  count(*) loan_count
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 = 600

"""


query_loan_details = """
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
  where loan.loan_paid_at >= '{0}' 
    AND loan.loan_paid_at < '{1}'
     AND loan.funding_code = 600
"""


class xingye_loan():
    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)
        ##test##
        #self.start = datetime.date(2018, 9, 1)
        #self.end = datetime.date(2018, 10, 1)
        ##test##
        self.dir_path = path + self.start.strftime('%Y%m')
        if not os.path.exists(self.dir_path):
            os.makedirs(self.dir_path)

    def xingye_loan_details(self):
        #放款汇总
        df_loan = pd.read_sql(sql=query_loan_sql.format(self.start, self.end), con=audit_conn)
        df_loan_count = pd.read_sql(sql=count_loan_sql.format(self.start, self.end), con=audit_conn)
        df_loan['代付成本'] = df_loan_count['loan_count'].tolist()[0] * 1
        df_loan.to_excel(os.path.join(self.dir_path, u'兴业-放款汇总表-{}.xlsx'.format(self.start.strftime('%Y%m'))), index=None)

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


if __name__ == '__main__':
    xingye_loan().xingye_loan_details()
    print('======================xingye_loan done===================================')