#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 23 00:36:24 2021

@author: rico
"""

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

def get_point_category_params_data(category):

    category_sheet_name = category.replace("/","_")
    #创建产品库链接
    try:
        conn_zi_new = pymssql.connect(host='172.17.9.129', user='zgcprice3311',password='zgcprice20200628',database= 'ZI_NEW',autocommit=True)
        cursor = 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 = 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()
    
    cursor.execute(f"select id,name from p_category where id not in (select distinct pid from p_category) and name in ('{category}')")
    
    data = (cursor.fetchall())
    export_category = pd.DataFrame(data,columns=[tuple[0] for tuple in cursor.description])
    
    date = str(datetime.datetime.now()).split(' ')[0]
    
    writer = pd.ExcelWriter(f"{category_sheet_name}参数确认{date}.xlsx")
    
    for category_code,category_name in zip(export_category['id'].tolist(),export_category['name'].tolist()):
        
        print(f"开始提取{category_name}参数数据")

        #获取产品信息
        cursor.execute(f"select a.*,h.name as father_brand_name,d.name as brand_name,g.name as attr_name,f.value from p_sku a \
                       left join p_spu b \
                       on a.spuid = b.id \
                       left join p_category c \
                       on b.categoryid = c.id \
                       left join p_brand d \
                       on b.brandid = d.id \
                       left join p_skuvaluemap e \
                       on a.id = e.skuid \
                       left join p_skuvalue f \
                       on e.valueid = f.id \
                       left join p_skusubtitle g \
                       on f.subtitleid = g.id \
                       left join p_brand h \
                       on d.pid = h.id \
                       where b.categoryid = {category_code} and a.state in (1,2,4)")
        data = (cursor.fetchall())
        df_sku = pd.DataFrame(data,columns=[tuple[0] for tuple in cursor.description])
        
        cursor.execute(f"select a.*,d.name as brand_name,g.name as attr_name,f.value from p_sku a \
                   left join p_spu b \
                   on a.spuid = b.id \
                   left join p_category c \
                   on b.categoryid = c.id \
                   left join p_brand d \
                   on b.brandid = d.id \
                   left join p_valuemap e \
                   on b.id = e.spuid \
                   left join p_value f \
                   on e.valueid = f.id \
                   left join p_subtitle g \
                   on f.subtitleid = g.id \
                   where b.categoryid = {category_code} and a.state in (1,2,4)")
        data = (cursor.fetchall())
        df_spu = pd.DataFrame(data,columns=[tuple[0] for tuple in cursor.description])
        
        res = pd.DataFrame()
        id_list = []
        spu_id_list = []
        state_list = []
        product_name_list = []
        father_brand_list = []
        brand_list = []
        category_list = []
        #param_list
        
        cursor.execute(f"select * from vw_property where categoryid = {category_code}")
        data = cursor.fetchall()
        params_df = pd.DataFrame(data, columns=[tuple[0] for tuple in cursor.description])
        params_df['needed_param'] = params_df['identy'].apply(lambda x: x[0])
        params_df['match_param'] = params_df['identy'].apply(lambda x: x[1])
        params_df['standard_param'] = params_df['identy'].apply(lambda x: x[2])
        
        params_df = params_df[(params_df['needed_param'] != '0') | (params_df['skuorspu'] == 'spu')]
        params_df['subtitle'] = params_df['subtitle'].apply(lambda x: x.strip())
        

        param_list = params_df['subtitle'].tolist()
        for param in param_list:
            param_var = '_' + ''.join(param.split()).replace('（','').replace('）','').replace('/','').replace('(','').replace(')','').replace('+','').replace('-','').replace('*','').replace('.','')
            exec('%s_list=[]'%param_var)
    
                
        
        process_index = 0
        index = Index()
        
        for prodcut_id in list(df_sku['sku'].unique()):
            
            try:
                print(index(process_index,len(list(df_sku['sku'].unique()))-1), end='%')
            except:
                print(index(process_index,1), end='%')
            process_index+=1
            
            id_list.append(prodcut_id)
            spu_id_list.append(df_sku[df_sku['sku'] == prodcut_id]['spuid'].tolist()[0])
            state_list.append(df_sku[df_sku['sku'] == prodcut_id]['state'].tolist()[0])
            product_name_list.append(df_sku[df_sku['sku'] == prodcut_id]['skuname'].tolist()[0])
            
            father_brand_list.append(df_sku[df_sku['sku'] == prodcut_id]['father_brand_name'].tolist()[0])
            brand_list.append(df_sku[df_sku['sku'] == prodcut_id]['brand_name'].tolist()[0])
            
            category_list.append(category_name)
            
            for param in param_list:
                param_var = '_' + ''.join(param.split()).replace('（','').replace('）','').replace('/','').replace('(','').replace(')','').replace('+','').replace('-','').replace('*','').replace('.','')
                try:
                    exec("%s_list.append(df_sku[(df_sku['sku'] == prodcut_id) & (df_sku['attr_name'] == '%s')]['value'].tolist()[0])"%(param_var,param))
                except:
                    try:
                        exec("%s_list.append(df_spu[(df_spu['sku'] == prodcut_id) & (df_spu['attr_name'] == '%s')]['value'].tolist()[0])"%(param_var,param))
                    except:
                        exec("%s_list.append('无参数，需补充')"%param_var)


        res['产品编码'] = id_list
        res['SPUID'] = spu_id_list
        res['产品状态'] = state_list
        res['产品名称'] = product_name_list
        res['产品父品牌'] = father_brand_list
        res['产品品牌'] = brand_list
        res['产品类别'] = category_list
        
        filter_params_col_list = []
        for index,row in params_df.iterrows():
            param = row['subtitle']
            needed_flag = row['needed_param']
            match_flag = row['match_param']
            standard_flag = row['standard_param']
            
            if param == '产品名称':
                continue
            
            param_var = '_' + ''.join(param.split()).replace('（','').replace('）','').replace('/','').replace('(','').replace(')','').replace('+','').replace('-','').replace('*','').replace('.','')

            #标记标准项
            if needed_flag == '1' and standard_flag == '1':
                param = '*' + param
            #if match_flag == '1':
            #    param = '*' + param
            #    filter_params_col_list.append(param)
                

            exec("res['%s']=%s_list"%(param,param_var))
        '''
        url_list = []
        goods_model_list = []
        process_index = 0
        index = Index()
        for index_,row in res.iterrows():
            try:
                print(index(process_index,len(res)-1), end='%')
            except:
                print(index(process_index,1), end='%')
            process_index+=1
            sku = str(row['产品编码'])

            cursor_zdindex.execute(f"select goods_model,goods_url from zd_purchase_price where goods_id = '{sku}' and periods in (select top 1 max(periods) from zd_entry_goods_price) and purchase_id = 'ZC-HEILONGJIANG'")
            try:
                goods_model,url = tuple(cursor_zdindex.fetchone())
            except:
                
                goods_model,url = '无','无'
            url_list.append(url)
            
            goods_model_list.append(goods_model)
        res['黑龙江采购商品名称'] = goods_model_list
        res['链接'] = url_list
        '''
            
    
        res.to_excel(writer,f"{category_sheet_name}参数数据")
        
        '''
        cursor_zdindex.execute(f"select a.goods_id,a.goods_name,b.goods_name as '链接名称',a.platform_id,a.goods_url,a.index_price_wave,a.final_price from zd_week_price a \
                                    left join (select goods_id,goods_name from zd_purchase_price where periods = '20211216') b \
                                    on a.goods_id = b.goods_id \
                                    where a.periods = '20211216' and a.sub_category_code = {category_code}")
        '''
        cursor_zdindex.execute(f"select goods_id,goods_name,source_goods_name,platform_id,goods_url,index_price_wave,final_price from zd_week_price \
                                    where periods in (select top 1 max(periods) from zd_entry_goods_price) and sub_category_code = {category_code}")
        data = (cursor_zdindex.fetchall())
        price_df = pd.DataFrame(data,columns=[tuple[0] for tuple in cursor_zdindex.description])
        price_df.to_excel(writer,f"{category_sheet_name}价格链接数据")
        
        
        
        '''
        filter_res = res[list(res.columns)[0:7] + filter_params_col_list]
        combine_df = pd.merge(price_df,filter_res,left_on = 'goods_id',right_on = '产品编码',how='left')
        combine_df['指数型号不在原始名称中'] = [1 if str(model).strip().upper() not in str(name).upper() else 0 for model,name in zip(combine_df['*产品型号'].tolist(),combine_df['source_goods_name'].tolist())]
        combine_df.to_excel(writer,f"{category_sheet_name}数据合并")
        print(f"{category_name}数据导出完毕！")
        '''
        
    writer.save()
    conn_zi_new.close()


category_list = category_list = ['复印纸']
for category in category_list:
    get_point_category_params_data(category)