# coding=utf-8


import json
from django.core.management import BaseCommand

from api.models.service import Service, AttrOptions, ServiceItem
from utils.execel import ExcelReader
from openpyxl import load_workbook

excel_name = './modify_sku_name.xlsx'


column_config = {
    u'注射美肤': {'sku_id':8, 'sku_name': 19},
    u'皮肤美容': {'sku_id':9, 'sku_name': 20},
    u'抗衰紧致': {'sku_id':10, 'sku_name': 21}
}



def process(e_reader):
    '''
    处理函数
    '''
    sheetnames = e_reader._excel.sheetnames
    for stn in sheetnames:
        process_sheet(e_reader, stn)


def process_sheet(e_reader, sheet_name):
    '''
    处理单个sheet
    '''
    print('begin to process sheet[%s]' % sheet_name)
    columns = column_config.get(sheet_name)
    id_column = columns.get('sku_id')
    name_column = columns.get('sku_name')
    if not columns:
        print('sheet_name[%s] can not find column_config, failed' % sheet_name)
        return
    
    e_reader.sheet_select_by_name(sheet_name)
    rn = e_reader.row_number
    sku_id_name_list = []
    for r in range(1, rn+1):
        try:
            sku_id = int(e_reader._cell(r, id_column).value)
            sku_name = (e_reader._cell(r, name_column).value or '').strip()
            if sku_id and sku_name:
                sku_id_name_list.append([sku_id, sku_name])
        except:
            pass

    print('todo sku_list: \n %s' % json.dumps(sku_id_name_list, ensure_ascii=False))
    update_sku_names(sku_id_name_list)
    print('finished processing sheet[%s]' % sheet_name)


def update_sku_names(sku_id_name_list):
    i = 0
    for id_name in sku_id_name_list:
        s_id, s_name = id_name
        ServiceItem.update_sku_name(s_id, s_name)
        i += 1
        if i%1000 == 0:
            print('batch update (%s)sku successfully' % i)


class Command(BaseCommand):
    """
    short_description，AttrOptions--name
    """
    def handle(self, *args, **kwargs):
        print('开始处理......')
        e_reader = ExcelReader(excel_name)
        e_reader._excel = load_workbook(excel_name, data_only=True)
        process(e_reader)
        print('处理完毕!')

