#!usr/bin/env python
# -*- coding:utf-8 -*-
"""
@author: dell
@file: 重复产品更新.py
@time: 2021/04/07
@desc:
"""
import pymssql
import pandas as pd
import time
import os


def duplicate_product_update(filepath,sheet_name=0):
    df=pd.read_excel(filepath,sheet_name=sheet_name,converters={'产品编码': str, '正确产品编码':str, '产品名称': str, '正确产品名称':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_zi_test=pymssql.connect(host='123.56.115.207', user='zgcprice3311', password='zgcprice20200628',
                                      database='ZI_NEW_TEST', autocommit=True)
    cursor_zi_test=conn_zi_test.cursor()
    conn_zdindex=pymssql.connect(host='123.56.115.207', user='zgcprice3311', password='zgcprice20200628',
                                      database='zdindex', autocommit=True)
    cursor_zdindex=conn_zdindex.cursor()

    timestr = time.strftime('%Y-%m-%d %H %M %S', time.localtime())
    folderpath = "./数据库更新日志"
    folder = os.path.exists(folderpath)
    if not folder:
        os.makedirs(folderpath)
    logname = f"{folderpath}/重复产品更新{timestr}.txt"
    with open(f"{logname}", 'w', encoding='utf-8') as f:
        for index,row in df.iterrows():
            if type(row['正确产品编码']) == float:
                continue
            product_id=row['产品编码']
            product_id_correct=row['正确产品编码']
            product_name = row['产品名称']
            product_name_correct = row['正确产品名称']
            if product_id == product_id_correct and product_name==product_name_correct:
                continue
            print(f"index:{index}", file=f)

            product_name_repeated = product_name_correct + f"（sku：{product_id}；重复sku：{product_id_correct}）"

            cursor_zi_new.execute(f"update p_sku set state=6, skuname='{product_name_repeated}' where sku='{product_id}' ")
            print(f"    if successful: p_sku表，sku编码为'{product_id}'的数据，state被改为6，skuname被改为'{product_name_repeated}'", file=f)
            cursor_zi_new.execute(f"update Productcode_Sku set sku='{product_id_correct}' where sku='{product_id}' ")
            print(f"    if successful: Productcode_Sku表，sku编码为'{product_id}'的数据，sku被改为'{product_id_correct}'", file=f)
            cursor_zdindex.execute("select top 1 max(periods) from zd_electricity_price")
            zd_e_p=cursor_zdindex.fetchone()[0]
            cursor_zdindex.execute(f"update zd_electricity_price set goods_id='{product_id_correct}' where goods_id = '{product_id}' and periods = {zd_e_p} ")
            print(f"    if successful: zd_electricity_price表，goods_id为'{product_id}'且periods为最新的数据，goods_id被改为'{product_id_correct}'", file=f)
            cursor_zdindex.execute("select top 1 max(periods) from zd_purchase_price")
            zd_p_p = cursor_zdindex.fetchone()[0]
            cursor_zdindex.execute(
                f"update zd_purchase_price set goods_id='{product_id_correct}' where goods_id = '{product_id}' and periods = {zd_p_p} ")
            print(
                f"    if successful: zd_purchase_price表，goods_id为'{product_id}'且periods为最新的数据，goods_id被改为'{product_id_correct}'",
                file=f)
            cursor_zdindex.execute("select top 1 max(periods) from zd_entry_goods_price")
            zd_e_g_p = cursor_zdindex.fetchone()[0]
            cursor_zdindex.execute(
                f"update zd_entry_goods_price set goods_id='{product_id_correct}' where goods_id = '{product_id}' and periods = {zd_e_g_p} ")
            print(
                f"    if successful: zd_entry_goods_price表，goods_id为'{product_id}'且periods为最新的数据，goods_id被改为'{product_id_correct}'",
                file=f)
            cursor_zdindex.execute("select top 1 max(periods) from zd_week_price")
            zd_w_p = cursor_zdindex.fetchone()[0]
            cursor_zdindex.execute(
                f"update zd_week_price set goods_id='{product_id_correct}' where goods_id = '{product_id}' and periods = {zd_w_p} ")
            print(
                f"    if successful: zd_week_price表，goods_id为'{product_id}'且periods为最新的数据，goods_id被改为'{product_id_correct}'",
                file=f)


if __name__ == '__main__':
    # filepath="E:\\ZDZC\\激光打印机产品重复型号分析.xlsx"
    filepath="E:\\ZDZC\\显示器重复产品分析0506.xlsx"
    sheet_name = 'Sheet1'
    duplicate_product_update(filepath, sheet_name)

# filepath="E:\\ZDZC\\处理后数据-扫描仪数据0407.xlsx"
# sheet_name='重复产品'
# df=pd.read_excel(filepath,sheet_name=sheet_name,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_zi_test=pymssql.connect(host='123.56.115.207', user='zgcprice3311', password='zgcprice20200628',
#                                   database='ZI_NEW_TEST', autocommit=True)
# cursor_zi_test=conn_zi_test.cursor()
# conn_zdindex=pymssql.connect(host='123.56.115.207', user='zgcprice3311', password='zgcprice20200628',
#                                   database='zdindex', autocommit=True)
# cursor_zdindex=conn_zdindex.cursor()
#
# for index,row in df.iterrows():
#     product_id=row['产品编码']
#     product_id_correct=row['正确编码']
#     product_name_correct=row['修改状态，错误编码下报价改为正确编码，替换错误编码下商品名称']  # .split('（')[0].strip()
#
#     cursor_zi_new.execute(f"select skuname, state, sku from p_sku where sku='{product_id}'")
#     output=cursor_zi_new.fetchone()
#     # print((output))
#     # cursor_zi_test.execute(f"insert into p_sku (skuname, state, sku) values ({output[0]},{output[1]},'{product_id}')")
#     # cursor_zi_test.execute(f"select * from p_sku where sku={product_id}")
#     # out_put=cursor_zi_test.fetchall()
#     # print(out_put)
#
#     cursor_zi_new.execute(f"update p_sku set state=6, skuname='{product_name_correct}' where sku='{product_id}' ")
#     cursor_zi_new.execute(f"update Productcode_Sku set sku='{product_id_correct}' where sku='{product_id}' ")
#     cursor_zdindex.execute(f"update zd_electricity_price set goods_id='{product_id_correct}' where goods_id = '{product_id}' and periods = 20210405 ")
#     cursor_zdindex.execute(
#         f"update zd_purchase_price set goods_id='{product_id_correct}' where goods_id = '{product_id}' and periods = 20210405 ")
#     cursor_zdindex.execute(
#         f"update zd_entry_goods_price set goods_id='{product_id_correct}' where goods_id = '{product_id}' and periods = 20210405 ")
#     cursor_zdindex.execute(
#         f"update zd_week_price set goods_id='{product_id_correct}' where goods_id = '{product_id}' and periods = 20210405 ")
