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

collect_data_sql = """
    INSERT INTO tmp_xjd_plan_ref SELECT
     plan_id,
     sum(ref_amount) ref_amount,
     sum(principle) principle,
     sum(interest) interest,
     sum(service_fee) service_fee,
     sum(punish) punish,
     sum(collection_relief) collection_relief,
     sum(remain_income) remain_income,
     sum(xyqb_poundage) xyqb_poundage,
     sum(mitigate_collection_relief) mitigate_collection_relief,
     sum(mitigate_service_fee) mitigate_service_fee,
     sum(mitigate_interest) mitigate_interest,
     sum(mitigate_principle) mitigate_principle,
     sum(red_package_fee) red_package_fee,
     sum(mitigate_all) mitigate_all,
     sum(residual_service_fee) residual_service_fee,
     min(bill_time) first_repaid_at,
     max(bill_time) last_repaid_at
    FROM
     new_transaction.xjd_repay_plan_repay_record_ref where bill_time < {}
    GROUP BY
     1;
"""

append_collect_data_sql = """
    INSERT INTO tmp_xjd_plan_ref SELECT
     plan_id,
     sum(ref_amount) ref_amount,
     sum(principle) principle,
     sum(interest) interest,
     sum(service_fee) service_fee,
     sum(punish) punish,
     sum(collection_relief) collection_relief,
     sum(remain_income) remain_income,
     sum(xyqb_poundage) xyqb_poundage,
     sum(mitigate_collection_relief) mitigate_collection_relief,
     sum(mitigate_service_fee) mitigate_service_fee,
     sum(mitigate_interest) mitigate_interest,
     sum(mitigate_principle) mitigate_principle,
     sum(red_package_fee) red_package_fee,
     sum(mitigate_all) mitigate_all,
     sum(residual_service_fee) residual_service_fee,
     min(bill_time) first_repaid_at,
     max(bill_time) last_repaid_at
    FROM
     new_transaction.xjd_repay_plan_repay_record_ref where bill_time >= {} and bill_time < {}
    GROUP BY
     1;
"""

loan_sql = """
    select
     lm.is_active,
      lm.funding_code,
      date_format(lm.loan_paid_at, '%%Y-%%m') loan_paid_at,
      sum(lm.contract_loan_amount) contract_loan_amount
    from
     audit.loan_manifest lm
    where lm.funding_code in (270, 310, 320, 390, 410, 490)
    group by 1,2,3;
"""
behalf_sql = """
select
 lm.is_active,
  lm.funding_code,
  date_format(lm.loan_paid_at, '%%Y-%%m') loan_paid_at,
  urp.term_no,
  date_format(urp.deadline, '%%Y-%%m') deadline,
  sum(urp.principle + urp.interest) req_prin_inst
from
 new_transaction.user_repayment_plan urp
  join audit.loan_manifest lm
    on lm.ref_id = urp.ref_id
    and lm.funding_code in (270, 310, 320, 390)
  left join test_mzh.tmp_xjd_plan_ref ref
    on urp.id = ref.plan_id
where ref.plan_id is null
group by 1,2,3,4,5
union
all
select
 lm.is_active,
  lm.funding_code,
  date_format(lm.loan_paid_at, '%%Y-%%m') loan_paid_at,
  urp.term_no,
  date_format(urp.deadline, '%%Y-%%m') deadline,
  sum(urp.principle + urp.interest) req_prin_inst
from
 test_mzh.tmp_xjd_plan_ref ref
  join new_transaction.user_repayment_plan urp
    on urp.id = ref.plan_id
    and urp.fund_code in (270, 310, 320, 390)
    and date_format(urp.deadline, '%%Y-%%m') < date_format(ref.first_repaid_at, '%%Y-%%m')
  join audit.loan_manifest lm
    on lm.ref_id = urp.ref_id
group by 1,2,3,4,5;
"""

collect_sql = """
select
 lm.is_active,
  lm.funding_code,
  date_format(lm.loan_paid_at, '%%Y-%%m') loan_paid_at,
  urp.term_no,
  date_format(ref.first_repaid_at, '%%Y-%%m') repaid_at,
  sum(if (
    date_format(urp.deadline, '%%Y-%%m') < date_format(ref.first_repaid_at, '%%Y-%%m'),
    ref.principle - ref.mitigate_principle + ref.interest - ref.mitigate_interest,
    0
 ))  paid_prin_inst ,
  sum(ref.punish - ref.mitigate_collection_relief) paid_punish
from
 test_mzh.tmp_xjd_plan_ref ref
  join new_transaction.user_repayment_plan urp
    on urp.id = ref.plan_id
    and urp.fund_code in (270, 310, 320, 390)
  join audit.loan_manifest lm
    on lm.ref_id = urp.ref_id
group by 1,2,3,4,5;

"""
head_repay_sql = """
SELECT
 lm.is_active,
 lm.funding_code,
 date_format(lm.loan_paid_at, '%%Y-%%m') loan_paid_at,
 urp.term_no,
 date_format(
  ref.first_repaid_at,
  '%%Y-%%m'
 ) repaid_at,
 sum(
  ref.principle - ref.mitigate_principle + ref.interest - ref.mitigate_interest
 ) repay_prin_inst
FROM
 test_mzh.tmp_xjd_plan_ref ref
JOIN new_transaction.user_repayment_plan urp ON urp.id = ref.plan_id
AND urp.fund_code  in (410, 490)
AND date_format(urp.deadline, '%%Y-%%m') >= date_format(
 ref.first_repaid_at,
 '%%Y-%%m'
)
JOIN audit.loan_manifest lm ON lm.ref_id = urp.ref_id
GROUP BY 1, 2, 3, 4, 5;

"""

