#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Dec  3 11:14:31 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 get_configure_price():
    #获取配件价格
    try:
        conn = pymssql.connect(host='123.56.115.207', user='zgcindex', password='jiayou202006', database='ZI_NEW',autocommit=True)
        cursor = conn.cursor()
        #cursor.execute("select * from vw_electricity_source_price where ProductCode in "+ code_list +" and periods = (select top 1 periods from vw_entry_source_price order by periods desc)")
        cursor.execute("select category_code,category_name,part,detail,price from configure_price")
        configure_price = pd.DataFrame([v for v in cursor.fetchall()],columns=[tuple[0] for tuple in cursor.description])
        configure_price['price'] = pd.to_numeric(configure_price['price'])
            
        cursor.close()
        conn.close()
        
        return configure_price
    except:
        print('连接失败，重新连接')
        return get_configure_price()


def check_configure_price(category,path):
    
    if category not in ['笔记本','台式机','一体电脑','工作站']:
        print("该类别无配件，无需校验配件价格")
        return "该类别无配件，无需校验配件价格"
    
    params_list = get_category_params_list(category)
    
    conn = pymssql.connect(host='123.56.115.207', user='zgcindex', password='jiayou202006', database='ZI_NEW',autocommit=True)
    cursor = conn.cursor()
    
    cursor.execute(f"select name,id from p_category where name in ('笔记本','台式机','一体电脑','工作站')")
    category_df = pd.DataFrame([v for v in cursor.fetchall()],columns=[tuple[0] for tuple in cursor.description])
    category_dict = dict(zip(category_df['name'].tolist(),category_df['id'].tolist()))
    
    date = str(datetime.datetime.now()).split(" ")[0]
    
    category_list = [category]
    configure_price_df = get_configure_price()
    
    cat_params_df = pd.read_excel(path)
    try:
        cat_params_df['驳回原因'] = cat_params_df['驳回原因'].apply(lambda x:str(x))
    except:
        cat_params_df['驳回原因'] = ['nan' for i in range(len(cat_params_df))]
    cat_configure_price_df = configure_price_df[configure_price_df['category_name'] == category]
    
    process_index = 0
    index_ = Index()
    
    res_list = []
    for index,row in cat_params_df.iterrows():
        
        try:
            print(index_(process_index,len(cat_params_df)-1), end='%')
        except:
            print(index_(process_index,1), end='%')
        process_index+=1

        remark = row['驳回原因']
        if remark != 'nan':
            continue

        
        for params in params_list:
            value = row[params]
            
            if params not in list(cat_configure_price_df['part']):
                continue
            else:
                try:
                    current_price = cat_configure_price_df[(cat_configure_price_df['part'] == params) & (cat_configure_price_df['detail'] == value)]['price'].tolist()[0]
                except:
                    mark = "无该配件价格：" + category + " " + params + " " + value
                    if mark in res_list:
                        continue
                    else:
                        res_list.append(mark)
                        category_code = category_dict[category]
                        cursor.execute(f"insert into configure_price (category_code,part,detail,create_date,category_name) \
                                          values ('{category_code}','{params}','{value}','{date}','{category}')")
    if res_list:
        print("请补充配件价格")
        print(res_list)
    else:
        print("配件价格齐全，无需补充")
    
    return res_list



#校验通过的数据需要进行配件价格校验
category_name = '笔记本'
checked_path = "/Users/rico/Downloads/激光打印机参数补充回导.xlsx"
check_configure_price(category_name,checked_path)

