# coding=utf-8


import re
from django.core.management import BaseCommand

from api.models.service import Service, AttrOptions

WHILTE_LIST = [u'{', u'}', u'\uff08', u'\uff09', u'\u2014\u2014', u'\uff01', u'\u3001', u'\uff0c', u'\u3002', u'\uff1f',
               u'\uff1a', u'\uff1b', u'\u201c', u'\u201d', u'\u2018', u'\u2019', u'\u300a', u'\u300b', u'\xb7',
               u'\uffe5', u'/', u'[', u']', u'(', u')', u'-', u'!', u',', u'.', u'?', u':', u';', u'"', u"'", u'$',
               u'*', u'+', u'\uff1e', u'\u2265', u'<', u'\u2264', u'=', u'%', u'\u2030', u'~', u'@', u'\u2160',
               u'\u2161', u'\u2162', u'\u2163', u'\u2164', u'\u2165', u'\u2166', u'\u2167', u'\u2168', u'\u2169',
               u'\u3010', u'\u3011']


def generate_uncode(lst):
    """
    将特殊字符编码为unicode编码
    :param lst:
    :return:
    """
    unicode_list = []
    for char in lst:
        unicode_list.append(unicode(char, 'utf-8'))
    return unicode_list


def is_uchar(uchar):
    """判断一个unicode是否是汉字"""

    if u'\u4e00' <= uchar <= u'\u9fa5':
        return True

    """判断一个unicode是否是数字"""
    if u'\u0030' <= uchar <= u'\u0039':
        return True

    """判断一个unicode是否是英文字母"""
    if (u'\u0041' <= uchar <= u'\u005a') or (u'\u0061' <= uchar <= u'\u007a'):
        return True

    if uchar in WHILTE_LIST:
        return True

    return False


def replace_special_char(s):
    if not s:
        return None

    char_str = ''
    for char in s:
        if is_uchar(char):
            char_str += char
        else:
            char_str += ' '

    return re.sub(r"\s{2,}", " ", char_str)


def modify_spu_name():
    service_ids = Service.objects.filter(is_online=True).values_list('id', flat=True)
    for service_id in service_ids:
        s = Service.objects.get(pk=service_id)
        short_description = s.short_description
        if not short_description:
            continue
        try:
            short_description = replace_special_char(short_description)
            s.short_description = short_description
            s.save()
        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)
    for attr_id in attr_ids:
        u = AttrOptions.objects.get(pk=attr_id)
        name = u.name
        if not name:
            continue
        try:
            ret_name = replace_special_char(name)
            u.name = ret_name
            u.save()
        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('开始处理美购名称......')
        modify_sku_name()
        print('处理完毕!')

