# -*- coding: utf-8 -*-

import os
import sys
import datetime
import numpy as np
import pandas as pd

sys.path.append('../../../finance_out_table')
from db_con.db_connect import sql_engine

conn_w = sql_engine('audit_w', 'audit', echo=True).get_engine()
engine_xyqb = sql_engine('xyqb', 'xyqb', True).get_engine()

query_audit_loan = """
select loan_id from audit.loan_manifest where loan_paid_at >= '2018-04-01' and loan_paid_at<'2018-08-15' and contract_created_at is null order by loan_paid_at;
"""

query_xyqb_contrace = """
SELECT loan_application_history_id 'loan_id',created_at 'contract_created_at' 
FROM contract WHERE loan_application_history_id in {}
"""

sql_update = """
    update audit.loan_manifest set contract_created_at = %s where loan_id = %s;
"""

if __name__ == '__main__':
    df_loan = pd.read_sql(sql=query_audit_loan, con=conn_w)
    df_loan.loan_id = df_loan.loan_id.astype(str)
    loan_ids = df_loan.loan_id.tolist()
    df_xyqb_loan_contract = pd.read_sql(sql=query_xyqb_contrace.format(str(tuple(loan_ids)).replace(',)', ')')),
                                        con=engine_xyqb)
    df_xyqb_loan_contract.loan_id = df_xyqb_loan_contract.loan_id.astype(str)
    df_audit_loan_manifest = pd.merge(df_loan, df_xyqb_loan_contract, on='loan_id', how='left')
    df_not_null = df_audit_loan_manifest.loc[~df_audit_loan_manifest['contract_created_at'].isnull()]
    conn_w.execute(sql_update, df_not_null[['contract_created_at', 'loan_id']].values.tolist())
