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



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

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 = 630
"""

query_duishou_sql = """
SELECT loan_year 放款年,loan_month 放款月,fund_name 资金方, sum(loan_amount) 放款金额 , sum(duishou_amount) QG服务费金额趸收  FROM (
SELECT 
  year(loan.loan_paid_at) loan_year,
  month(loan.loan_paid_at) loan_month,
  f.name fund_name,
  loan.contract_loan_amount loan_amount,
  round(loan.contract_loan_amount * 0.00875,2 ) duishou_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 = 630
) t group by 1,2,3

"""


class xiaoniu_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 xiaoniu_loan_repay_details(self):
        # 放款汇总
        df_loan = pd.read_sql(sql=query_loan_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_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)

        # 趸收收入确认表
        df_loan_details = pd.read_sql(sql=query_duishou_sql.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__':
    xiaoniu_loan_repay().xiaoniu_loan_repay_details()
    print('======================xiaoniu_loan_repay done===================================')


