#!/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

def transform_simplevalue(cursor_zi_new,shujuzidiandf,categoryname,subtitle,stdvalue):
    
    stdvalue = stdvalue.strip()
    
    simple_subtitle_list = ['CPU型号','显存容量','操作系统','双面器','双面输稿器','网络打印','标配外服务及配件','标配外耗材','镜头描述','碎纸效果','产品尺寸','分辨率','是否含壁挂架','是否含底座','CPU','内存','硬盘','尺寸']
    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})
    

    #创建新产品库链接
    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'")
    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()
    
    
    #获取数据字典
    cursor_zi_new.execute(f"select * from ShuJuZiDian_Cfg where categoryname = '{category}'")
    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
    
    
    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['产品品牌']
        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]
        
    
        cursor_zi_new.execute(f"select pid from p_brand where id = {brand_code}")
        father_brand_code = cursor_zi_new.fetchone()[0]
        
        params = dict(zip(subtitle_list,[row[subtitle] for subtitle in subtitle_list]))
        
        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:
                    cursor_zi_new.execute(f"select name from p_brand where id = {father_brand_code}")
                    father_brand = cursor_zi_new.fetchone()[0].strip()
                    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 == '产品品牌':
                continue
            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}'")
        
        
        
        
        #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
                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(cursor_zi_new,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("）","")
                
                value = str(params[element])
                
                value = transform_simplevalue(cursor_zi_new,single_data_dict,category,element,value.upper())
                
                skuname += "（" + value + "） "
                continue
            
            else:
                value = str(params[element])
                
                value = transform_simplevalue(cursor_zi_new,single_data_dict,category,element,value.upper())
                
                if element == '计价规格（包/箱或单包装）':
                    value = '计价规格：' + value
        
            skuname += value + " "

        skuname = skuname.strip()
    
        #处理名称中的空格
        if category in ['复印纸','扫描仪','针式打印机']:
            skuname = skuname    
        
        elif category in ['笔记本','台式机','一体电脑','碎纸机']:
            
            skuname = dael_name_content(skuname,brandname)
    
        elif category in ['复印机','多功能一体机','单反相机','显示器','平板电视','触控一体机']:
    
            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 ['投影机','激光打印机','空调']:
            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 ['单电/微单相机']:
            
            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:
            
            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
        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}'")
        #print(skuname)
        

        
        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()
    conn_zdindex.close()
    print(f"{category_name}参数数据更新完成，命名完成")
    
 
category_name = '激光打印机'
path = '/Users/rico/Downloads/2 汪伟(校验通过)激光打印机参数确认.xlsx'
   
upload_params_data(category_name,path)