#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug  5 14:28:01 2020

@author: rico
"""
import pymssql
import pandas as pd
import re
import datetime
import time
import uuid

def stock_in_brand(new_brand_list):
    
    #新建品牌
    
    try:
        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()
        
        temp_dict_list = list()
        
        for new_brand in new_brand_list:
            
            res_name_list = list()
            res_code_list = list()
            
            cname = ''.join(re.findall(r'[0-9\u4E00-\u9FA5]', str(new_brand))).strip()
            ename = str(re.sub(r'[^A-Za-z0-9]',' ', str(new_brand)).upper()).strip()
            
            if ename == '':
                new_brand = cname
            else:
                
                if cname == '':
                    new_brand = ename
                else:
                    new_brand = cname + '（' + ename + '）'
            
            cursor_zi_new.execute(f"select name from p_brand where name = '{new_brand}'")
            data = cursor_zi_new.fetchall()
            brand_df = pd.DataFrame(data, columns=[tuple[0] for tuple in cursor_zi_new.description])
            
            if brand_df.empty:
                cursor_zi_new.execute(f"insert into p_brand (name,cname,ename,pid) values('{new_brand}','{cname}','{ename}',0)")
                
            cursor_zi_new.execute(f"select id from p_brand where name = '{new_brand}' and id not in (select distinct(pid) from p_brand)")
            data = cursor_zi_new.fetchall()
            brandcode = pd.DataFrame(data, columns=[tuple[0] for tuple in cursor_zi_new.description])['id'].tolist()[0]
            res_name_list.append(new_brand)
            res_code_list.append(brandcode)
            
            temp_dict = dict(zip(res_name_list,res_code_list))
            temp_dict_list.append(temp_dict)
            
        res_dict = dict(zip(new_brand_list,temp_dict_list))
        
        conn_zi_new.close()
        
        code = 1
        msg = "success"
        
        return code,msg,res_dict
    
    except Exception as e:
        
        conn_zi_new.close()
        code = 0
        msg = str(e)
        return code,msg,{}
    
#new_brand_list = ['测试产品 Test']

#stock_in_brand(new_brand_list)



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.strip()
    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 get_new_name(category,brandname,params):
    try:
        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 * from skuname_named_rule")
        named_rules_df = pd.DataFrame(cursor_zi_new.fetchall(), columns=[tuple[0] for tuple in cursor_zi_new.description])
        #该类别命名规则
        named_rule = named_rules_df[named_rules_df['categoryname'] == category]['rule'].str.cat()
        
        cursor_zi_new.execute("select * from ShuJuZiDian_Cfg")
        data_dict = pd.DataFrame(cursor_zi_new.fetchall(), columns=[tuple[0] for tuple in cursor_zi_new.description])
        
        single_data_dict = data_dict[data_dict['categoryname'] == category]
        single_data_dict['stdvalue'] = single_data_dict['stdvalue'].apply(lambda x : x.upper())
        
    
        flag = True
        skuname = ''
        
        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 value:
                    #    pass
                    #else:
                    #   flag = False
                    #   continue
                    
                    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())
                
                #if value:
                #    pass
                #else:
                #    flag = False
                #    continue
                
                skuname += "（" + value + "） "
                continue
            
            else:
                value = str(params[element])
                
                value = transform_simplevalue(cursor_zi_new,single_data_dict,category,element,value.upper())
                
                #if value:
                #    pass
                #else:
                #    flag = False
                #    continue
                if element == '计价规格（包/箱或单包装）':
                        value = '计价规格：' + value
        
            skuname += value + " "
            
        #if flag == False:
        #    continue
        skuname = skuname.strip()
    
        #处理名称中的空格
        if category in ['复印纸','扫描仪','针式打印机']:
            skuname = skuname    
        
        elif category in ['笔记本','台式机','一体电脑','碎纸机','U盘','电热水器','冰箱']:
            
            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
            
    
        print(skuname)
        conn_zi_new.close()
        code = 1
        msg = "success"
        
        return code,msg,skuname
    
    except Exception as e:
        
        conn_zi_new.close()
        code = 0
        msg = str(e)
        return code,msg,''
    

#get_new_name("台式机","联想（LENOVO）",{"产品系列":"启天","产品子系列":"M427","CPU型号":"AMD RYZEN 3 3200G","内存容量":"8GB","硬盘容量":"1TB+128GB SSD","显存容量":"共享内存容量","操作系统":"WINDOWS 10 PROFESSIONAL","屏幕尺寸":"21英寸","质保时间":"1年"})


#入库
#id_list =  df['id'].tolist()

#zi_brandname_list = df['zi_brandname'].tolist()

#zi_brandcode_list = df['zi_brandcode'].apply(lambda x:str(x)).tolist()

#zi_subcategoryname = df['zi_subcategoryname'].tolist()

#zi_subcategorycode = df['zi_subcategorycode'].apply(lambda x:str(x)).tolist()

#newname_list = df['new_name'].tolist()

#std_params_list = df['params_standard'].apply(lambda x:eval(x)).tolist()

'''
zi_brandname_list = df['FINISH_P_BRAND_NAME'].tolist()

zi_brandcode_list = df['FINISH_P_BRAND_CODE'].apply(lambda x:str(x)).tolist()

zi_subcategoryname = df['FINISH_P_LASTCATEGORY_NAME'].tolist()

zi_subcategorycode = df['FINISH_P_LASTCATEGORY_CODE'].apply(lambda x:str(x)).tolist()

newname_list = df['FINISH_P_NAME'].tolist()

std_params_list = df['FINISH_P_PARAMS'].apply(lambda x:eval(x)).tolist()
'''

#zi_brandname_list,zi_brandcode_list,zi_subcategoryname,zi_subcategorycode,std_params_list,newname_list = brand_list,brandId_list,category_list,categoryId_list,params_list,name_list
def stock_in_product(zi_brandname_list,zi_brandcode_list,zi_subcategoryname,zi_subcategorycode,std_params_list,newname_list):
    
    #
    try:
        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 * from vw_property")
        data = cursor_zi_new.fetchall()
        subtitle_df = pd.DataFrame(data, columns=[tuple[0] for tuple in cursor_zi_new.description])
        
        subtitle_df['require_param'] = subtitle_df['identy'].apply(lambda x: x[0])
        subtitle_df['match_param'] = subtitle_df['identy'].apply(lambda x: x[1])
        subtitle_df['standard_param'] = subtitle_df['identy'].apply(lambda x: x[2])
        subtitle_df['part_param'] = subtitle_df['identy'].apply(lambda x: x[3])
        
        sku_list = list()
        spuid_list = list()
        had_sku_list = list()
        #创建spu参数信息
        spu_params_dict_list = list()
        params_categoryid_list = list()
        params_categoryname_list = list()
 
        #创建sku参数信息
        sku_params_dict_list = list()
        sku_params_categoryid_list = list()
        sku_params_categoryname_list = list()
        
        for brand,brandcode,cat,catcode,params,newname in zip(zi_brandname_list,zi_brandcode_list,zi_subcategoryname,zi_subcategorycode,std_params_list,newname_list):
            
            brand = str(brand.strip())
            brandcode = brandcode
            
            cursor_zi_new.execute(f"select pid from p_brand where id = {brandcode}")
            father_brand_code = cursor_zi_new.fetchone()[0]
            
            if "新建品牌：" in brand:
                create_brand = brand.replace("新建品牌：","")
                res = stock_in_brand([create_brand])
                brand = list(res[2][create_brand].keys())[0]
                brandcode = list(res[2][create_brand].values())[0]
                
            category = cat
            params = params
            
            cat_subtitle_df = subtitle_df[subtitle_df['name'] == category]
            
            #创建SPU 获取SPUid
            
            if category == '复印纸':
                if '彩色' in params['产品系列']:
                    name = brand
                else:
                    if father_brand_code == 0:
                        name = brand
                    else:
                        cursor_zi_new.execute(f"select name from p_brand where id = {father_brand_code}")
                        father_brand = cursor_zi_new.fetchone()[0].strip()
                        name = str(father_brand)
            else:
                
                name = brand

                
            for spu_param in cat_subtitle_df[cat_subtitle_df['skuorspu'] == 'spu'].sort_values("Expr1")['subtitle'].tolist():

                if spu_param == '产品品牌':
                    continue
                else:
                    if spu_param == '产品系列（SPU）':
                        if '彩色' in params['产品系列']:
                            value = '彩色复印纸'
                        else:
                            value = params['产品系列']
                            
                        name += " "
                        name += str(value)
                        
                        params.update({'产品系列（SPU）':value})
                    elif spu_param == 'CPU属性':
                        name += " "
                        cpu = str(params['CPU型号'])
                        if '飞腾' in cpu or '龙芯' in cpu or '兆芯' in cpu:
                            pass
                        else:
                            cpu = cpu.split('-')[0]
                        name += cpu
                        params.update({'CPU属性':cpu})
                    else:
                    
                        name += " "
                        name += str(params[spu_param])
            
            name = name + " " +str(category)#spu名称
            
            spu = str(uuid.uuid1()).replace('-','')#spu编码
            category_code = catcode#类别编码
            brand_code = brandcode#品牌编码
            
            cursor_zi_new.execute(f"select spu from p_spu where categoryid = {category_code} 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])
            param_deal_flag = False #是否处理参数
            if spu_df.empty:
                cursor_zi_new.execute(f"insert into p_spu (spuname,spu,categoryid,brandid) values ('{name}','{spu}',{category_code},{brand_code})")
                param_deal_flag = True
            else:
                spu = spu_df['spu'].tolist()[0]
            
            cursor_zi_new.execute(f"select id from p_spu where spu = '{spu}'")
            data = cursor_zi_new.fetchall()
            spuid = pd.DataFrame(data, columns=[tuple[0] for tuple in cursor_zi_new.description])['id'].tolist()[0] #spuid
            spuid_list.append(spuid)
            
            if param_deal_flag:
                params_spuid_list = list()
                params_dict_list = list()
                
                params_spuid_list.append(str(spuid))
                
                subtitle_list = list()
                value_list = list()
                for subtitle in cat_subtitle_df[cat_subtitle_df['skuorspu'] == 'spu']['subtitle'].tolist():
                    try:
                        value = str(params[subtitle])
                        subtitle_list.append(subtitle)
                        value_list.append(value)
                    except:
                        print(f"'{category}','{subtitle}',缺失")
                        continue
                    
                
                params_dict = dict(zip(subtitle_list,value_list))
                params_dict_list.append(params_dict)
                
                
                spu_params_dict_list.append(dict(zip(params_spuid_list,params_dict_list)))
                params_categoryid_list.append(catcode)
                params_categoryname_list.append(category)
        
            
            skuname = newname.strip().replace("'","''")
            sku = datetime.datetime.now().strftime("%Y-%m-%d%H:%M:%S.%f").replace('-','').replace(':','').replace('.','')[:-3]
            time.sleep(0.001)
            #spuid = int(row['spuid'])
            state = 1
            source = '1'
            createddate = datetime.datetime.now().strftime("%Y-%m-%d %X")
            
            cursor_zi_new.execute(f"select sku from p_sku where skuname = '{skuname}' and spuid = {spuid}")
            data = cursor_zi_new.fetchall()
            sku_df = pd.DataFrame(data, columns=[tuple[0] for tuple in cursor_zi_new.description])
            
            param_deal_flag = False#是否处理参数
            if sku_df.empty:
                try:
                    cursor_zi_new.execute(f"insert into p_sku (skuname,sku,spuid,state,source,createddate) values ('{skuname}','{sku}',{spuid},{state},'{source}','{createddate}')")
                    param_deal_flag = True
                    sku_list.append(sku)
                    had_sku_list.append('None')
                except:
                    print(f"重复商品不入库， '{skuname}'")
                    cursor_zi_new.execute(f"select sku from p_sku where skuname = '{skuname}'")
                    had_sku = cursor_zi_new.fetchone()[0]
                    had_sku_list.append(had_sku)
                    sku_list.append('None')
            else:
                sku = sku_df['sku'].tolist()[0]
                had_sku_list.append(sku)
                sku_list.append('None')
            #cursor_zi_new.execute(f"select id from p_sku where sku = '{sku}'")
            #data = cursor_zi_new.fetchall()
            #skuid = pd.DataFrame(data, columns=[tuple[0] for tuple in cursor_zi_new.description])['id'].tolist()[0] #skuid
            
            
            
            if param_deal_flag:
                params_sku_list = list()
                temp_params_dict_list = list()
                
                params_sku_list.append(sku)
                
                subtitle_list = list()
                value_list = list()
                for subtitle in cat_subtitle_df[cat_subtitle_df['skuorspu'] == 'sku']['subtitle'].tolist():
                    try:
                        value = str(params[subtitle])
                        subtitle_list.append(subtitle)
                        value_list.append(value)
                    except:

                        continue
                        
                
                sku_params_dict = dict(zip(subtitle_list,value_list))
                temp_params_dict_list.append(sku_params_dict)
                
                sku_params_dict_list.append(dict(zip(params_sku_list,temp_params_dict_list)))
                sku_params_categoryid_list.append(catcode)
                sku_params_categoryname_list.append(category)
                
        print(sku_list)
        #print(sku_params_dict_list)
        print(stock_in_params(spu_params_dict_list,params_categoryid_list,params_categoryname_list,'spu'))
        print(stock_in_params(sku_params_dict_list,sku_params_categoryid_list,sku_params_categoryname_list,'sku'))
        
        
        
        conn_zi_new.close()
        
        code = 1
        msg = "success"
        res = {'code':code,'msg':msg,'sku_list':sku_list,'had_sku_list':had_sku_list}
        return res
  
    
    except Exception as e:
        
        conn_zi_new.close()
        code = 0
        msg = str(e)
        res = {'code':code,'msg':msg,'sku_list':[],'had_sku_list':[]}
        return res

     
#zi_brandname_list = ['联想（THINKVISION）']
#zi_brandcode_list = ['11178']
#zi_subcategoryname = ['笔记本']
#zi_subcategorycode = ['672']
#std_params_list = [{'CPU型号':'测试型号','内存容量':'测试8G','产品系列':'测试系列','产品子系列':'测试子系列','CPU属性':'测试CPU属性'}]
#newname_list = ['测试产品00000']
    



#params_dict_list = [{'20201112182020344':{'分类': '消防沙箱', '商品名称': '星工 XINGGONG 消防沙箱 铁皮黄沙箱 加厚 40CM*40CM*40CM', '产品型号': '加厚 40CM*40CM*40CM', '商品产地': '无该参数信息', '商品毛重': '无该参数信息'}}]
#category_id_list = ['14068']
#category_name_list = ['消防器材']
#mode = 'sku'


#params_dict_list = [{'20200813221833380':{'CPU型号':'INTEL 酷睿 双核 I7-6500U测试','产品型号':'测试数据'}},{'20200813221830037':{'CPU型号':'INTEL 酷睿 双核 I7-7500U测试','产品型号':'测试数据'}}]
#category_id_list = ['672','672']
#category_name_list = ['笔记本','笔记本']
#mode = 'sku'

def stock_in_params(params_dict_list,category_id_list,category_name_list,mode):
    
    #导入参数项，参数值
    
    try:
        
        if mode == 'sku':
            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()
            
            index = 0
            for sku_params_dict,category_id,category_name in zip(params_dict_list,category_id_list,category_name_list):
    
                subtitle_list = [list(v.keys()) for v in sku_params_dict.values()][0]
            
                subtitle_id_list = list()
                sku_subtitle_list = list()
                for subtitle in subtitle_list:
                    
                    cursor_zi_new.execute(f"select subtitleid from vw_property where name = '{category_name}' and subtitle = '{subtitle}' and skuorspu = 'sku'")
                    data = cursor_zi_new.fetchone()
                    try:
                        subtitle_id = data[0]
                    except:
                        continue
                        '''
                        cursor_zi_new.execute(f"select id from p_skusubtitle where name = '{subtitle}' and lev = 2")
                        data = cursor_zi_new.fetchone()
                        
                        try:
                            subtitle_id = data[0]
                        except:
                            cursor_zi_new.execute(f"insert into p_skusubtitle (name,lev,pid) values ( '{subtitle}',2,3)")
                            
                            cursor_zi_new.execute(f"select id from p_skusubtitle where name = '{subtitle}' and lev = 2")
                            data = cursor_zi_new.fetchone()
                            subtitle_id = data[0]
                        
                        cursor_zi_new.execute(f"insert into p_skusubtitlecategorymap (categoryid,subtitleid,identy) values ( {category_id},{subtitle_id},'0000')")
                        '''
                    sku_subtitle_list.append(subtitle) 
                    subtitle_id_list.append(subtitle_id)
                    
                subtitle_dict = dict(zip(sku_subtitle_list,subtitle_id_list))
            
            
                sku = list(sku_params_dict.keys())[0]
                cursor_zi_new.execute(f"select id from p_sku where sku = '{sku}'")
                data = cursor_zi_new.fetchone()
                skuid = data[0]
            
                for subtitle in sku_subtitle_list:
            
                    value = sku_params_dict[sku][subtitle].replace("'","''")
                    subtitleid = subtitle_dict[subtitle]
                    
            
                    cursor_zi_new.execute(f"select id from p_skuvalue where subtitleid = {subtitleid} and value = '{value}'")
                    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})")
                        
                           
                index+=1          
                print(index)
                
            conn_zi_new.close()        
            code = 1
            msg = "success"
            
            return code,msg
        
        elif mode == 'spu':
            
            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()

            index = 0
            for spu_params_dict,category_id,category_name in zip(params_dict_list,category_id_list,category_name_list):
    
                subtitle_list = [list(v.keys()) for v in spu_params_dict.values()][0]                    

                subtitle_id_list = list()
                spu_subtitle_list = list()
                for subtitle in subtitle_list:
                    
                    cursor_zi_new.execute(f"select subtitleid from vw_property where name = '{category_name}' and subtitle = '{subtitle}' and skuorspu = 'spu'")
                    data = cursor_zi_new.fetchone()
                    try:
                        subtitle_id = data[0]
                    except:
                        continue
                        '''
                        cursor_zi_new.execute(f"select id from p_subtitle where name = '{subtitle}' and lev = 2")
                        data = cursor_zi_new.fetchone()
                        
                        try:
                            subtitle_id = data[0]
                        except:
                            cursor_zi_new.execute(f"insert into p_subtitle (name,lev,pid) values ( '{subtitle}',2,5)")
                            
                            cursor_zi_new.execute(f"select id from p_subtitle where name = '{subtitle}' and lev = 2")
                            data = cursor_zi_new.fetchone()
                            subtitle_id = data[0]
                        
                        cursor_zi_new.execute(f"insert into p_subtitlecategorymap (categoryid,subtitleid,identy) values ( {category_id},{subtitle_id},'0000')")
                        '''
                    spu_subtitle_list.append(subtitle)
                    subtitle_id_list.append(subtitle_id)
                    
                subtitle_dict = dict(zip(spu_subtitle_list,subtitle_id_list))
            
            
                spuid = list(spu_params_dict.keys())[0]
            
                for subtitle in spu_subtitle_list:
            
                    value = spu_params_dict[spuid][subtitle].replace("'","''")
                    subtitleid = subtitle_dict[subtitle]
                    
            
                    cursor_zi_new.execute(f"select id from p_value where subtitleid = {subtitleid} and value = '{value}'")
                    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})")
                        
                           
                index+=1          
                print(index)
                
            conn_zi_new.close()        
            code = 1
            msg = "success"
            
            return code,msg
                
        else:
            code = 0
            msg = "异常模式"
            return code,msg
    
    except Exception as e:
        
        conn_zi_new.close()
        code = 0
        msg = str(e)
        return code,msg
    
    
def stock_in_sku_relationship(sku_list,code_list,channel_list):
    
    #导入sku对应关系
    
    try:
        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()
        
        createddate = datetime.datetime.now().strftime("%Y-%m-%d %X")
        
        for sku,code,channel in zip(sku_list,code_list,channel_list):
            channel = channel.replace("SXLQ_",'')
            cursor_zi_new.execute(f"select id from Productcode_Sku where sku = '{sku}' and frm = '{channel}'")
            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 Productcode_Sku (productcode,sku,createddate,frm) values ('{code}','{sku}','{createddate}','{channel}')")
            else:
                pass
        
        conn_zi_new.close()
        
        code = 1
        msg = "success"
        res = {'code':code,'msg':msg}
        return res

    
    except Exception as e:
        
        conn_zi_new.close()
        code = 0
        msg = str(e)
        res = {'code':code,'msg':msg}
        return res

    



def stock_in_price(sku_list,goods_name_list,price_list,url_list,channel_id_list):
    
    #导入价格信息
    try:
        conn_zdindex = pymssql.connect(host='123.56.115.207', user='zgcprice3311',password='zgcprice20200628',database= 'zdindex',autocommit=True)
        cursor_zdindex = conn_zdindex.cursor()
        
        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_zi_database = pymssql.connect(host='123.56.115.207', user='zgcprice3311',password='zgcprice20200628',database= 'ZI_DataBase',autocommit=True)
        cursor_zi_database = conn_zi_database.cursor()
        
        #获取实体市场税率
        cursor_zdindex.execute("select * from zd_wholesale_restore_market")
        zd_restore_rate = pd.DataFrame(cursor_zdindex.fetchall(), columns=[tuple[0] for tuple in cursor_zdindex.description])
    
        
        #获取三个渠道的id
        cursor_zdindex.execute("select mall_id as channel_id,'DS' from zd_electricity_mall \
                               UNION all select shop_id  as channel_id,'ST' from zd_entry_shop \
                                   UNION all select purchase_id  as channel_id,'ZC' from zd_purchase_center")
        data = cursor_zdindex.fetchall()
        channel_id_df = pd.DataFrame(data, columns=[tuple[0] for tuple in cursor_zdindex.description])      
        channel_id_dict = dict(zip(channel_id_df['channel_id'].tolist(),channel_id_df[''].tolist()))
        
        
        input_df = pd.DataFrame()
        input_df['sku'] = sku_list
        input_df['goods_name'] = goods_name_list

        input_df['url'] = url_list
        input_df['channel_id'] = channel_id_list
        
        input_df['channel'] = input_df['channel_id'].apply(lambda x : channel_id_dict[x])
        input_df['price'] = [float(ele) for ele in price_list]
        
        ds_df = input_df[input_df['channel'] == 'DS']
        
        st_df = input_df[input_df['channel'] == 'ST']
        
        zc_df = input_df[input_df['channel'] == 'ZC']

        #导入价格库所需的公共参数
        an_state = 0
        mom_state = 0
        create_by = '343ec45436994e4cb35717fc1cc3c528'
        create_time = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
        deleted = 0
        row_version = 0
        cursor_zdindex.execute("select top 1 max(periods) from zd_entry_goods_price")
        periods = str((cursor_zdindex.fetchall())[0]).replace("(","").replace(",)","")
        
        public_parmas_tuple = (an_state,mom_state,create_by,create_time,deleted,row_version,periods)
        
        #电商价格导入
        if ds_df.empty:
            print("无电商价格录入")
        else:
            
            sku_rel_sku_list = []
            sku_rel_productcode_list = []
            sku_rel_channel_list = []
            
            insert_list = list()
            for index,row in ds_df.iterrows():
                
                sku = row['sku']
                skuname = str(row['goods_name']).replace("'","''")
                price = float(row['price'])
                url = row['url'].strip()
                channel_id = row['channel_id']
                
                insert_list.append((sku,skuname,price,url,channel_id) + public_parmas_tuple)
                
                sku_rel_channel = channel_id.split('-')[1]
                
                if sku_rel_channel == 'GM':
                    sku_rel_sku = url.split('.html')[0].split('-')[-1]
                else: 
                    sku_rel_sku = url.split('.html')[0].split('/')[-1]
                
                sku_rel_sku_list.append(sku_rel_sku)
                sku_rel_productcode_list.append(sku)
                sku_rel_channel_list.append(sku_rel_channel)
        
            data_status = 1
            params = [tuple_data + (data_status,) for tuple_data in insert_list]
            
            sql = 'insert into zd_electricity_price (goods_id,goods_name,goods_price,goods_url,mall_id,an_state,mom_state,create_by,create_time,deleted,row_version,periods,data_status) \
               values (%s,%s,%d,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)'
        
            cursor_zdindex.executemany(sql,params)
            
            #删除重复插入的数据
            cursor_zdindex.execute(f"delete from zd_electricity_price where id in (select a.id from ( \
                                    select MIN(id) id,goods_id,mall_id,goods_price,goods_url from zd_electricity_price \
                                    where periods = '{periods}' \
                                    GROUP BY goods_id,mall_id,goods_price,goods_url \
                                    HAVING COUNT(1) > 1) a)")
            
            res = stock_in_sku_relationship(sku_rel_sku_list,sku_rel_productcode_list,sku_rel_channel_list)
            print(res)
            print("电商对应关系录入完成")
            
            print("电商价格录入完成")
        
        #政采价格导入
        if zc_df.empty:
            print("无政采价格录入")
        else:
            
            zc_df_contract = zc_df[(zc_df['url'] == '') | (zc_df['url'] == '无')]
            zc_df_ele = zc_df[(zc_df['url'] != '') & (zc_df['url'] != '无')]
            
            if zc_df_ele.empty:
                print("无政采电子商城价格录入")
            else:
                insert_list = list()
                for index,row in zc_df_ele.iterrows():
                    
                    sku = row['sku']
                    skuname = str(row['goods_name']).replace("'","''")
                    price = float(row['price'])
                    url = row['url'].strip()
                    channel_id = row['channel_id']
                    
                    insert_list.append((sku,skuname,price,url,channel_id) + public_parmas_tuple)
                    
                data_status = 1
                price_id = datetime.datetime.now().strftime("%Y-%m-%d%H:%M:%S.%f").replace('-','').replace(':','').replace('.','')
            
                params = [tuple_data + (data_status,price_id) for tuple_data in insert_list]
                
                sql = 'insert into zd_purchase_price (goods_id,goods_name,electronic_mall_price,goods_url,purchase_id,an_state,mom_state,create_by,create_time,deleted,row_version,periods,data_status,price_id) \
                   values (%s,%s,%d,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)'
            
                cursor_zdindex.executemany(sql,params)
                print("政采电子商城价格录入完成")
                
            if zc_df_contract.empty:
                print("无政采合同价格录入")
            else:
                insert_list = list()
                for index,row in zc_df_contract.iterrows():
                    
                    sku = row['sku']
                    skuname = str(row['goods_name']).replace("'","''")
                    price = float(row['price'])
                    channel_id = row['channel_id']
                    
                    insert_list.append((sku,skuname,price,channel_id) + public_parmas_tuple)
                    
                data_status = 1
                price_id = datetime.datetime.now().strftime("%Y-%m-%d%H:%M:%S.%f").replace('-','').replace(':','').replace('.','')
            
                params = [tuple_data + (data_status,price_id) for tuple_data in insert_list]
                
                sql = 'insert into zd_purchase_price (goods_id,goods_name,contract_price,purchase_id,an_state,mom_state,create_by,create_time,deleted,row_version,periods,data_status,price_id) \
                   values (%s,%s,%d,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)'
            
                cursor_zdindex.executemany(sql,params)
                print("政采合同价格录入完成")
        
        #实体价格导入
        if st_df.empty:
            print("无实体价格录入")
        else:
            
            insert_list = list()
            for index,row in st_df.iterrows():
                
                sku = row['sku']
                
                cursor_zi_new.execute(f"select b.categoryid,b.brandid from p_sku a \
                                      left join p_spu b \
                                          on a.spuid = b.id \
                                              where a.sku = '{sku}'")
                
                data = cursor_zi_new.fetchall()
                search_df = pd.DataFrame(data, columns=[tuple[0] for tuple in cursor_zi_new.description])
                
                cat_id = search_df['categoryid'].tolist()[0]
                brand_id = search_df['brandid'].tolist()[0]
                
                skuname = str(row['goods_name']).replace("'","''")
                in_price = float(row['price'])
                
                rate = zd_restore_rate[(zd_restore_rate['sub_category_code'] == cat_id) & (zd_restore_rate['brand_code'] == brand_id) & ((zd_restore_rate['begin_price'] < in_price) | (zd_restore_rate['begin_price'] == in_price)) & ((zd_restore_rate['end_price'] > in_price) | (zd_restore_rate['end_price'] == in_price))]['max_rate'].tolist()[0]
                entry_retail_price = float(in_price*float(rate))
                
                channel_id = row['channel_id']
                
                insert_list.append((sku,skuname,in_price,entry_retail_price,channel_id) + public_parmas_tuple)
                
            is_copy = 0
            params = [tuple_data + (is_copy) for tuple_data in insert_list]
            
            sql = 'insert into zd_entry_goods_price (goods_id,goods_name,in_price,entry_retail_price,shop_id,an_state,mom_state,create_by,create_time,deleted,row_version,periods,is_copy) \
               values (%s,%s,%d,%d,%s,%s,%s,%s,%s,%s,%s,%s,%s)'
        
            cursor_zdindex.executemany(sql,params)
            print("实体价格录入完成")
         
        #临时价格导入
        for index,row in input_df.iterrows():
            sku = row['sku']
            skuname = str(row['goods_name']).replace("'","''")
            price = float(row['price'])
            
            cursor_zi_database.execute(f"select Index_ID from ZI_Price_Quote where ProductCode = '{sku}'")
            check_df = pd.DataFrame(cursor_zi_database.fetchall(), columns=[tuple[0] for tuple in cursor_zi_database.description])
            if check_df.empty:
                cursor_zi_database.execute(f"insert into ZI_Price_Quote(ProductCode,CreatedDate,ProductName,MaximumPrice) values ('{sku}','{create_time}','{skuname}',{price})")
            else:
                pass
            
        print("临时表价格录入完成") 
        
        
        conn_zi_database.close()
        conn_zi_new.close()
        conn_zdindex.close()
        
        code = 1
        msg = "success"
        res = {'code':code,'msg':msg}
        return res

        
    except Exception as e:
        
        conn_zi_database.close()
        conn_zi_new.close()
        conn_zdindex.close()
        code = 0
        msg = str(e)
        res = {'code':code,'msg':msg}
        return res



#sku_list = ['111111']
#goods_name_list = ['测试产品']
#price_list = ['1985']
#url_list = ['www.jd.com/item1542115']
#channel_id_list = ['DS-JD']
#stock_in_price(sku_list,goods_name_list,price_list,url_list,channel_id_list)





def stock_in_attr_relationship(channel,categoryname_list,subtitle_list,outsubtitle_list):
    
    #导入参数项对应关系
    
    try:
        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()
        
        
        for cat,subtitle,outsubtitle in zip(categoryname_list,subtitle_list,outsubtitle_list):
            
            cursor_zi_new.execute(f"select Index_ID from Product_Relation_Attribute_Subtitle where ZI_SubCategoryCode = '{cat}' and ZI_SubTitle = '{subtitle}' and Other_SubTitle = '{outsubtitle}' and Source = '{channel}'")
            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 Product_Relation_Attribute_Subtitle (ZI_SubCategoryCode,ZI_SubTitle,Other_SubTitle,Source) values ('{cat}','{subtitle}','{outsubtitle}','{channel}')")
            else:
                pass
        
        conn_zi_new.close()
        
        code = 1
        msg = "success"
        res = {'code':code,'msg':msg}
        return res

    
    except Exception as e:
        
        conn_zi_new.close()
        code = 0
        msg = str(e)
        res = {'code':code,'msg':msg}
        return res



'''
def stock_in_category_relationship(channel,categoryname_list,zi_categoryname_list,zi_categorycode_list):
    
    #导入类别对应关系(入产品库)
    
    try:
        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()
        
        
        for cat,zi_cat,zi_cat_code in zip(categoryname_list,zi_categoryname_list,zi_categorycode_list):
            
            cursor_zi_new.execute(f"select id from p_skusubtitle_out_map where categoryname = '{cat}' and subtitle = '{subtitle}' and outsubtitle = '{outsubtitle}' and frm = '{channel}'")
            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_skusubtitle_out_map (categoryname,subtitle,outsubtitle,frm) values ('{cat}','{subtitle}','{outsubtitle}','{channel}')")
            else:
                pass
        
        conn_zi_new.close()
        
        code = 1
        msg = "success"
        
        return code,msg
    
    except Exception as e:
        
        conn_zi_new.close()
        code = 0
        msg = str(e)
        return code,msg
'''
    
def stock_in_category_relationship_to_server(channel,categoryname_list,zi_categoryname_list,zi_categorycode_list):
    
    #导入类别对应关系（入服务库）
    
    try:

        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()
        
        for cat,zi_cat,zi_cat_code in zip(categoryname_list,zi_categoryname_list,zi_categorycode_list):
            
            cursor_zi_new.execute(f"select id from product_category_map where type = 'channel_category_map' and othersubcategory = '{cat}' and subcategoryname = '{zi_cat}' and subcategorycode = '{zi_cat_code}' and frm_alias = '{channel}'")
            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 product_category_map (othersubcategory,subcategoryname,subcategorycode,frm_alias,type) values ('{cat}','{zi_cat}','{zi_cat_code}','{channel}','channel_category_map')")
            else:
                pass
            
            cursor_zi_new.execute(f"select id from product_category_map where type = 'p_category_detail_map' and othersubcategory = '{cat}' and subcategoryname = '{zi_cat}' and subcategorycode = '{zi_cat_code}'")
            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 product_category_map (subcategoryname,subcategorycode,othersubcategory,type) values ('{zi_cat}','{zi_cat_code}','{cat}','p_category_detail_map')")
            else:
                pass
            
        
        conn_zi_new.close()
        
        code = 1
        msg = "success"
        
        res = {'code':code,'msg':msg}
        return res
    
    except Exception as e:
        
        conn_zi_new.close()
        code = 0
        msg = str(e)
        res = {'code':code,'msg':msg}
        return res
'''
df = pd.read_excel("/Users/rico/Downloads/新品获取渠道信息整理_20210201.xlsx",sheet_name = '类别对应关系')
code = []
for index,row in df.iterrows():
    
    cursor_zi_new.execute(f"select id from p_category where name = '{row['对应指数类别']}' and id not in (select distinct pid from p_category)")
    code.append(cursor_zi_new.fetchone()[0])

df['编码'] = code
for index,row in df.iterrows():
    
    cat = row['客户类别']
    zi_cat = row['对应指数类别']
    zi_cat_code = row['编码']
    cat = row['客户类别']
    channel = row['政采名称']
    channel_alias = row['政采简称']
    
    cursor_zi_new.execute(f"select id from product_category_map where type = 'channel_category_map' and othersubcategory = '{cat}' and subcategoryname = '{zi_cat}' and subcategorycode = '{zi_cat_code}' and frm_alias = '{channel_alias}'")
    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 product_category_map (othersubcategory,subcategoryname,subcategorycode,frm,frm_alias,type) values ('{cat}','{zi_cat}','{zi_cat_code}','{channel}','{channel_alias}','channel_category_map')")
    else:
        pass
    

    
'''

    