# coding=utf-8
from django.core.management import BaseCommand
from api.models import Service, ServiceTag
from gm_types.gaia import TAG_TYPE
from django.db.models import Q
from rpc.tool.log_tool import info_logger
from django.db import transaction


class Command(BaseCommand):
    def handle(self, *args, **options):
        with transaction.atomic():
            service_obj_list = Service.objects.filter()
            for single_service in service_obj_list:
                old_tags_list = single_service.tags.filter(~Q(tag_type=TAG_TYPE.YUNYING))
                if old_tags_list.count() > 1 or old_tags_list.count() == 0:
                    print single_service.id
                    info_logger.info('service_id----{}-----ServiceTag-------delete'.format(single_service.id))
                    info_logger.info(old_tags_list)

                    q = Q(service=single_service) & (~Q(tag__tag_type=TAG_TYPE.YUNYING))
                    ServiceTag.objects.filter(q).delete()
                    if single_service.project_type:
                        ServiceTag.objects.create(service_id=single_service.id,
                                                  tag_id=single_service.project_type.id)
                        info_logger.info('service_id----{}-----ServiceTag-------create-----tag_id----{}'.
                                         format(single_service.id, single_service.project_type.id))
                else:
                    if single_service.project_type and old_tags_list and old_tags_list[0]:
                        if old_tags_list[0].id != single_service.project_type.id:
                            print single_service.id
                            info_logger.info('service_id----{}-----ServiceTag-------delete'.format(single_service.id))
                            info_logger.info(old_tags_list)

                            q = Q(service=single_service) & (~Q(tag__tag_type=TAG_TYPE.YUNYING))
                            ServiceTag.objects.filter(q).delete()
                            if single_service.project_type:
                                ServiceTag.objects.create(service_id=single_service.id,
                                                          tag_id=single_service.project_type.id)
                                info_logger.info('service_id----{}-----ServiceTag-------create-----tag_id----{}'.
                                                 format(single_service.id, single_service.project_type.id))



