#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "chenwei"
# Date: 2019/5/30
import json
from django.db.models import Q
from django.conf import settings
from api.models.doctor import Doctor
from django.core.management import BaseCommand

from api.models import Service, ServiceItem, ServiceItemKey, AttrOptions

replace_dict = {
    u"私密超声刀": u"私密超声紧致",
    u"超声刀": u"超声提升",
}

class Command(BaseCommand):

    def handle(self, *args, **kwargs):
        print("start to amend service name")

        service_amend_info = {}
        print("------------start to amend service info------------")
        for w, f in replace_dict.iteritems():
            for s in Service.objects.using(settings.SLAVE_DB_NAME).filter(Q(name__contains=w) | Q(short_description__contains=w)):
                service_amend_info[s.id] = {'name': s.name, "short_description": s.short_description}
                print(u'origin: [{id}]:[{name}]:[{short_description}]'.format(id=s.id, name=s.name,
                                                                              short_description=s.short_description))
                s.name = s.name.replace(w, f)
                if s.short_description:
                    s.short_description = s.short_description.replace(w, f)
                s.save()
                print(u'replace: [{id}]:[{name}]:[{short_description}]'.format(id=s.id, name=s.name,
                                                                               short_description=s.short_description))
        print("------------end amend service info------------")

        print("------------start to AttrOptions info------------")

        options_info = {}
        service_item_ids = list(ServiceItem.objects.using(settings.SLAVE_DB_NAME).values_list("id", flat=True))
        serviceattroption_ids = list(ServiceItemKey.objects.using(settings.SLAVE_DB_NAME).filter(serviceitem_id__in=service_item_ids).values_list("serviceattroption_id", flat=True))
        for w, f in replace_dict.iteritems():
            for op in AttrOptions.objects.filter(Q(id__in=serviceattroption_ids) & Q(name__contains=w)):
                print(u'origin: [{id}]:[{name}]'.format(id=op.id, name=op.name))
                options_info[op.id] = op.name
                op.name = op.name.replace(w, f)
                op.save()
                print(u'replace: [{id}]:[{name}]'.format(id=op.id, name=op.name))

        print("------------end AttrOptions info------------")


        print("------------start to write log------------")

        write_str = json.dumps(service_amend_info) + '\\n' + json.dumps(options_info)

        with open("replace-names.log", "w+") as f:
            f.write(write_str)

        print("------------------write log end ------------------------")
