# -*- coding: utf-8 -*-
import datetime
import sys
import multiprocessing as mtp
from itertools import product

import pandas as pd
from sqlalchemy import create_engine
from dateutil.relativedelta import relativedelta

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


# path = 'E:/hk/bt/'
# 注意修改数据源
engine_new_transaction = create_engine(
    'mysql+mysqldb://internal_r:ArbNgtvlJzZHXsEu@172.16.3.201:3306/all_back_0731?charset=utf8',
    echo=True)

read_feiquna_sql='''

SELECT d,SUM(jine) FROM 
(SELECT CONCAT(m.merchant_name,t4.order_no) as d,
SUM(t1.principle-t1.mitigate_principle) as jine
FROM baitiao_repay_plan_repay_record_ref t1
JOIN offline_alipay_record t2 on t1.record_id = t2.id 
and t1.repay_channel = 13 and t2.transfer_time >='2017-01-01' AND t2.transfer_time<'2017-08-01'
join user_bt_repayment_plan t3 on t3.id = t1.plan_id 
join baitiao_order t4 on t4.ref_id = t3.ref_id and t4.is_active in (1,-2) and t4.loan_paid_at <'2017-01-01'
JOIN merchant m ON m.merchant_id=t4.merchantId
GROUP BY 1
UNION
SELECT  CONCAT(m.merchant_name,t4.order_no) as d,
SUM(t1.principle-t1.mitigate_principle) as jine
FROM  baitiao_repay_plan_repay_record_ref t1 
JOIN repay_record_online t2 on t1.record_id = t2.id 
and t1.repay_channel < 13 and t2.bill_time >= '2017-01-01' AND t2.bill_time<'2017-08-01'
join user_bt_repayment_plan t3 on t3.id = t1.plan_id 
join baitiao_order t4 on t4.ref_id = t3.ref_id and t4.is_active in (1,-2) and t4.loan_paid_at < '2017-01-01'
JOIN merchant m ON m.merchant_id=t4.merchantId
GROUP BY 1) as a 
GROUP BY 1
'''
df_feiquna=pd.read_sql(read_feiquna_sql,con=engine_new_transaction)
print df_feiquna.shape

ff_feiquna=pd.read_excel(u"C:\\Users\\dinghiguo\\Desktop\\未还本金_2016---非去哪儿最新.xlsx")
print ff_feiquna.shape
df_all=pd.merge(ff_feiquna,df_feiquna,how='left',left_on='new',right_on='d')
df_all=df_all.drop_duplicates([u'订单号'])
df_all.to_excel(u"C:\\Users\\dinghiguo\\Desktop\\最终版201707非去哪未还本金收回_new.xlsx", index=None)


