# coding=utf-8


import re
from django.core.management import BaseCommand

from api.models.service import Service, AttrOptions


rp = re.compile(u'\u4e13\u5229')


def fmt_content(s):
    if not s:
        return s

    res = rp.sub('', s)
    return res


def modify_spu_name():
    service_ids = Service.objects.filter(is_online=True).values_list('id', flat=True)
    cnt = 0
    for service_id in service_ids:
        s = Service.objects.get(pk=service_id)
        short_description = s.short_description
        if not short_description:
            continue
        try:
            new_short_description = fmt_content(short_description)
            if new_short_description == short_description:
                continue
            s.short_description = new_short_description
            s.save()
            cnt += 1
            if cnt % 10 == 0:
                print('process %s spu_name... at spu(%s)' % (cnt, s.id))
        except Exception:
            print('spu: {service_id}, 替换失败....'.format(service_id=service_id))


def modify_sku_name():
    attr_ids = AttrOptions.objects.filter(is_online=True).values_list('id', flat=True)
    cnt = 0
    for attr_id in attr_ids:
        u = AttrOptions.objects.get(pk=attr_id)
        name = u.name
        if not name:
            continue
        try:
            ret_name = fmt_content(name)
            if ret_name == name:
                continue
            u.name = ret_name
            u.save()
            cnt += 1
            if cnt % 10 == 0:
                print('process %s sku_name...' % cnt)
        except Exception:
            print('spu: {attr_id}, 替换失败....'.format(attr_id=attr_id))


class Command(BaseCommand):
    """
    short_description，AttrOptions--name
    """
    def handle(self, *args, **kwargs):
        print('开始处理项目描述......')
        modify_spu_name()
        print('处理完毕!')

        print('开始处理sku名称......')
        modify_sku_name()
        print('处理完毕!')

