# -*- 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, Q, CommodityCategoryRelation
from rpc.tool.log_tool import info_logger




class Command(BaseCommand):
    def handle(self, *args, **options):
        level1_category = CommodityCategory.objects.get(name=u'鼻部整形')
        level2_category_qs = CommodityCategory.objects.filter(Q(father_id=level1_category.id) &
                                                              ~Q(name__in=[u'鼻部综合', u'隆鼻']))
        level3_to_level2_dict = {}
        for category in level2_category_qs:
            qs = CommodityCategory.objects.filter(father_id=category.id)
            # qs = {x.get('id'): x.get('father_id') for x in qs}
            for level3 in qs:
                print(level3.id, level3.name, level3.property_info, level3.father_id)
                info_logger.info('level3 backup: {}, {}, {}, {}'.format(level3.id, level3.name, level3.property_info, level3.father_id))
                level3_to_level2_dict.update({level3.id: level3.father_id})

        print(json.dumps(level3_to_level2_dict))
        qs = CommodityCategoryRelation.objects.filter(category_id__in=list(level3_to_level2_dict.keys()))
        for relation in qs:
            relation.category_id = level3_to_level2_dict.get(relation.category_id)
            relation.save()