import uuid
import pandas as pd
import pymssql

# coding=utf-8

#读取excel中的内容

def clean_excel(DATABASE):
    #需要修改为1不用修改为0
    index_row = 0
    is_important_category = []
    df_test = pd.read_excel('显示器产品类别分析0428.xlsx',sheet_name = 0,converters={'产品编码':str,'备注':str,'是否为重点类':str})
    category_name = df_test['类别名称'].tolist()
    conn = pymssql.connect(host='123.56.115.207', user='zgcprice3311',password='zgcprice20200628',database= DATABASE ,autocommit=True)
    #创建游标
    cursor = conn.cursor()
    sql = ("SELECT category_name FROM important_category_service")
    cursor.execute(sql)
    important_category_tuple = cursor.fetchone()
    important_category = ''.join(important_category_tuple)
    for i in category_name:
        if str(i) in important_category:
            is_important_category.append('0')
            index_row+=1
        else:
            is_important_category.append('1')
            index_row+=1
    df_test['是否需要手动修改'] = is_important_category
    df_clean = df_test[df_test['备注'] == '1']
    df_clean.to_excel(r'显示器产品类别分析0428_清洗后.xlsx', index = False)
    return df_clean

#SKU命名
def all_modify_SKU_name(product_name,category_name,product_category,DATABASE):
    list_temp = []#需要输出的列表
    index_row = 0
    #从excel中获取两个列的数据，类型为list
    product_name_list = df_clean[product_name].tolist()
    category_name_list = df_clean[category_name].tolist()
    product_category_list = df_clean[product_category].tolist()
    import_category_list = df_clean["是否重点类"].tolist()
    print(import_category_list)
    #替换产品名称中错误的类别
    for i in product_name_list:
        #重点类，需要生成新sku名字
        print(import_category_list[index_row])
        print(type(import_category_list[index_row]))
        if import_category_list[index_row] == 1.0:
            print("重点类")
            temp = i.replace(category_name_list[index_row], "")
            temp_1 = temp.replace(product_category_list[index_row], "")
            temp_final = temp_1+" "+category_name_list[index_row]
            list_temp.append(temp_final)
        #非重点类，sku名字已经修改正确
        else:
            list_temp.append(i)
        index_row += 1
    print("Through the list")
    #检查替换后的列表    
    SKU_name = list_temp
    print(SKU_name)
    return SKU_name

#SPU命名
def all_modify_SPU_name(product_brand,category_name):
    list_temp = []
    index_row = 0
    #从excel中获取两个列的数据，类型为list
    product_brand_list = df_clean[product_brand].tolist()
    category_name_list = df_clean[category_name].tolist()
    #合并两项成为SPU
    for i in product_brand_list:
        temp = product_brand_list[index_row] + ' ' + category_name_list[index_row]
        list_temp.append(temp)
        index_row+=1
    
    SPU_name = list_temp
    return SPU_name    


def all_match_SPU_name(DATABASE,TEST_DATABASE,SPU_name, CATEGORY_id, BRAND_id):
    # host    数据库服务器名称或IP
    # user      用户名
    # password  密码
    # database  数据库名称
    #连接数据库
    conn = pymssql.connect(host='123.56.115.207', user='zgcprice3311',password='zgcprice20200628',database= DATABASE ,autocommit=True)
    #创建游标
    cursor_database = conn.cursor()
    conn_test = pymssql.connect(host='123.56.115.207', user='zgcprice3311',password='zgcprice20200628',database= DATABASE ,autocommit=True)
    #创建游标
    cursor_test = conn_test.cursor()
    #需要输出的列表
    list_spu_update = []
    #计算找到和没找到的SPU的名字
    match_number = 0
    unmatch_number = 0
    index_row = 0
    for i in SPU_name:
        sql = ("SELECT spu FROM p_spu WHERE spuname = %s")
        cursor_database.execute(sql,i)
        spu_update_tuple = cursor_database.fetchone()

        if(spu_update_tuple is None):
            spu = str(uuid.uuid1()).replace('-','')#spu编码          
            list_spu_update.append(spu)
            print("SPU created by uuid")
            sql_insert = "INSERT INTO p_spu(spuname, spu, categoryid, brandid) VALUES (%s, %s, %s, %s)"
            print(i)
            print(spu)
            print(CATEGORY_id[index_row])
            print(BRAND_id[index_row])
            列名1 = i
            列名2 = spu
            列名3 = CATEGORY_id[index_row]
            列名4 = BRAND_id[index_row]
  
            values = (列名1, 列名2, 列名3, 列名4)
            cursor_test.execute(sql_insert, values)
            index_row += 1
            unmatch_number+=1

        else:
            spu_update = spu_update_tuple[0]           
            list_spu_update.append(spu_update)
            print("SPU founded in database")
            match_number+=1
            index_row += 1

    #print(list_spu_update)
    print("The number of matched data is")
    print(match_number)
    print("The number of unique data is")
    print(unmatch_number)
    conn.close()
    conn_test.close()
    return list_spu_update


