# coding=utf-8
import pipes
import shlex
import sys
import traceback

from django.core.management import BaseCommand
from django.db import transaction
from django.db import connection

from api.models import Order, Service, ServiceItem, ServiceItemPrice
from pay.models import ServiceSnapshot

from django.db import models
from api.tool.service_tool import get_serviceitem_by_option_id

import json


class OldServiceItem(models.Model):
    class Meta:
        verbose_name = u'福利'
        verbose_name_plural = u'福利'
        db_table = 'api_serviceitem'
        app_label = 'api'

    key = models.CharField(max_length=40, verbose_name=u"标识符")

    # from Item
    discount = models.IntegerField(verbose_name=u'抽成', default=0)
    pre_payment_price = models.IntegerField(verbose_name=u'预付款', default=999999)
    original_price = models.IntegerField(verbose_name=u'市场价', default=999999)
    gengmei_price = models.IntegerField(verbose_name=u'更美价', default=999999)
    cash_back_rate = models.IntegerField(verbose_name=u'返现百分比', default=10)
    cash_back_fee = models.IntegerField(verbose_name=u'返现金额', default=0)
    self_support_discount = models.IntegerField(verbose_name=u'自营抽成', default=0)
    # from Item


class Command(BaseCommand):
    def add_arguments(self, parser):
        parser.add_argument('--id-start', type=int)
        parser.add_argument('--id-end', type=int)
        parser.add_argument('--make-slices', type=int, default=None)

    def handle(self, *args, **options):
        make_slices = options.get('make_slices')
        if make_slices is not None:
            slices = self.get_slices(make_slices)
            for start, end in slices:
                cmdline = list(sys.argv)
                idx = cmdline.index('--make-slices')
                assert idx >= 0
                cmdline = cmdline[:idx]
                if start is not None:
                    cmdline.extend([
                        '--id-start', str(start),
                    ])
                if end is not None:
                    cmdline.extend([
                        '--id-end', str(end),
                    ])
                print(' '.join(pipes.quote(s) for s in cmdline))
        else:
            id_start = options.get('id_start')
            id_end = options.get('id_end')
            self.handle_range(id_start=id_start, id_end=id_end)

    def get_slices(self, count):
        expected_max_id = 90000
        sep_points = [None]
        for p in range(1, count):
            sep_points.append(int(expected_max_id / count * p))
        sep_points.append(None)
        return zip(sep_points[:count], sep_points[1:])

    def handle_range(self, id_start=None, id_end=None):
        qs = OldServiceItem.objects.all()
        if id_start is not None:
            qs = qs.filter(id__gte=id_start)
        if id_end is not None:
            qs = qs.filter(id__lt=id_end)
        qs = qs.order_by('id')

        sss = list(qs.values_list('id', flat=True))

        import datetime
        log_name_base = "sku161212_create_price_" + datetime.datetime.now().strftime('%Y%m%d_%H%M%S_%f')
        log_error_name = log_name_base + '_error.log'
        log_name = log_name_base + '_info.log'

        with open(log_error_name, 'a+') as error_log_file:
            with open(log_name, 'a+') as log_file:

                header_text = "range : [{}, {})\ncount : {}".format(id_start, id_end, len(sss))
                print header_text

                log_file.write(header_text)
                log_file.write('\n')

                i = 0

                for siid in sss:
                    i += 1
                    if i % 1000 == 0:
                        print "on index {}/{} siid: {}".format(i, len(sss), siid)

                    try:
                        with transaction.atomic():
                            si = ServiceItem.objects.get(id=siid)
                            oldsi = OldServiceItem.objects.get(id=siid)

                            d_info = si.get_default_price_info()

                            if not d_info:
                                si.create_price(
                                    sale_limit=2,  # 实际上会被内部改成999999.因为is_default_price=True
                                    is_default_price=True,
                                    selling_rule_id=None,
                                    discount=oldsi.discount,
                                    pre_payment_price=oldsi.pre_payment_price,
                                    original_price=oldsi.original_price,
                                    gengmei_price=oldsi.gengmei_price,
                                    cash_back_rate=oldsi.cash_back_rate,
                                    cash_back_fee=oldsi.cash_back_fee,
                                    self_support_discount=oldsi.self_support_discount,
                                    single_user_buy_limit=0,
                                )
                                log_text = "create price for service_item: " + str(siid)

                                log_file.write(log_text)
                                log_file.write('\n')

                    except:
                        error_text = traceback.format_exc()

                        error_log_file.write(error_text)
                        error_log_file.write('\n')

                # select p.id as p_id from api_serviceitem s left join api_serviceitemprice p on p.service_item_id = s.id where p.id IS NULL; 用来验证有没有漏网之鱼
                print "success!"

                log_file.write("success!")
                log_file.write('\n')
