#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 25 10:53:59 2021

@author: rico
"""

import pymssql
import pandas as pd
from public import Index
import uuid
import datetime

def transform_simplevalue(simple_subtitle_list,shujuzidiandf,categoryname,subtitle,stdvalue):
    
    stdvalue = stdvalue.strip()
    
    #simple_subtitle_list = ['CPU型号','显存容量','操作系统','双面器','双面输稿器','网络打印','标配外服务及配件','标配外耗材','镜头描述','碎纸效果','产品尺寸','分辨率','是否含壁挂架','是否含底座','CPU','内存','硬盘','尺寸','容量','最大读取速度','颜色','最大容积L','总容积L','类别']
    if subtitle not in simple_subtitle_list:
        return stdvalue
    
    simplevalue_list = list(set(shujuzidiandf[(shujuzidiandf['categoryname'] == categoryname) & (shujuzidiandf['subtitle'] == subtitle) & (shujuzidiandf['stdvalue'] == stdvalue)]['simplevalue'].tolist()))
    
    if len(simplevalue_list) == 0:
        print(f"非法值，不存在数据字典中。{subtitle},{stdvalue}")
        #add_shujuzidian(cursor_zi_new,categoryname,subtitle,stdvalue)
        return False
    
    elif len(simplevalue_list) == 1:
        if simplevalue_list[0] == '无简称':
            #add_shujuzidian(categoryname,subtitle,stdvalue)
            return " "
        else:
            return simplevalue_list[0]
        
    else:
        print(f"异常数据，具有多个简称。{subtitle},{stdvalue}")
        return False



def dael_name_content(skuname,brand):
    #处理产品名称中 括号里的内容

    skuname = skuname.replace(brand,'')

    name_head = skuname.split('（')[0]
    name_tail = skuname.split('（')[1].split('）')[1]
       
    name_content = skuname.split('（')[1].split('）')[0].split('/')
    
    if (len(list(set(name_content))) == 1 and name_content[0] == ' ') or (len(list(set(name_content))) == 2 and ' ' in name_content and '/' in name_content):
        if name_tail == '': 
            res = brand + name_head
        else:
            res = brand  + name_head + " " + name_tail
    else:
        temp_content = ''
        for element in name_content:
            if element == ' ':
                continue
            else:
                temp_content += element + '/'
        temp_content = "（" + temp_content.strip('/') + "）"
        
        if name_tail == '':
            res = brand + name_head + temp_content
        else:
            if temp_content == '':
                res = brand + name_head + " " + name_tail
            else:
                res = brand + name_head + temp_content + name_tail
    
    return res.strip()


def upload_params_data(category,path):

    df = pd.read_excel(path,converters = {'产品编码':str})
    

    #创建新产品库链接
    try:
        conn_zi_new = pymssql.connect(host='172.17.9.129', user='zgcprice3311',password='zgcprice20200628',database= 'ZI_NEW',autocommit=True)
        cursor_zi_new = conn_zi_new.cursor()
        
        conn_zdindex = pymssql.connect(host='172.17.9.129', user='zgcprice3311',password='zgcprice20200628',database= 'zdindex',autocommit=True)
        cursor_zdindex = conn_zdindex.cursor()
    except:
        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()
        
        conn_zdindex = pymssql.connect(host='123.56.115.207', user='zgcprice3311',password='zgcprice20200628',database= 'zdindex',autocommit=True)
        cursor_zdindex = conn_zdindex.cursor()
    
    ##加载库中参数项数据（参数id，参数从属）
    cursor_zi_new.execute(f"select * from vw_property where name = '{category}' and (identy != '0000' or subtitle = '硬盘容量' or skuorspu = 'spu')")
    db_params = pd.DataFrame(cursor_zi_new.fetchall(), columns=[tuple[0] for tuple in cursor_zi_new.description])
    db_params['subtitle'] = db_params['subtitle'].apply(lambda x: x.strip())
    subtitle_list = db_params['subtitle'].tolist()
    
    
    
    subtitle_id_dict = dict(zip(db_params['subtitle'].tolist(),db_params['subtitleid'].tolist()))
    subtitle_type_dict = dict(zip(db_params['subtitle'].tolist(),db_params['skuorspu'].tolist()))
    
    #获取类别ID
    categoryid = db_params['categoryid'].tolist()[0]
    
    #获取命名规则
    cursor_zi_new.execute(f"select * from skuname_named_rule where categoryname = '{category}'")
    named_rules_df = pd.DataFrame(cursor_zi_new.fetchall(), columns=[tuple[0] for tuple in cursor_zi_new.description])
    
    if named_rules_df.empty:
        print(f"{category}类别无SKU命名规则，无法处理")
        return False
    named_rule = named_rules_df['rule'].str.cat()
    index_func = named_rules_df['index_func'].str.cat()
    tip = eval(named_rules_df['tip'].tolist()[0])
    
    #获取数据字典
    cursor_zi_new.execute(f"select * from ShuJuZiDian_Cfg where categoryname = '{category}' and stdvalue is not Null")
    data_dict = pd.DataFrame(cursor_zi_new.fetchall(), columns=[tuple[0] for tuple in cursor_zi_new.description])
    data_dict['stdvalue'] = data_dict['stdvalue'].apply(lambda x : x.upper())
    single_data_dict = data_dict
    
    #去掉*标识
    current_list = df.columns.tolist()
    update_list = [col[1:] if col[0] == '*' else col for col in current_list]
    col_dict = dict(zip(current_list,update_list))
    df = df.rename(columns=col_dict)

    process_index = 0
    index_ = Index()
    #SPU、SKU命名 
    for index,row in df.iterrows():
        try:
            print(index_(process_index,len(df)-1), end='%')
        except:
            print(index_(process_index,1), end='%')
        process_index+=1
        
        sku = row['产品编码']
        brandname = row['产品品牌']
        try:
            cursor_zi_new.execute(f"select id from p_brand where name = '{brandname}' and id not in (select distinct pid from p_brand)")
            brand_code = cursor_zi_new.fetchone()[0]
        except:
            print(f"异常品牌： {brandname}，请检查产品品牌表")
            break
        
    
        cursor_zi_new.execute(f"select pid from p_brand where id = {brand_code}")
        father_brand_code = cursor_zi_new.fetchone()[0]
        
        cursor_zi_new.execute(f"select id,spuid from p_sku where sku = '{sku}'")
        try:
            skuid,spuid = cursor_zi_new.fetchone()
        except:
            print(f"{sku}已不存在在产品库中")
            continue
        
        spuname = ''
        skuname = ''
        
        #SPU命名
        if category == '复印纸':
            if '彩色' in row['产品系列']:
                spu_brandname = brandname
            else:
                if father_brand_code == 0:
                    spu_brandname = brandname
                else:
                    try:
                        cursor_zi_new.execute(f"select name from p_brand where id = {father_brand_code}")
                        father_brand = cursor_zi_new.fetchone()[0].strip()
                    except:
                        print(f"异常品牌编码： {father_brand_code}，请检查产品品牌表")
                        break
                    spu_brandname = father_brand
        else:
            
            spu_brandname = brandname
        name = str(spu_brandname)
        for spu_param in db_params[db_params['skuorspu'] == 'spu'].sort_values("Expr1")['subtitle'].tolist():
            if spu_param == '产品系列（SPU）':
                if '彩色' in row['产品系列']:
                    value = '彩色复印纸'
                else:
                    value = row['产品系列']
                    
                name += " "
                name += str(value)
            elif spu_param == 'CPU属性':
                name += " "
                cpu = str(row['CPU型号'])
                if '飞腾' in cpu or '龙芯' in cpu or '兆芯' in cpu:
                    pass
                else:
                    cpu = cpu.split('-')[0]
                name += cpu
            else:
            
                name += " "
                name += str(row[spu_param])
            
        
        name = name + " " +str(category)#spu名称
        
        spu = str(uuid.uuid1()).replace('-','')#spu编码

        cursor_zi_new.execute(f"select id from p_spu where categoryid = {categoryid} and brandid = {brand_code} and spuname = '{name}'")
        data = cursor_zi_new.fetchall()
        spu_df = pd.DataFrame(data, columns=[tuple[0] for tuple in cursor_zi_new.description])
        if spu_df.empty:
            cursor_zi_new.execute(f"insert into p_spu (spuname,spu,categoryid,brandid) values ('{name}','{spu}',{categoryid},{brand_code})")
            cursor_zi_new.execute(f"select id from p_spu where spuname = '{name}'")
            spuid = cursor_zi_new.fetchone()[0]
        else:
            spuid = spu_df['id'].tolist()[0]
        
        cursor_zi_new.execute(f"update p_sku set spuid = '{spuid}' where id = '{skuid}'")
        
        params = dict(zip(subtitle_list,[row[subtitle] for subtitle in subtitle_list]))
        '''
        #增加硬盘容量
        if '机械硬盘容量' in subtitle_list:
            jx_harddisk = str(row['机械硬盘容量'])
            gt_harddisk = str(row['固态硬盘容量'])
            
            if jx_harddisk == '0' and gt_harddisk != '0':
                harddisk_value = gt_harddisk
            elif jx_harddisk != '0' and gt_harddisk == '0':
                harddisk_value = jx_harddisk
            elif jx_harddisk != '0' and gt_harddisk != '0':
                harddisk_value = jx_harddisk+"+"+gt_harddisk
            params.update({'硬盘容量':harddisk_value})
        '''
        
        #SKU命名
        for element in named_rule.split(" "):
            
            if element == '品牌名称':
                #复印纸品牌获取（彩色系列取子品牌，白色系列有父品牌取父品牌，否则取子品牌）
                if category == '复印纸':
                    if '彩色' in row['产品系列']:
                        value = brandname
                    else:
                        if father_brand_code == 0:
                            value = brandname
                        else:
                            cursor_zi_new.execute(f"select name from p_brand where id = {father_brand_code}")
                            father_brand = cursor_zi_new.fetchone()[0].strip()
                            value = father_brand
                    value = value.replace("FATHER","")
                else:
                    
                    value = brandname
                
                
            elif element == '类别名称':
                value = category
            
            elif element[0] == "（" and "/" in element:
                element = element.replace("（","").replace("）","")
                detail_element_list = element.split("/")
                for i in range(len(detail_element_list)):
    
                    #value = cat_sku_df[(cat_sku_df['sku'] == sku) & (cat_sku_df['name'] == detail_element_list[i])]['value'].tolist()[0]
                    value = str(params[detail_element_list[i]])
     
                    value = transform_simplevalue(tip,single_data_dict,category,detail_element_list[i],value.upper())
                    
                    if i == 0:
                        skuname += "（" + value + "/"
                        
                    elif i == len(detail_element_list)-1:
                        skuname +=  value + "） "
                        
                    else:
                        skuname +=  value + "/"
                continue
            
            elif element[0] == "（" and "/" not in element:
                element =  element.replace("（","").replace("）","")

                if element == '碎纸效果' and brandname != '碎乐':
                            
                            continue
                
                value = str(params[element])
                
                value = transform_simplevalue(tip,single_data_dict,category,element,value.upper())
                
                skuname += "（" + value + "） "
                continue
            
            else:
                value = str(params[element])
                
                value = transform_simplevalue(tip,single_data_dict,category,element,value.upper())
                
                if element == '计价规格（包/箱或单包装）':
                    value = '计价规格：' + value
        
            skuname += value + " "

        skuname = skuname.strip()
    
        #处理名称中的空格
        if index_func == 'func1':
            skuname = skuname    
        
        #elif category in ['笔记本','台式机','一体电脑','碎纸机','U盘','电热水器','冰箱','电风扇','移动硬盘']:
        elif index_func == 'func2':
            
            skuname = dael_name_content(skuname,brandname)
    
        #elif category in ['复印机','多功能一体机','单反相机','显示器','平板电视','触控一体机','平板电脑']:
        elif index_func == 'func3':
    
            skuname_part1 = skuname.split(category)[0]
            skuname_part2 = skuname.split(category)[1]
            
            skuname_1 = dael_name_content(skuname_part1,brandname)
            skuname_2 = dael_name_content(skuname_part2,brandname).replace(brandname,"")
            
            skuname = skuname_1 + " " + category + skuname_2
            
        #elif category in ['投影机','激光打印机','空调']:
        elif index_func == 'func4':
            if category == '空调':
                skuname_part1 = skuname.split("空调 （")[0].strip()
            else:
                skuname_part1 = skuname.split(category)[0].strip()
            skuname_part2 = skuname.replace("中央空调","").replace("空调扇","").split(category)[1]
            
            skuname_2 = dael_name_content(skuname_part2,brandname).replace(brandname,"")
            
            skuname = skuname_part1 + " " + category + skuname_2
     
        #elif category in ['单电/微单相机']:
        elif index_func == 'func5':
            
            skuname_part1 = skuname.split(category)[0]
            skuname_part2 = skuname.split(category)[1]
            
            skuname_1 = dael_name_content(skuname_part1,brandname)
            skuname_2 = dael_name_content(skuname_part2,brandname).replace(brandname,"")
            
            skuname = skuname_1 + " " + category + skuname_2
        #else:
        elif index_func == 'func6':
            
            skuname_part1 = skuname.split(category)[0].strip()
            skuname_part2 = skuname.split(category)[1]
            
            skuname_2 = dael_name_content(skuname_part2,brandname).replace(brandname,"")
            
            skuname = skuname_part1 + " " +category + skuname_2
        if len(skuname) > 200:
            skuname = skuname[0:200]+"..."
            
        try:
            cursor_zi_new.execute(f"update p_sku set skuname = '{skuname}' where sku = '{sku}'")
        except:
            cursor_zi_new.execute(f"select sku from p_sku where skuname = '{skuname}'")
            correct_sku = cursor_zi_new.fetchone()[0]

            skuname_double = skuname + f"（sku：{sku}；重复sku：{correct_sku}）"
            cursor_zi_new.execute(f"update p_sku set skuname = '{skuname_double}',state = '6' where sku = '{sku}'")

            #更新价格库数据
            cursor_zdindex.execute(f"select top 1 max(periods) from zd_entry_goods_price")
            periods = cursor_zdindex.fetchone()[0]
            
            cursor_zdindex.execute(f"update zd_entry_goods_price set goods_id = '{correct_sku}' where periods = '{periods}' and goods_id = '{sku}'")
            cursor_zdindex.execute(f"update zd_electricity_price set goods_id = '{correct_sku}' where periods = '{periods}' and goods_id = '{sku}'")
            cursor_zdindex.execute(f"update zd_purchase_price set goods_id = '{correct_sku}' where periods = '{periods}' and goods_id = '{sku}'")
            
        
        
        for subtitle in subtitle_list:
            
            
            
            value = str(row[subtitle]).strip()
            subtitleid = subtitle_id_dict[subtitle]
            
            subtitle_type = subtitle_type_dict[subtitle]
            
            if subtitle_type == 'sku':
            
                cursor_zi_new.execute(f"select id from p_skuvalue where subtitleid = {subtitleid} and value = '{value}' order by id")
                data = cursor_zi_new.fetchall()
                
                try:
                    valueid = pd.DataFrame(data, columns=[tuple[0] for tuple in cursor_zi_new.description])['id'].tolist()[0]
                except:
                    cursor_zi_new.execute(f"insert into p_skuvalue (subtitleid,value) values ({subtitleid}, '{value}')")
                        
                    cursor_zi_new.execute(f"select id from p_skuvalue where subtitleid = {subtitleid} and value = '{value}'")
                    valueid = pd.DataFrame(cursor_zi_new.fetchall(), columns=[tuple[0] for tuple in cursor_zi_new.description])['id'].tolist()[0]
                    
                    
                cursor_zi_new.execute(f"select a.valueid from p_skuvaluemap a \
                                                  left join p_skuvalue b \
                                                  on a.valueid = b.id \
                                                  left join p_skusubtitle c \
                                                  on b.subtitleid = c.id \
                                                  where a.skuid = {skuid} and c.name = '{subtitle}'")
                data = cursor_zi_new.fetchall()
                valueid_df = pd.DataFrame(data, columns=[tuple[0] for tuple in cursor_zi_new.description])
                
                if valueid_df.empty:
                    
                    cursor_zi_new.execute(f"select id from p_skuvaluemap where skuid = {skuid} and valueid = {valueid}")
                    data = cursor_zi_new.fetchall()
                    check_df = pd.DataFrame(data, columns=[tuple[0] for tuple in cursor_zi_new.description])
                    if check_df.empty:
                        cursor_zi_new.execute(f"insert into p_skuvaluemap (skuid,valueid) values ({skuid}, {valueid})")
                else:
                    
                    valueid_list = valueid_df['valueid'].unique().tolist()
                    for valueid_ in valueid_list:
                        cursor_zi_new.execute(f"delete from p_skuvaluemap where skuid = {skuid} and valueid = {valueid_}")
                    
                    cursor_zi_new.execute(f"select id from p_skuvaluemap where skuid = {skuid} and valueid = {valueid}")
                    data = cursor_zi_new.fetchall()
                    check_df = pd.DataFrame(data, columns=[tuple[0] for tuple in cursor_zi_new.description])
                    if check_df.empty:
                        cursor_zi_new.execute(f"insert into p_skuvaluemap (skuid,valueid) values ({skuid}, {valueid})")
                        
            elif subtitle_type == 'spu':
                
                cursor_zi_new.execute(f"select id from p_value where subtitleid = {subtitleid} and value = '{value}' order by id")
                data = cursor_zi_new.fetchall()
                
                try:
                    valueid = pd.DataFrame(data, columns=[tuple[0] for tuple in cursor_zi_new.description])['id'].tolist()[0]
                except:
                    cursor_zi_new.execute(f"insert into p_value (subtitleid,value) values ({subtitleid}, '{value}')")
                        
                    cursor_zi_new.execute(f"select id from p_value where subtitleid = {subtitleid} and value = '{value}'")
                    valueid = pd.DataFrame(cursor_zi_new.fetchall(), columns=[tuple[0] for tuple in cursor_zi_new.description])['id'].tolist()[0]
                    
                    
                cursor_zi_new.execute(f"select a.valueid from p_valuemap a \
                                                  left join p_value b \
                                                  on a.valueid = b.id \
                                                  left join p_subtitle c \
                                                  on b.subtitleid = c.id \
                                                  where a.spuid = {spuid} and c.name = '{subtitle}'")
                data = cursor_zi_new.fetchall()
                valueid_df = pd.DataFrame(data, columns=[tuple[0] for tuple in cursor_zi_new.description])
                
                if valueid_df.empty:
                    
                    cursor_zi_new.execute(f"select id from p_valuemap where spuid = {spuid} and valueid = {valueid}")
                    data = cursor_zi_new.fetchall()
                    check_df = pd.DataFrame(data, columns=[tuple[0] for tuple in cursor_zi_new.description])
                    if check_df.empty:
                        cursor_zi_new.execute(f"insert into p_valuemap (spuid,valueid) values ({spuid}, {valueid})")
                else:
                    
                    valueid_list = valueid_df['valueid'].unique().tolist()
                    for valueid_ in valueid_list:
                        cursor_zi_new.execute(f"delete from p_valuemap where spuid = {spuid} and valueid = {valueid_}")
                    
                    cursor_zi_new.execute(f"select id from p_valuemap where spuid = {spuid} and valueid = {valueid}")
                    data = cursor_zi_new.fetchall()                
                    check_df = pd.DataFrame(data, columns=[tuple[0] for tuple in cursor_zi_new.description])
                    if check_df.empty:
                        cursor_zi_new.execute(f"insert into p_valuemap (spuid,valueid) values ({spuid}, {valueid})")
    
    conn_zi_new.close()
    print(f"{category}参数数据更新完成，命名完成")

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,params_list):
    
    if category not in ['笔记本','台式机','一体电脑','工作站']:
        return "该类别无配件，无需校验配件价格"
    
    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)
    #cat_params_df['备注'] = cat_params_df['备注'].apply(lambda x:str(x))
    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 = '台式机'
path = '/Users/rico/WorkSpace/1_Project/Company/中电中采/4_中电商品库功能类/更新库内参数并重新命名/台式机参数确认(校验通过).xlsx'

upload_params_data(category,path)

#params_list = ['CPU型号', '产品子系列', '产品系列', '内存容量', '固态硬盘容量', '屏幕尺寸', '操作系统', '显存容量', '机械硬盘容量', '质保时间']
#check_configure_price(category,path,params_list)