def all_get_category_id (category_id):
    category_id_list = df_clean[category_id].tolist()
    #print(category_id_list)
    return category_id_list


def all_get_brand_id (product_brand, DATABASE):
    product_brand_list = df_clean[product_brand].tolist()
    list_brand_id_update = []
    conn = pymssql.connect(host='123.56.115.207', user='zgcprice3311',password='zgcprice20200628',database= DATABASE ,autocommit=True)
    #创建游标
    cursor_read = conn.cursor()
    for i in product_brand_list:
        #print(i).
        sql = ("SELECT id FROM p_brand WHERE name = %s")
        cursor_read.execute(sql,i)
        brand_update_id_tuple = cursor_read.fetchone()
        #判断产品ID是否存在
        if(brand_update_id_tuple[0] == ""):
            print("此产品项不存在")
            list_brand_id_update.append("产品id需补充")
        else:
            list_brand_id_update.append(brand_update_id_tuple[0])


    
    conn.close()
    return(list_brand_id_update)


def delete_data(SPU_name, DATABASE):
    conn = pymssql.connect(host='123.56.115.207', user='zgcprice3311',password='zgcprice20200628',database= DATABASE ,autocommit=True)
    cursor = conn.cursor()
    for i in SPU_name:
        print(i)
        sql = "DELETE FROM p_spu WHERE spuname = %s"
        cursor.execute(sql, i)
    conn.close()


def get_sku(sku):
    sku_list = df_clean[sku].tolist()
    #print(sku_list)
    return(sku_list)


def get_spu_id(spu, DATABASE):
    spu_id_list = []
    conn = pymssql.connect(host='123.56.115.207', user='zgcprice3311',password='zgcprice20200628',database= DATABASE ,autocommit=True)
    #创建游标
    cursor_read = conn.cursor()
    for i in spu:
        #print(i)
        #print(i)
        sql = ("SELECT id FROM p_spu WHERE spu = %s")
        cursor_read.execute(sql,i)
        temp = cursor_read.fetchone()
        spu_id_list.append(temp[0])
        #判断产品ID是否存在
    #print(spu_id_list)
    conn.close()
    return(spu_id_list)

    
def write_data_to_excel(sku, spu, spu_id):
    sku_excel = sku
    spu_excel = spu
    spu_id_excel = spu_id
    df = pd.DataFrame.from_dict({'sku':sku_excel,'spu':spu_excel,'spu_id': spu_id_excel})
    df.to_excel('data.xlsx', header=True, index=False)

def update_sku_data(DATABASE,SKU,SKU_name,SPU_ID):
    #连接数据库
    conn = pymssql.connect(host='123.56.115.207', user='zgcprice3311',password='zgcprice20200628',database= DATABASE ,autocommit=True)
    #创建游标
    cursor_read = conn.cursor()
    j = 0
    for i in SKU_name:
        sql = "SELECT id FROM p_sku where skuname = %s"
        sql_1 = "UPDATE p_sku SET skuname = %s WHERE sku = %s"  #1.更新p_sku中的skuname，通过表中的sku进行匹配
        sql_2 = "UPDATE p_sku SET spuid = %s  WHERE  sku = %s"  #2.更新p_sku中的spuid，通过表中的sku进行匹配
        cursor_read.execute(sql,i)
        result = cursor_read.fetchone()
        if (result is None):
            values_1 = (SKU_name[j],SKU[j])
            values_2 = (SPU_ID[j],SKU[j])
            cursor_read.execute(sql_1, values_1)
            cursor_read.execute(sql_2, values_2)
        else:
            values_2 = (SPU_ID[j],SKU[j])
            cursor_read.execute(sql_2, values_2)
        j +=1
    print("The work is done for category update")

sku = '产品编码'
product_brand = '产品品牌'
product_name = '产品名称'
product_category = '产品类别'
category_name = '类别名称'
category_id = '类别编码'
database = 'ZI_NEW'
test_database = 'ZI_NEW_TEST'

#在跑之前只需改第243行得excel文件路径和第237行得库名

#df_clean = clean_excel(database)
df_excel = pd.read_excel('平板电视类别分析0512_反馈.xlsx', sheet_name = 0, converters={'产品编码':str,'类别名称':str,'产品名称':str,'产品品牌':str,'产品类别':str,'类别编码':str,'是否为重点类': int,'备注':int})
df_clean = df_excel[df_excel['备注'] == 1]
SKU_name = all_modify_SKU_name(product_name,category_name,product_category,database)
SPU_name = all_modify_SPU_name(product_brand,category_name)
CATEGORY_id = all_get_category_id (category_id)
BRAND_id = all_get_brand_id (product_brand, database)
SPU = all_match_SPU_name(database,database,SPU_name,CATEGORY_id,BRAND_id)
SKU = get_sku(sku)
SPU_ID = get_spu_id(SPU, database)
#print(SKU)
#update_sku_data(database,SKU,SKU_name,SPU_ID)

#delete_data(SPU_name, test_database)删库内数据用的，少用







