# -*- coding: utf-8 -*-
import sys
import pandas as pd
import datetime
import os

path = '/home/quant_group/vpants/finance/table/'
sys.path.append('../../../finance_out_table')
from db_con.db_connect import sql_engine

engine_audit = sql_engine('audit_w', 'audit').get_engine()
engine_xyqb = sql_engine('xyqb', 'xyqb').get_engine()

sql_xyqb_loan_manifest = """
SELECT
	loan_id,
	ref_id 
FROM
	loan_manifest lm
WHERE
	lm.loan_paid_at >= '{0}' 
	and lm.loan_paid_at < '{1}'
	and lm.funding_code = 590
"""

sql_xjd_dunjiao_info = """
SELECT
	loan_id,
    amount qg_one_time_service_fee,
    pay_status repay_status,
    pay_finished_at xyqb_repaid_at
FROM
	loan_extra_fee 
WHERE
	loan_id in {}
"""

sql_xjd_dunjiao_info_real = """
select loan_id, amount, pay_finished_at from loan_extra_fee where product_type = 3 and pay_finished_at >= '{0}' and pay_finished_at < '{1}';
"""

sql_audit_query_loan_id = """
select loan_id from xjd_zhongan_dunjiao_plan where loan_id in {};
"""

sql_dunjiao_exists = """SELECT id,loan_id FROM xjd_zhongan_dunjiao_plan WHERE loan_id in {} and repay_status = 3"""

sql_dunjiao_update = """
update xjd_zhongan_dunjiao_plan set real_qg_one_time_service_fee = %s, xyqb_repaid_at = %s where loan_id = %s'
"""

sql_new_summary = """
SELECT 
  year(loan.loan_paid_at) 放款年,
  month(loan.loan_paid_at) 放款月,
  f.name 资金方,
  loan.class 风险等级,
  sum(loan.contract_loan_amount) 放款金额,
  sum(d.qg_one_time_service_fee) 保证险应收金额,
  sum(d.real_qg_one_time_service_fee) 保证险实收金额,
  sum(d.qg_one_time_service_fee) - sum(d.real_qg_one_time_service_fee) 待还保证金
FROM
  audit.loan_manifest loan 
  JOIN basic.funding_corp f 
    ON f.funding_code = loan.funding_code 
  JOIN audit.xjd_zhongan_dunjiao_plan d on loan.ref_id = d.ref_id
  AND loan.loan_paid_at >= '{0}' 
    AND loan.loan_paid_at < '{1}' 
    AND loan.funding_code = 590
GROUP BY 1, 2, 3, 4 ;
"""

sql_new_details = """
SELECT 
  f.name 资金方,
  loan.loan_id,
  loan.contract_no 贷款合同号,
  date(loan.loan_paid_at) 放款日期,
  loan.contract_loan_amount 放款金额,
  loan.contract_term 总期数,
  d.qg_one_time_service_fee 保证险应收金额,
  loan.monthly_interest_rate 月利率,
  loan.class 风险等级
FROM
  audit.loan_manifest loan 
  JOIN basic.funding_corp f 
    ON f.funding_code = loan.funding_code
  JOIN audit.xjd_zhongan_dunjiao_plan d on loan.ref_id = d.ref_id
  where loan.loan_paid_at >= '{0}' 
    AND loan.loan_paid_at < '{1}'
     AND loan.funding_code = 590
"""

sql_dun_details = """
SELECT 
  year(loan.loan_paid_at) 放款年,
  month(loan.loan_paid_at) 放款月,
  f.name 资金方,
  sum(loan.contract_loan_amount) 放款金额,
  sum(loan.contract_loan_amount)*0.01 QG服务费金额1趸收
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 = 590
GROUP BY 1, 2, 3 
"""


