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

# 广达-账户不可用资金统计#

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/'
xyqb_conn = sql_engine('xyqb', 'xyqb').get_engine()
payment_center_conn = sql_engine('paycenter', 'payment_center').get_engine()

query_xyqb_sql = """
select rr.actual_repayment,rr.pay_center_order_no from repayment_record rr 
inner join loan_application_manifest_history lamh on lamh.loan_application_history_id=rr.loan_application_history_id and lamh.funding_corp_id=480 and lamh.transaction_status=2 
and lamh.loan_paid_at > '2018-01-03'  
where rr.repayment_status=3 and rr.repayment_received_at >= {} and repayment_received_at < {}
"""

query_paycenter_sql = """
select merchant_repay_order_no as pay_center_order_no ,amount from repay_order where repay_status=3 and merchant_id=3 and merchant_repay_order_no in {}
"""


class fund_account():
    def __init__(self):
        self.last_day = datetime.date.today() + datetime.timedelta(-1)
        self.today = datetime.date.today()
        self.tomorrow = datetime.date.today() + datetime.timedelta(1)

    def account(self):
        #begin_time = self.last_day.strftime("'%Y-%m-%d'")
        #end_time = self.today.strftime("'%Y-%m-%d'")

        #begin_time = "'2019-08-20'"
        #end_time = "'2019-08-21'"

        begin_time = self.today.strftime("'%Y-%m-%d'")
        end_time = self.tomorrow.strftime("'%Y-%m-%d'")

        df_xyqb = pd.read_sql(sql=query_xyqb_sql.format(begin_time,end_time), con=xyqb_conn)
        df_xyqb.pay_center_order_no = df_xyqb.pay_center_order_no.astype(str)

        df_repay_order = pd.read_sql(
            sql=query_paycenter_sql.format(str(tuple(df_xyqb.pay_center_order_no)).replace(',)', ')')),
            con=payment_center_conn)

        df_repay_all = pd.merge(df_xyqb, df_repay_order, how='inner', on='pay_center_order_no')
        sumAmount = np.round(df_repay_all['amount'].sum(),2)

        #table = {'统计日期': [self.today.strftime("%Y-%m-%d")], '金额': [sumAmount]}
        table = {'统计日期': [begin_time], '金额': [sumAmount]}
        df_table = pd.DataFrame(data=table)
        #df_table.to_excel(os.path.join(path, '广达-众信利民代收的客户还款-不可用金额-{}.xlsx'.format(self.last_day.strftime("%Y-%m-%d"))), index=None)
        df_table.to_excel(os.path.join(path, '广达-众信利民代收的客户还款-不可用金额-{}.xlsx'.format(begin_time)), index=None)
        print df_table


if __name__ == '__main__':
    fund_account().account()
    print('======================fund_account done===================================')
