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

sql_debt_age = """
select
  timestampdiff(
    month,
    concat(
      date_format(loan_paid_at, '%%Y-%%m'),
      '-01'
    ),
    concat(
      date_format(
        if(
          deadline > '{0}',
          deadline,
          '{0}'
        ),
        '%%Y-%%m'
      ),
      '-01'
    )
  ) loan_age,
  date_format(deadline, '%%Y-%%m') 应还年月,
  class 风险等级,
  sum(assets) assets
from
  test_mzh.cash_assets_model
where loan_paid_at < '{0}' and is_active = 1
group by 1,  2 ;
"""

sql_remain = """
select
  loan_id,
  class 风险等级,
  date(loan_paid_at) 放款日期,
  service_fee 应还服务费,
  assets_remain
from
  test_mzh.cash_assets_model
where loan_paid_at < '{0}' and  
assets_remain <> 0 and is_active = 1;
"""

sql_term_no = """
select
  term_no 当前期数,
  date_format(deadline, '%%Y-%%m') 应还年月,
  class 风险等级,
  sum(assets) assets
from
  test_mzh.cash_assets_model
where loan_paid_at < '{0}' and is_active = 1
group by 1,  2,  3 ;
"""

sql_total = """
select 
  sum(
    if(
      term_no = 1,
      contract_loan_amount,
      0
    )
  ) 放款金额,
  sum(
    if(
      term_no = 1,
      bad_debt_fee,
      0
    )
  ) 计提风险金,
  sum(
    if(
      term_no = 1,
      bad_debt_fee_no_pre_fee,
      0
    )
  ) 去掉一次性服务费的计提风险金,
  sum(assets) assets,
  sum(assets_remain) assets_remain 
from
  test_mzh.cash_assets_model 
where loan_paid_at < '{}' 
  and is_active = 1 
"""


class asserts():
    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 asserts_details(self):
        df = pd.read_sql(sql=sql_total.format(self.end), con=conn)
        df1 = pd.read_sql(sql=sql_debt_age.format(self.end), con=conn)
        df2 = pd.read_sql(sql=sql_term_no.format(self.end), con=conn)
        df3 = pd.read_sql(sql=sql_remain.format(self.end), con=conn)

        excel_file = pd.ExcelWriter(
            os.path.join(self.dir_path, u'assets减值明细-{}.xlsx'.format(self.start.strftime('%Y%m'))))

        df.to_excel(excel_file, sheet_name=u'汇总', index=None)
        df1.to_excel(excel_file, sheet_name=u'账龄汇总', index=None)
        df2.to_excel(excel_file, sheet_name=u'期数汇总', index=None)
        df3.to_excel(excel_file, sheet_name=u'assets_remain', index=None)
        excel_file.close()


if __name__ == '__main__':
    asserts().asserts_details()
    print('======================asserts done===================================')
