# -*- coding:utf-8 -*-
# Author: Perry_Zhu

import sys
import datetime
import pandas as pd
import numpy as np
from itertools import product
from sqlalchemy import create_engine
import multiprocessing as mtp
from dateutil.relativedelta import relativedelta

reload(sys)
sys.setdefaultencoding("utf-8")
pd.options.mode.chained_assignment = None
engine_new_transaction = create_engine(
    'mysql+mysqldb://yulong:ohVU1nPITynSZwR2@172.16.3.201:3306/all_back_0630?charset=utf8', echo=False).connect()

path = u'E:/数据汇总/白条/去哪儿/放款/'

# 放款计划
sql_pay = '''
select t1.product_no ,t1.loan_amount
from qunaer_new.pay_detail t1
JOIN qunaer_new.repayment_plan_2016_201706 t2 ON t1.product_no=t2.product_no
WHERE
	t1.STATUS = 1
AND t2.`status`!=3
and  t1.trans_time >= '2016-08-01' and t1.trans_time < '2016-09-01'
GROUP BY 1
'''
sql_plan = '''
SELECT
	t2.product_no,
	sum(t2.principle) principle
from qunaer_new.repayment_plan_2016_201706 t2 
WHERE
t2.status!=3
AND t2.product_no in %s
	GROUP  BY 1
'''
sql_refund = '''
select t1.product_no,sum(t1.refund_amount) loan_amount
from qunaer_new.refund_detail t1 
where t1.refund_status = 1 and t1.product_no in %s
GROUP  BY  1
'''


def loan_info():
    df_pay = pd.read_sql(sql_pay, engine_new_transaction)
    df_pay['product_no'] = df_pay['product_no'].astype(str)
    product_no_list = df_pay['product_no'].tolist()
    df_refund = pd.read_sql(sql_refund % str(tuple(product_no_list)).replace(',)', ')'), engine_new_transaction)
    df_out = pd.concat([df_pay, df_refund], axis=0, ignore_index=True)
    df_pay = df_out.groupby(['product_no'])['loan_amount'].agg(['sum']).reset_index().rename(
        columns={'sum': 'loan_amount_sum'})
    df_plan = pd.read_sql(sql_plan % str(tuple(product_no_list)).replace(',)', ')'), engine_new_transaction)
    df_plan['product_no'] = df_plan['product_no'].astype(str)
    df_t = pd.merge(df_pay, df_plan, on=['product_no'], how='left')
    df_t['diff'] = df_t['principle'] - df_t['loan_amount_sum']
    df_2 = df_t.ix[df_t['diff'] != 0]
    if len(df_2) > 0:
        df_2.to_csv(path + u'去哪儿放款2016-08差异表.csv', index=None, encoding='gbk')


loan_info()
