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

from sqlalchemy import create_engine

reload(sys)
sys.setdefaultencoding('utf8')


'''
1、同利息有关系，需要获取每期的利息
'''

engine_audit = create_engine(
    'mysql+mysqldb://yulong_rw:TouBStYwN8wkdxVt@172.16.3.201:3306/baitiao_audit?charset=utf8',
    echo=True)

engine_offline = create_engine(
    'mysql+mysqldb://linfang_ol_r:pYZrv6DDkBCOIzX3@172.16.1.135:6033/offline?charset=utf8',
    echo=True)

engine_xyqb = create_engine(
'mysql+mysqldb://linfang_ol_r:pYZrv6DDkBCOIzX3@172.16.1.135:6033/xyqb?charset=utf8',
    echo=True
)

'线下白条'
def get_offline_rate():
    read_off_merchantid='''select id ,monthly_repaid_args FROM merchant'''
    df_off=pd.read_sql(read_off_merchantid,con=engine_offline)
    list_off=[]
    for index,row in df_off.iterrows():
        merchantId=row['id']
        json_args=json.loads(row['monthly_repaid_args'])
        for (k, v) in json_args.items():
            k=k.replace('INS_','')
            list_off.append([merchantId,k,v])
    df=pd.DataFrame(list_off,columns=['off_merchant_id','contract_term','rate'])
    return df

'线下白条'
def cal_off_rate():
    '线下利率更新'
    read_bt_1_sql = '''
    SELECT id,`contract_term`,`merchantId`,order_no FROM `baitiao_order` where is_online=0 and contract_term is not NULL
    '''
    read_bt_2_sql = '''
    select id order_no,merchant_id off_merchant_id from offline_order
    '''
    df_off_rate = get_offline_rate()
    df_off_rate['off_merchant_id'] = df_off_rate['off_merchant_id'].astype(int)
    df_off_rate['contract_term'] = df_off_rate['contract_term'].astype(int)

    df_1 = pd.read_sql(read_bt_1_sql, con=engine_audit)
    df_1['merchantId'] = df_1['merchantId'].astype(int)
    df_1['contract_term'] = df_1['contract_term'].astype(int)
    df_1['order_no'] = df_1['order_no'].astype(str)
    df_2 = pd.read_sql(read_bt_2_sql, con=engine_offline)
    df_2['order_no'] = df_2['order_no'].astype(str)
    '获取offline 库的merchant_id'
    df_1 = pd.merge(df_1, df_2, on='order_no', how='left')
    '获取利率'
    # df_1.fillna(0,inplace=True)
    df_1['off_merchant_id'] = df_1['off_merchant_id'].astype(int)
    df_1 = pd.merge(df_1, df_off_rate, on=['off_merchant_id', 'contract_term'], how='left')
    df_1.to_csv('E:/off_rate.csv')
# cal_off_rate()

'账单白条,注意查询xyqb库的权限，批量查询有限制'
def cal_bill_rate():
    # read_1_sql=''' SELECT DISTINCT order_no FROM new_transaction.`user_bt_repayment_plan` WHERE sys_tag ='XYQB_BILL_BT' '''
    # df_1=pd.read_sql(read_1_sql,con=engine_audit)
    # order_nos=tuple(df_1['order_no'].astype(str))
    # read_2_sql=''' SELECT order_no,rate FROM `baitiao_bill_repayment_plan` WHERE order_no IN %s '''
    # df_2=pd.read_sql(read_2_sql % str(order_nos),con=engine_xyqb)
    # print len(df_2)
    # df_2.drop_duplicates(['order_no'],inplace=True)
    df_2=pd.read_csv('E:/bill_rate.csv')
    df_2.drop_duplicates(['order_no'],inplace=True)
    df_2.to_csv('E:/bill_rate1.csv')


'计算线上利率'
def cal_online_rate():
    read_1_sql=''' SELECT order_no ,SUM(`principle`) prin,SUM(`interest`) inst FROM new_transaction.`user_bt_repayment_plan` WHERE order_no='253102937' GROUP BY `order_no` '''
    df_1=pd.read_sql(read_1_sql,con=engine_audit)
    df_1['rate'] = df_1.apply(lambda x:np.round(x['inst']/x['prin'],6),axis=1)
    df_1.to_csv('E:/online_rate.csv')

cal_online_rate()