# -*- encoding: utf8 -*-

"""
目标：
    现金贷还款表按还款月统计汇总
数据库：
    audit.loan_manifest
    根据不同时段的需求，选取不同阶段的备份数据库
字段名：
    还款年，还款月，资金方，收款账户，还款总额，实还本金，实还利息，实还服务费，实还罚息，其他收益
注意：

"""
import os

import pandas as pd

from db_con.db_connect import sql_engine

# ----------------------------------------------
pd.options.mode.chained_assignment = None
file_path = u'E:/审计出表/现金贷'
file_name = u'现金贷还款表-汇总表'
if not os.path.exists(file_path):
    os.makedirs(file_path)
mysql = sql_engine('audit', 'temp').get_engine()
sql = """
SELECT
  year(xrprrrrd.repaid_at)                               还款年,
  month(xrprrrrd.repaid_at)                              还款月,
  urp.fund_code,
  xrprrr.repay_channel,
  sum(xrprrr.ref_amount)                                 还款总额,
  sum(xrprrr.principle - xrprrr.mitigate_principle)      实还本金,
  sum(xrprrr.interest - xrprrr.mitigate_interest)        实还利息,
  sum(xrprrr.service_fee - xrprrr.mitigate_service_fee)  实还服务费,
  sum(xrprrr.punish - xrprrr.mitigate_collection_relief) 实还罚息,
  sum(xrprrr.remain_income)                              其他收益
FROM new_transaction.xjd_repay_plan_repay_record_ref xrprrr
  JOIN new_transaction.xjd_repay_plan_repay_record_ref_repay_date xrprrrrd ON xrprrrrd.xjd_ref_id = xrprrr.id
  JOIN new_transaction.user_repayment_plan urp ON urp.id = xrprrr.plan_id
GROUP BY 1, 2, 3, 4;
"""
sql_dunshou = """
SELECT
  year(rro.bill_time)  还款年,
  month(rro.bill_time) 还款月,
  fc.name              资金方,
  rc.approach_name     收款账户,
  sum(xdpr.ref_amount) 实还趸收服务费
FROM
  new_transaction.xjd_dunjiao_plan_ref xdpr
  JOIN new_transaction.xjd_dunjiao_plan xdp
    ON xdpr.plan_id = xdp.id
  JOIN audit.loan_manifest lm
    ON xdp.ref_id = lm.ref_id
  JOIN new_transaction.repay_record_online rro
    ON xdpr.record_id = rro.id
  JOIN new_transaction.funding_corp fc
    ON fc.id = lm.funding_code
  JOIN new_transaction.repay_channel rc ON rc.id = rro.pay_approach
GROUP BY 1, 2, 3, 4;
"""
sql_fund_code = """
SELECT
  funding_code fund_code,
  name         资金方
FROM audit.funding_corp;
"""
sql_repay_channel = """
SELECT
  id            repay_channel,
  approach_name 收款账户
FROM new_transaction.repay_channel;
"""
# ----------------------------------------------
df = pd.read_sql(sql=sql, con=mysql)
df_dunshou = pd.read_sql(sql=sql_dunshou, con=mysql)
df_fund = pd.read_sql(sql=sql_fund_code, con=mysql)
df_channel = pd.read_sql(sql=sql_repay_channel, con=mysql)
df = df.merge(df_fund, how='left', on='fund_code').merge(df_channel, on='repay_channel', how='left')
df = df.merge(df_dunshou, on=[u'还款年', u'还款月', u'资金方', u'收款账户'], how='left')
df = df[[u'还款年', u'还款月', u'资金方', u'收款账户', u'还款总额', u'实还本金', u'实还利息', u'实还服务费', u'实还罚息', u'其他收益',
         u'实还趸收服务费']]
df.to_csv(os.path.join(file_path, '%s.csv' % file_name), index=None, encoding='utf8')
df.to_excel(os.path.join(file_path, '%s.xlsx' % file_name), index=None)