t_plus_behalf_sql = """
SELECT
 lm.is_active,
 lm.funding_code,
 date_format(lm.loan_paid_at, '%%Y-%%m') loan_paid_at,
 urp.term_no,
 date_format(urp.deadline, '%%Y-%%m') deadline,
 sum(urp.principle + urp.interest) req_prin_inst
FROM
 new_transaction.user_repayment_plan urp
JOIN audit.loan_manifest lm ON lm.ref_id = urp.ref_id
AND lm.funding_code  in (410, 490)
LEFT JOIN test_mzh.tmp_xjd_plan_ref ref ON urp.id = ref.plan_id
WHERE
 ref.plan_id IS NULL
GROUP BY 1,2,3,4,5
UNION ALL
 SELECT
 lm.is_active,
  lm.funding_code,
  date_format(lm.loan_paid_at, '%%Y-%%m') loan_paid_at,
  urp.term_no,
  date_format(urp.deadline, '%%Y-%%m') deadline,
  sum(urp.principle + urp.interest) req_prin_inst
 FROM
 test_mzh.tmp_xjd_plan_ref ref
 JOIN new_transaction.user_repayment_plan urp ON urp.id = ref.plan_id
 AND urp.fund_code  in (410, 490)
 AND date_format(
  DATE_ADD(
   urp.deadline,
   INTERVAL 1 MONTH
 ),
  '%%Y-%%m'
 ) < date_format(
  ref.first_repaid_at,
  '%%Y-%%m'
 )
 JOIN audit.loan_manifest lm ON lm.ref_id = urp.ref_id
 GROUP BY 1,2,3,4,5;

"""
t_plus_collect_sql = """
SELECT
 lm.is_active,
 lm.funding_code,
 date_format(lm.loan_paid_at, '%%Y-%%m') loan_paid_at,
 urp.term_no,
 date_format(
  ref.first_repaid_at,
  '%%Y-%%m'
 ) repaid_at,
 sum(

  IF (
   date_format(
    DATE_ADD(
     urp.deadline,
     INTERVAL 1 MONTH
 ),
    '%%Y-%%m'
 ) < date_format(
    ref.first_repaid_at,
    '%%Y-%%m'
 ),
   ref.principle - ref.mitigate_principle + ref.interest - ref.mitigate_interest,
   0
 )
 ) paid_prin_inst,
 sum(
  ref.punish - ref.mitigate_collection_relief
 ) paid_punish
FROM
 test_mzh.tmp_xjd_plan_ref ref
JOIN new_transaction.user_repayment_plan urp ON urp.id = ref.plan_id
AND urp.fund_code  in (410, 490)
JOIN audit.loan_manifest lm ON lm.ref_id = urp.ref_id
GROUP BY 1,2,3,4,5;

"""


class collection_behalf():
    def __init__(self, is_mock):
        self.is_mock = is_mock
        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 collection_behalf_details(self):
        if not self.is_mock:
            # 准备数据
            conn.execute(collect_data_sql.format(self.end.strftime("'%Y-%m-%d'")))

        # 出表
        # 放款统计
        df_loan = pd.read_sql(sql=loan_sql, con=engine_new_transaction)
        # 代偿统计
        df_behalf = pd.read_sql_query(sql=behalf_sql, con=engine_new_transaction)
        # 催回
        df_collect = pd.read_sql_query(sql=collect_sql, con=engine_new_transaction)
        # T+1日提前还款
        df_head_repay = pd.read_sql_query(sql=head_repay_sql, con=engine_new_transaction)
        # T+1日代偿
        df_t_plus_behalf = pd.read_sql_query(sql=t_plus_behalf_sql, con=engine_new_transaction)
        # T+1日催回
        df_t_plus_collect = pd.read_sql_query(sql=t_plus_collect_sql, con=engine_new_transaction)

        excel_file = pd.ExcelWriter(os.path.join(self.dir_path, u'渤海催回和代偿-{}.xlsx'.format(self.start.strftime('%Y%m'))))
        df_loan.to_excel(excel_file, '放款', index=None)
        df_behalf.to_excel(excel_file, 'T-代偿', index=None)
        df_collect.to_excel(excel_file, 'T-催回', index=None)
        df_head_repay.to_excel(excel_file, 'T+1-提前还款', index=None)
        df_t_plus_behalf.to_excel(excel_file, 'T+1-代偿', index=None)
        df_t_plus_collect.to_excel(excel_file, 'T+1-催回', index=None)
        excel_file.save()


if __name__ == '__main__':
    collection_behalf(False).collection_behalf_details()
    print('======================bohai collection_behalf done===================================')
