# -*- coding: utf-8 -*-
from django.conf import settings
from django.core.management import BaseCommand
from django.db.utils import IntegrityError
from django.db import connection

from api import Service
from api.models import ServiceRegisterItem, ServiceItemPrice, CommodityCategoryRelation, \
    CommodityCategoryPropertyRelation, AttrOptions, ServiceRegisterItemKey, Tag
from rpc.tool.log_tool import info_logger


def fix_service(service):
    service_item_qs = service.items.filter(is_delete=False)
    for service_item in service_item_qs:
        service_register_item = ServiceRegisterItem.objects.filter(serviceitem=service_item).first()
        if service_register_item:
            info_logger.info(r'fix_service: register_item exists, %r, %r', service.id, service_register_item.id)
            continue
        
        item_price = ServiceItemPrice.objects.filter(service_item=service_item, is_enable=True).first()
        item_dict = {}
        item_dict['discount'] = item_price.discount
        item_dict['pre_payment_price'] = item_price.pre_payment_price
        item_dict['pre_payment_price_int'] = item_price.pre_payment_price
        item_dict['original_price'] = item_price.original_price
        item_dict['gengmei_price'] = item_price.gengmei_price
        item_dict['cash_back_rate'] = item_price.cash_back_rate
        item_dict['cash_back_fee'] = item_price.cash_back_fee
        item_dict['is_online'] = True
        item_dict['sort'] = service_item.sort
        item_dict['stock_add_num'] = service_item.sku_stock
        item_dict['serviceitem'] = service_item
        item_dict['sku_description'] = service_item.sku_description
        # points_deduction_percent
        # item_dict['points_deduction_percent'] = service.points_deduction_percent

        service_register = service.servicereg.order_by('-created_time').first()
        item_dict['service_register'] = service_register

        service_register_item = ServiceRegisterItem.objects.create(**item_dict)
        tag = service.project_type
        opt = AttrOptions.objects.create(
            tag_attr_id=settings.DEFAULT_TAG_ATTR_ID,
            name=tag.name, is_online=True)
        ServiceRegisterItemKey.objects.create(
            serviceregisteritem=service_register_item, serviceregisterattroption=opt)

        # 组装类目信息
        category_relation = CommodityCategoryRelation.objects.filter(
            commodity_id=service_item.id).first()
        if category_relation:
            category_relation.commodity_register_id = service_register_item.id
            category_relation.save()

        category_property_relations = CommodityCategoryPropertyRelation.objects.filter(
            commodity_id=service_item.id)
        if category_property_relations:
            category_property_relations.commodity_register_id = service_register_item.id
            category_property_relations.save()

        info_logger.info('fix_service: create register_item, %r, %r, %r', service.id,
                         service_item.id, service_register_item.id)


class Command(BaseCommand):
    def add_arguments(self, parser):
        parser.add_argument(
            '-service_id', dest="service_id",
            help="service_id",
            type=int,
            required=False
        )

    def handle(self, *args, **options):
        service_id = options['service_id']
        if service_id:
            service = Service.objects.filter(id=service_id).first()
            if not service:
                info_logger.info(r'fix_service: service not exists, %r', service_id)
                return
            fix_service(service)
            return

        # fix_all
        service_qs = Service.objects.filter(is_delete=False)
        for service in service_qs:
            fix_service(service)


