# -*- encoding: utf8 -*-
import sys
import os
import datetime,time
import numpy as np
import pandas as pd
from dateutil.relativedelta import relativedelta
from sqlalchemy import create_engine

'''
@author linfang
'''

engine_qunaer = create_engine('mysql+mysqldb://yulong:ohVU1nPITynSZwR2@172.16.3.201:3306/qunaer_new?charset=utf8', echo=False).connect()
engine_djy = create_engine('mysql+mysqldb://wanglinfang_data_r:uh90888n7y8ijk8886@192.168.4.6:8066/dujiangyan?charset=utf8', echo=False).connect()
# 同都江堰库比较还款差异
def djy_repay_diff(year,month):
    start_time = datetime.datetime(year, month, 1, 0, 0, 0)
    end_time = start_time + relativedelta(months=+1)
    sql_djy='''
     select repayment_no,repayment_term from qunar_repay_history where repay_request_time >= '%s' and repay_request_time < '%s'
    ''' % (start_time,end_time)
    df_djy=pd.read_sql(sql_djy,engine_djy)
    df_djy.ix[df_djy.repayment_term == 0,'repayment_term'] = 1
    sql_qunaer='''
    select id,repay_no,current_stage_no from repay_detail where repay_time >= '%s' and repay_time < '%s'
    ''' % (start_time,end_time)
    df=pd.read_sql(sql_qunaer,engine_qunaer)
    df_diff=pd.merge(df_djy,df,left_on='repayment_no',right_on='repay_no',how='outer')
    df_diff.fillna(0,inplace=True)
    df_diff['diff']=df_diff['repayment_term'] - df_diff['current_stage_no']
    return df_diff.ix[df_diff['diff'] != 0]

# 同都江堰库比较放款差异
def djy_pay_diff(year,month):
    start_time = datetime.datetime(year, month, 1, 0, 0, 0)
    end_time = start_time + relativedelta(months=+1)
    sql_djy = '''
    select loan_no,loan_amount,status
    from qunar_loanpay_history
    where loan_time >= '%s' and loan_time < '%s'
    ''' % (start_time,end_time)
    sql_q = '''
    select product_no,loan_amount,is_ptf from pay_detail where trans_time >= '%s' and trans_time < '%s'
    ''' % (start_time,end_time)
    df_djy=pd.read_sql(sql_djy,engine_djy)
    df_q = pd.read_sql(sql_q,engine_qunaer)
    df_new=pd.merge(df_djy,df_q,left_on='loan_no',right_on='product_no',how='outer')
    df_new.fillna(0,inplace=True)
    df_new['diff']=np.round(df_new['loan_amount_x'] - df_new['loan_amount_y'],2)
    df_new = df_new.ix[df_new['diff'] != 0]
    return df_new



def djy_refund_diff(year,month):
    start_time = datetime.datetime(year, month, 1, 0, 0, 0)
    end_time = start_time + relativedelta(months=+1)
    sql_djy = '''
        select loan_no,sum(refund_amount) refund_amount
        from qunar_refund_history
        where refund_time >= '%s' and refund_time < '%s'
        GROUP BY 1
        ''' % (start_time, end_time)
    sql_q = '''
        select product_no,sum(refund_amount) refund_amount from refund_detail where refund_time >= '%s' and refund_time < '%s'
        GROUP BY 1
        ''' % (start_time, end_time)
    df_djy = pd.read_sql(sql_djy, engine_djy)
    df_q = pd.read_sql(sql_q, engine_qunaer)
    df_new = pd.merge(df_djy, df_q, left_on='loan_no', right_on='product_no', how='outer')
    df_new.fillna(0, inplace=True)
    df_new['diff'] = np.round(df_new['refund_amount_x'] + df_new['refund_amount_y'], 2)
    df_new = df_new.ix[df_new['diff'] != 0]
    return df_new


def repay_diff(year,month):
    start_time = datetime.datetime(year, month, 1, 0, 0, 0)
    end_time = start_time + relativedelta(months=+1)

    sql_1='''
    select repay_no,repay_amount from repay_detail
    where repay_time >= '%s' AND repay_time < '%s'  
    ''' % (start_time,end_time)
    sql_2='''
    select repay_no,repay_amount from repayment_plan_2017
    where repay_time >= '%s' AND repay_time < '%s'
    ''' % (start_time,end_time)
    sql_3='''
    select repay_no,repay_amount from repayment_plan_2016
    where repay_time >= '%s' AND repay_time < '%s'
    ''' % (start_time,end_time)
    df_1=pd.read_sql(sql_1,engine_qunaer)
    df_2=pd.read_sql(sql_2,engine_qunaer)
    df_3=pd.read_sql(sql_3,engine_qunaer)
    df_4=pd.concat([df_2,df_3],ignore_index=True,axis=0)
    df_4_1=df_4.ix[df_4.repay_no.str.contains(',')]
    df_4_2=df_4.ix[~df_4.repay_no.str.contains(',')]
    df_4_2 = pd.merge(df_1, df_4_2, on='repay_no', how='inner')
    df_4_2['diff']=np.round(df_4_2['repay_amount_x']-df_4_2['repay_amount_y'],3)
    df_4_2=df_4_2.ix[df_4_2['diff'] != 0]
    print df_4_2
    print '------df_1----len ---before---',len(df_1)
    df_4_2 = df_4.ix[~df_4.repay_no.str.contains(',')]
    df_1=df_1.ix[~df_1.repay_no.isin(df_4_2.repay_no)]
    print '------df_1-df_4_2------',len(df_4_2),len(df_1)
    list1 = []
    for index,row in df_4_1.iterrows():
        tmp = row['repay_no']
        tmp = str(tmp).strip().split(',')
        tmp_amount = float(row['repay_amount'])
        amount=0
        for repay_no in tmp:
            list1.append(str(repay_no))
            amount+=df_1.ix[df_1.repay_no == str(repay_no)]['repay_amount'].sum()
        if round(tmp_amount - amount,2) != 0:
            print '--------有差异的---------',tmp
    print '-------df_4_2-----',list1.__len__()
    df_1 = df_1.ix[~df_1.repay_no.isin(list1)]
    print '-----after--df_4_2----',len(df_1)
    print df_1





if __name__ == '__main__':

    year = 2017
    month = 7
    # repay_diff(year,month)
    #同都江堰库比较放款差异
    # df = djy_pay_diff(year,month)
    # print df.ix[df['diff'] != 0].to_csv('E:/diff.csv')
    #退款差异比较
    # df=djy_refund_diff(year,month)
    # df.ix[df['diff'] != 0].to_csv('E:/diff.csv')
    #还款差异比较
    # df=djy_repay_diff(year,month)
    # df.to_csv('E:/diff.csv')

    #校验还款记录未钩稽上还款计划
    # df=check_repay_plan(year,month)

