# -*- coding: utf-8 -*-
import json
import os

import xlrd
import xlwt
from django.core.management.base import BaseCommand
from django.conf import settings

from api.models import CommodityCategory
from rpc.tool.log_tool import info_logger


class ExcelReadTools(object):
    def __init__(self, file_path, field_list, head_title_list=None, data_starts_row_index=1, data_end_row_index=None):
        self.file_path = file_path
        self.field_list = field_list
        self.head_title_list = head_title_list
        self.data_starts_row_index = data_starts_row_index

        self.workbook = xlrd.open_workbook(self.file_path)
        self.sheet = self.workbook.sheet_by_index(0)
        self.data_end_row_index = data_end_row_index if data_end_row_index else self.sheet.nrows

    def iter_rows(self, LIMIT=None):
        for row_idx in range(self.data_starts_row_index, self.data_end_row_index):
            row_values = self.sheet.row_values(row_idx)
            item_dict = {}
            for field_name, value in zip(self.field_list, row_values):
                if field_name == '_':
                    continue
                item_dict.update({field_name: str(value or '').strip()})
            yield item_dict

    def get_row_value(self, row_idx):
        row_values = self.sheet.row_values(row_idx)
        item_dict = {}
        for field_name, value in zip(self.field_list, row_values):
            if field_name == '_':
                continue
            item_dict.update({field_name: str(value or '').strip()})
        return item_dict


def to_property_brand_dict(property_brand):
    if not property_brand:
        return {}
    level3_list = map(str.strip, property_brand.split())
    return {"1": [], "2": [], "3": level3_list}


def create_or_update_for_row(row, delete_child):
    level3_value = row.get('level3').strip()
    level3_name_list = level3_value.split()
    if not level3_name_list:
        level_list = [row.get('level1'), row.get('level2')]
    elif len(level3_name_list) > 1:
        level_list = [row.get('level1'), row.get('level2')]
    else:
        level_list = [row.get('level1'), row.get('level2'), level3_name_list[0]]

    property_brand = to_property_brand_dict(row.get('property_brand'))

    # 创建catetory
    parent_category = None
    for level_name in level_list:
        query_conditions = dict(name=level_name)
        if parent_category:
            query_conditions.update(father_id=parent_category.id)
        else:
            query_conditions.update(father_id=0)
        category = CommodityCategory.objects.filter(**query_conditions).first()

        if not category:
            category = CommodityCategory.objects.create(**query_conditions)
            info_logger.info('create category: %r, father_id: %r', category.id, parent_category.id)

        parent_category = category

    # 给叶子类目添加property
    # print(json.dumps(level3_name_list))
    # print(parent_category, parent_category.id)
    if len(level3_name_list) > 1:
        # 此时parent_category是level2的对应的category
        level2_catetory = parent_category
        for level_name in level3_name_list:
            query_conditions = dict(name=level_name, father_id=level2_catetory.id)
            category = CommodityCategory.objects.filter(**query_conditions).first()
            if not category:
                category = CommodityCategory.objects.create(**query_conditions)
                info_logger.info('create category level3: %r, father_id: %r',
                                 category.id, parent_category.id)
            else:
                info_logger.info('exists category level3: %r, father_id: %r',
                                 category.id, parent_category.id)
            category.property_info = json.dumps(property_brand) if property_brand else ''
            category.save()
    else:
        # parent_category是叶子节点，可能是level2, 也可能是level3
        if len(level3_name_list) == 1:
            # 有level3, 此时parent_category 是level3的catetory
            parent_category.property_info = json.dumps(
                property_brand) if property_brand else ''
            parent_category.save()
        else:
            # 只有level2, 没有level3,此时parent_category 是level2的catetory
            rows = CommodityCategory.objects.filter(father_id=parent_category.id) \
                .delete()
            info_logger.info('delete rows: %r, father_id: %r, parent_name: %r',
                             rows, parent_category.id, parent_category.name)

            parent_category.property_info = json.dumps(
                property_brand) if property_brand else ''
            parent_category.save()


class Command(BaseCommand):
    def handle(self, *args, **options):
        GAIA_PROJECT_ROOT_PATH = settings.BASE_DIR
        file_path = os.path.join(GAIA_PROJECT_ROOT_PATH, 'commodity_category.xlsx')

        head_title_list = ['level1', 'level2', 'level3', '_', '_', '_', 'property_brand']
        read_tools = ExcelReadTools(file_path, head_title_list, data_starts_row_index=87, data_end_row_index=96)
        for row in read_tools.iter_rows():
            # print(row.get('level2'))
            create_or_update_for_row(row, delete_child=True)