# encoding:utf8
import sys

import pandas as pd
from sqlalchemy import create_engine

pd.options.mode.chained_assignment = None

from api import db_connect

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

'''
@author: 王博
'''

# 核查是否有退款订单
# 文件的存储路径，按需修改
# file_path = "E:/quantgroup/3c/check_5_4/"

# files = os.listdir(file_path)

engine_xyqb = create_engine('mysql+mysqldb://syzhu_data_r:ulk0989742097y43@192.168.4.6:8066/xyqb?charset=utf8',echo=True)
engine_merchant = create_engine('mysql+mysqldb://bowang:in78u6ytgbhj56r@192.168.4.6:8066/merchant?charset=utf8',echo=True)
con = db_connect.db_connect('xyqb', 'xyqb').get_conn()

refund_sql = """
 select t.order_no from baitiao_order t where t.order_no IN %s AND t.status = 5 ;
"""

merchant_sql = """
SELECT supplier_amount , mall_order_no order_no FROM supplier_order WHERE mall_order_no IN %s 
"""


def check_refund():
    df = pd.read_excel(u'E:/quantgroup/3c/3c5月3至9日.xlsx')
    df.rename(columns={u'订单编号': 'order_no'}, inplace=True)
    df.rename(columns={u'售货价': 'amount'}, inplace=True)
    df['order_no'] = df['order_no'].astype(str)
    df['amount'] = df['amount'].astype(float)
    order_no = df['order_no'].tolist()
    df_tuidan = pd.read_sql(refund_sql % (str(tuple(order_no)),), engine_xyqb)
    if len(df_tuidan) > 0:
        df_tuidan.to_excel(u'E:/quantgroup/3c/退单.xlsx')
    df_amount = pd.read_sql(merchant_sql % (str(tuple(order_no)),), engine_merchant)
    df_amount['supplier_amount'] = df_amount['supplier_amount'].astype(float)
    df = pd.merge(df, df_amount, on='order_no')
    df['different'] = df['supplier_amount'] - df['amount']
    df_diff = df[df.different != 0]
    if len(df_diff) > 0:
        df_diff.to_excel(u'E:/quantgroup/3c/金额不同.xlsx')

check_refund()
# for f in files:
#     print file_path + f
#     pd_3c_df = pd.read_csv(file_path + f, header=0)
#     pd_refund_df = pd.DataFrame()
#
#     order_no_3c_series = pd_3c_df["order_no"]
#     order_no_str = str(tuple(order_no_3c_series[~order_no_3c_series.isnull()]))
#     refund_sql_arg = refund_sql % (order_no_str,)
#     print refund_sql_arg
#     pd_refund_sql_gen = pd.read_sql(sql=refund_sql_arg, con=con, chunksize=1000)
#     pd_refund_df = pd.DataFrame()
#     for value in pd_refund_sql_gen:
#         pd_refund_df = pd_refund_df.append(value, ignore_index=True)
#
#     pd_refund_df.to_csv(file_path + 'refund_order_no_%s.csv' % f)
