import json
from utils.base import APIView, get_offset_count
from utils.logger import error_logger


class BrandListView(APIView):

    def get(self, request):
        offset, count = get_offset_count(request)
        cn_name = request.GET.get('cn_name', None)
        id_ = request.GET.get('id', None)
        has_area = request.GET.get('has_area', None)
        is_online = request.GET.get('is_online', None)
        has_icon = request.GET.get('has_icon', None)
        classify_id = request.GET.get('classify_id', None)

        data = self.rpc['neptune/commodity/brand/list'](
            offset=offset, count=count, cn_name=cn_name, id_=id_, has_area=has_area, 
            is_online=is_online, has_icon=has_icon, classify_id=classify_id).unwrap()
        brand_ids = [obj.get('id') for obj in data]

        brands_grade = self.rpc['neptune/commodity/brand/grade'](ids=brand_ids).unwrap()
        grade_dict = {str(obj.get('brand_id')): obj.get('grade') for obj in brands_grade}

        product_count = self.rpc['neptune/commodity/brand/product_count'](ids=brand_ids).unwrap()

        category_infos = self.rpc['neptune/commodity/category/infos'](brand_ids=brand_ids).unwrap()
        category_dict = {}
        if category_infos:
            for obj in category_infos:
                obj_id = obj.get('brand_id')
                if category_dict.get(str(obj_id)):
                    category_dict.get(str(obj_id)).append(obj)
                else:
                    category_dict[str(obj_id)] = [obj]

        classify_infos = self.rpc['neptune/commodity/classify/infos'](brand_ids=brand_ids).unwrap()
        classify_dict = {str(obj.get('brand_id')): obj for obj in classify_infos} if classify_infos else {}
        
        for obj in data:
            brand_id = obj.get('id')
            obj['product_num'] = product_count.get(str(brand_id)) or 0
            
            category_info_list = category_dict.get(str(brand_id))
            obj['category_infos'] = [{'id': obj.get('id'), 'cn_name': obj.get('cn_name')} for obj in category_info_list] if category_info_list else []
            
            obj['grade'] = grade_dict.get(str(brand_id)) if grade_dict.get(str(brand_id)) else 0

            classify_info = classify_dict.get(str(brand_id))
            obj['classify_info'] = [{'id': classify_info.get('id'), 'cn_name': classify_info.get('cn_name')}] if classify_info else []

            obj.pop('platform')

        total = self.rpc['neptune/commodity/brand/count'](
            cn_name=cn_name, id_=id_, has_area=has_area, is_online=is_online, has_icon=has_icon,
            classify_id=classify_id).unwrap()
        result = {
            'list': data,
            'total': total,
        }

        return result


class BrandInfoView(APIView):
    
    def get(self, request):
        id_ = request.GET.get('id')

        data = self.rpc['neptune/commodity/brand/info'](id_=id_).unwrap()
        classify_infos = self.rpc['neptune/commodity/classify/infos'](brand_ids=[id_]).unwrap()
        data['classify_infos'] = [{'id': obj.get('id'), 'cn_name': obj.get('cn_name')} for obj in classify_infos] if classify_infos else []
        category_ids = self.rpc['neptune/commodity/brand/category_ids'](id_=id_).unwrap()
        category_infos = self.rpc['neptune/commodity/category/infos'](ids=category_ids).unwrap()
        data['category_infos'] = [{'id': obj.get('id'), 'cn_name': obj.get('cn_name')} for obj in category_infos] if category_infos else []
        return data


class BrandCreateView(APIView):

    def post(self, request):
        cn_name = request.POST.get('cn_name')
        icon = request.POST.get('icon', '')
        en_name = request.POST.get('en_name', None)
        alias = request.POST.get('alias', None)
        area = request.POST.get('area', None)
        classify_id = request.POST.get('classify_id', None)
        category_ids = json.loads(request.POST.get('category_ids', '[]'))
        description = request.POST.get('description', None)
        is_online = request.POST.get('is_online', False)

        if not cn_name or not classify_id:
            return r'缺少参数'

        data = self.rpc['neptune/commodity/brand/create'](
            cn_name=cn_name, icon=icon, en_name=en_name, alias=alias, area=area, 
            classify_id=classify_id, description=description,
            is_online=is_online).unwrap()
        brand_id = data.get('id')

        self.rpc['neptune/commodity/brand/batch_add_categorys'](
            id_=brand_id, category_ids=category_ids).unwrap()

        return data

    
class BrandUpdateView(APIView):

    def post(self, request):
        id_ = request.POST.get('id', None)
        cn_name = request.POST.get('cn_name', None)
        en_name = request.POST.get('en_name', None)
        alias = request.POST.get('alias', None)
        area = request.POST.get('area', None)
        icon = request.POST.get('icon', None)
        description = request.POST.get('description', None)
        is_online = request.POST.get('is_online', None)
        classify_id = request.POST.get('classify_id', None)
        category_ids = json.loads(request.POST.get('category_ids', '[]'))

        if not id_:
            return r'缺少参数'

        data = self.rpc['neptune/commodity/brand/update'](
            id_=id_, cn_name=cn_name, en_name=en_name, alias=alias, area=area, icon=icon, 
            description=description, is_online=is_online, classify_id=classify_id).unwrap()

        self.rpc['neptune/commodity/brand/batch_add_categorys'](
            id_=id_, category_ids=category_ids).unwrap()

        return data
