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

reload(sys)
sys.setdefaultencoding("utf-8")
pd.options.mode.chained_assignment = None

'''
同步都江堰的deadline
'''

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()
path = 'E:/'

def status_sync(insert_db=False):
    sql_1='''
    select id,product_no,current_stage_no from repayment_plan_2017
    where status != 3 AND repay_time is NULL 
    '''
    sql_2='''
    update repayment_plan_2017 set status = 3 where id = %s
    '''
    sql_3='''
    select loan_no product_no,term_no current_stage_no,paid_status from qunar_repayment_plan
      where paid_status = 'CONVERSION' and loan_no in %s
    '''
    df_al=pd.read_sql(sql_1,engine_qunaer,chunksize=5000)
    for df in df_al:
        product_nos = df.product_no.astype(str).tolist()
        df_3=pd.read_sql(sql_3 % str(tuple(product_nos)).replace(',)',')'),engine_djy)
        df_3.product_no=df_3.product_no.astype(str)
        df_3.current_stage_no=df_3.current_stage_no.astype(int)
        df.product_no = df.product_no.astype(str)
        df.current_stage_no = df.current_stage_no.astype(int)
        df=pd.merge(df,df_3,on=['product_no','current_stage_no'],how='inner')
        df.to_csv(path+'diff_status.csv',mode='a')
        if insert_db & (len(df) > 0):
            print '-----update--CONVERSION----',len(df)
            df['id'] = df['id'].map('{:.0f}'.format)
            up_vals = df[['id']].values.tolist()
            engine_qunaer.execute(sql_2, up_vals)


def deadline_sync():
    sql_1 = '''
    select id,product_no,current_stage_no,deadline from repayment_plan_201703
    '''
    sql_3 = '''
    update repayment_plan_201703 set deadline=%s where id=%s
    '''
    sql_2 = '''
    select loan_no product_no,term_no current_stage_no,due_date from qunar_repayment_plan
        where loan_no in %s
    '''

    df_al = pd.read_sql(sql_1, engine_qunaer, chunksize=5000)
    i = 0
    for df in df_al:
        print '------update---deadline----', i
        i += 5000
        product_nos = df.product_no.astype(str).tolist()
        df_djy = pd.read_sql(sql_2 % str(tuple(product_nos)).replace(',)', ')'), engine_djy)
        df.product_no = df.product_no.astype(str)
        df.current_stage_no = df.current_stage_no.astype(int)
        df.deadline = pd.to_datetime(df.deadline).dt.date
        df_djy.product_no = df_djy.product_no.astype(str)
        df_djy.current_stage_no = df_djy.current_stage_no.astype(int)
        df_djy.due_date = pd.to_datetime(df_djy.due_date).dt.date
        df = pd.merge(df, df_djy, on=['product_no', 'current_stage_no'], how='left')
        df['days'] = df.apply(lambda x: (x.deadline - x.due_date).days, axis=1)
        df = df.ix[df['days'] != 0]
        if len(df) > 0:
            df['id'] = df['id'].map('{:.0f}'.format)
            up_vals = df[['due_date', 'id']].values.tolist()
            engine_qunaer.execute(sql_3, up_vals)

status_sync()