class zhongan_loan():
    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 fetch_zhongan_loan_manifest(self, start, end):
        print('--------------开始{}的众安保证金数据录入----------------'.format(start))
        """根据时间查询放款"""
        df_loan = pd.read_sql(sql=sql_xyqb_loan_manifest.format(start, end), con=engine_audit)
        if len(df_loan) <= 0:
            return
        df_loan.loan_id = df_loan.loan_id.astype(str)
        loan_ids = df_loan.loan_id.tolist()
        """查保证金已经存在的loan"""
        df_audit_exist_loan = pd.read_sql(sql=sql_audit_query_loan_id.format(str(tuple(loan_ids)).replace(',)', ')')),
                                          con=engine_audit)
        """去掉已经存在的"""
        if len(df_audit_exist_loan) > 0:
            exist_loan_id_list = df_audit_exist_loan.loan_id.tolist()
            print("存在 exist loan_id: {}".format(str(exist_loan_id_list)))
            df_loan = df_loan.loc[~df_loan.loan_id.isin(df_audit_exist_loan.loan_id)]
            if len(df_loan) <= 0:
                return
        loan_ids = df_loan.loan_id.tolist()
        df_loan_dunjiao = pd.read_sql(sql=sql_xjd_dunjiao_info.format(str(tuple(loan_ids)).replace(',)', ')')),
                                      con=engine_xyqb)

        df_loan_dunjiao.loan_id = df_loan_dunjiao.loan_id.astype(str)

        df_dunjiao = pd.merge(df_loan, df_loan_dunjiao, how='inner', on='loan_id')
        df_dunjiao['real_qg_one_time_service_fee'] = 0
        df_dunjiao.loc[df_dunjiao['repay_status'] == 3, 'real_qg_one_time_service_fee'] = df_dunjiao[
            'qg_one_time_service_fee']

        if not self.is_mock:
            df_dunjiao.to_sql(name='xjd_zhongan_dunjiao_plan', con=engine_audit, if_exists='append', index=None,
                              chunksize=10000)
        print('----------------{}保证金录入完毕------------------'.format(start))

    def update_exists_dunjiao(self, start, end):
        print('--------------开始{}的更新保证金----------------'.format(start))
        df_dunjiao = pd.read_sql(sql=sql_xjd_dunjiao_info_real.format(start, end), con=engine_xyqb)
        if len(df_dunjiao) <= 0:
            return
        df_dunjiao.loan_id = df_dunjiao.loan_id.astype(str)
        loan_ids = tuple(df_dunjiao.loan_id)
        df_exists = pd.read_sql(sql=sql_dunjiao_exists.format(str(loan_ids).replace(',)', ')')), con=engine_audit)
        df_dunjiao = df_dunjiao.loc[~df_dunjiao.loan_id.isin(df_exists.loan_id)]
        if len(df_dunjiao) <= 0:
            print('---没有需要更新的数据---')
            return
        df_dunjiao.pay_finished_at = df_dunjiao.pay_finished_at.astype(str)
        if not self.is_mock:
            engine_audit.execute(sql_dunjiao_update,
                                 df_dunjiao[['amount', 'pay_finished_at', 'loan_id']].values.tolist())
        print('--------------结束{}更新保证金----------------'.format(start))

    def zhongan_loan_detail(self):
        # 准备数据
        if not self.is_mock:
            print('zhongan loan fetch data')
            self.fetch_zhongan_loan_manifest(self.start, self.end)
            self.update_exists_dunjiao(self.start, self.end)

        # 出表
        df = pd.read_sql(sql=sql_new_summary.format(self.start, self.end), con=engine_audit)
        df.to_excel(os.path.join(self.dir_path, u'众安-放款汇总表-{}.xlsx'.format(self.start.strftime('%Y%m'))),
                    index=None)

        df = pd.read_sql(sql=sql_new_details.format(self.start, self.end), con=engine_audit)
        df.to_excel(os.path.join(self.dir_path, u'众安-放款明细表-{}.xlsx'.format(self.start.strftime('%Y%m'))),
                    index=None)

        df = pd.read_sql(sql=sql_dun_details.format(self.start, self.end), con=engine_audit)
        df.to_excel(os.path.join(self.dir_path, u'众安-趸收表-{}.xlsx'.format(self.start.strftime('%Y%m'))),
                    index=None)


if __name__ == '__main__':
    zhongan_loan(False).zhongan_loan_detail()
    print('======================zhongan_loan done===================================')
