#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Dec  3 10:44:20 2021

@author: rico
"""
import os
import sys
sys.path.append(os.path.dirname(os.getcwd()))
from ESCore.ES import ES_Client
import datetime
import pandas as pd
import pymssql
import pymysql
from public import zgc_api,Index
from SimilarCharactor.string_similarity import similarity_cn,similarity_en



#获取指定类别的参数项
def get_category_params_list(category_name):

    conn_zi_new = pymssql.connect(host='123.56.115.207', user='zgcprice3311',password='zgcprice20200628',database= 'ZI_NEW',autocommit=True)
    cursor_zi_new = conn_zi_new.cursor()
    
    cursor_zi_new.execute(f"select subtitle,identy from vw_property where name = '{category_name}' and subtitle != '产品型号'")
    db_params = pd.DataFrame(cursor_zi_new.fetchall(), columns=[tuple[0] for tuple in cursor_zi_new.description])
    db_params['require_param'] = db_params['identy'].apply(lambda x: x[0])
    db_params['standard_param'] = db_params['identy'].apply(lambda x: x[2])
    db_params = db_params[(db_params['standard_param'] != '0') & (db_params['require_param'] != '0')]
    db_params['subtitle'] = db_params['subtitle'].apply(lambda x: x.strip())
    params_list = db_params['subtitle'].tolist()
    
    return params_list
    



def export_params_data(es,filter_col,filter_value,category_name):
    
    #导出指定项目数据
    if filter_col == 'DATA_BATCH':
        df = es.SearchByCondition(filter_col,filter_value)
    else:
        filter_value = filter_value[0]
        df = es.SearchAimAllByCondition(filter_col,filter_value)
    #df = df[df['DATA_BATCH'] == "202111160940430001"]
    #导出补参环节数据
    if category_name in ['笔记本','台式机','一体电脑','复印纸','工作站']:
        FLOW_NODE_STATUS = "SYS_GET_PARAMS_FAILD_REDUCTIVE"
        COL_LIST = ['DOC_ID','SOURCE_P_NAME','FINISH_P_LASTCATEGORY_NAME','FINISH_P_BRAND_NAME','SOURCE_P_PARAMS','SOURCE_P_URL']
    else:
        FLOW_NODE_STATUS = "SYS_GET_PARAMS_FAILD_NONREDUCTIVE"
        COL_LIST = ['DOC_ID','SOURCE_P_NAME','FINISH_P_LASTCATEGORY_NAME','FINISH_P_BRAND_NAME','FINISH_P_MODEL','SOURCE_P_PARAMS','SOURCE_P_URL']

    cat_df = df[(df['FINISH_P_LASTCATEGORY_NAME'] == category_name) & (df['FLOW_NODE_STATUS'] == FLOW_NODE_STATUS) & (df['FLOW_FINISH_STATUS'] == 'N')]
    
    params_list = get_category_params_list(category_name)
    
    for param in params_list:
        param_var = '_' + ''.join(param.split()).replace('（','').replace('）','').replace('/','').replace('(','').replace(')','').replace('+','').replace('-','').replace('*','').replace('.','')
        exec('%s_list=[]'%param_var)
        
    for index,row in cat_df.iterrows():
        
        #params_dict = eval(row['DEAL_UNSTD_PARAMS_DICT'])#取第一行的数据
        params_dict = eval(row['DEAL_STD_PARAMS_DICT'])

        for param in params_list:
            param_var = '_' + ''.join(param.split()).replace('（','').replace('）','').replace('/','').replace('(','').replace(')','').replace('+','').replace('-','').replace('*','').replace('.','')
            exec("%s_list.append('%s')"%(param_var,params_dict[param].replace("\\","需人工补充")))
                
    cat_df = cat_df[COL_LIST]#取指定的字段信息
    for param in params_list:
        param_var = '_' + ''.join(param.split()).replace('（','').replace('）','').replace('/','').replace('(','').replace(')','').replace('+','').replace('-','').replace('*','').replace('.','')
        exec("cat_df['%s']=%s_list"%(param,param_var))
    
    #结果导出excel
    date = str(datetime.datetime.now()).split(" ")[0]
    if "/" in category_name:
        category_name = category_name.replace("/","_")
    cat_df.to_excel(f"{category_name}参数补充{date}.xlsx")




#创建ES客户端
host = "http://123.56.114.138:9200/"
index_name = "model_params_test"
es = ES_Client(host,index_name)


#导出单个类补参数据
filter_col = "DATA_PROJECT_NAME"  # DATA_PROJECT_NAME 项目名称 / DATA_BATCH 批次号
filter_value = ['徽采商城数据入库']  # 项目名称/批次号  eg. 全渠道数据入库/202111171554120001/徽采商城数据入库
category_name = '笔记本'


#导出数据
export_params_data(es,filter_col,filter_value,category_name)



#导出多个类补参数据
#category_name_list = ['空调','摄像机','多功能一体机','U盘','移动硬盘','硒鼓/墨粉']
#导出数据
#for category_name in category_name_list:
    
#    export_params_data(es,filter_col,filter_value,category_name)

