# coding=utf-8
# author: oldman
import json
import traceback

from datetime import datetime
from django.core.management import BaseCommand
import tablib
from django.db import transaction

from api.models import Coupon, CouponDoctorRestrict, CouponSpecialRestrict


@transaction.atomic
def handle_data(coupon):
    if coupon.condition:
        conditions = json.loads(coupon.condition)
    else:
        conditions = {}
    if conditions.get('prepay_threshold') == '':
        coupon.has_threshold = False
        coupon.prepay_threshold = 0
    else:
        coupon.has_threshold = int(conditions.get('prepay_threshold', 0)) > 0
        coupon.prepay_threshold = int(conditions.get('prepay_threshold', 0))
    coupon.discount_limit = conditions.get('discount_limit', False)
    coupon.seckill_avail = conditions.get('seckill_avail', False)
    coupon.is_doctor_new = False
    coupon.activated_time = datetime.now()
    #     todo 专题
    #     todo 医生
    if coupon.doctor:
        coupon_doctor = CouponDoctorRestrict.objects.create(doctor_id=coupon.doctor.id,
                                                            coupon_id=coupon.id
                                                            )
        coupon_doctor.save()
        coupon.is_doctor_new = True
    if conditions.get('specials', []):
        for item in conditions.get('specials'):
            coupon_special = CouponSpecialRestrict.objects.create(special_id=item, coupon_id=coupon.id)
            coupon_special.save()
    coupon.announcement = u''
    coupon.save()


class Command(BaseCommand):
    """
    同步美券的数据 python manage.py deal_with_old_coupon_data -n coupon_id
    """

    def add_arguments(self, parser):
        parser.add_argument('-n',
                            '--num',
                            dest='coupon_id',
                            help='coupon id'
                            )

    def handle(self, *args, **options):
        if options['coupon_id']:
            coupons = Coupon.objects.filter(pk=options['coupon_id'])
        else:
            coupons = Coupon.objects.filter()
        dt_data = tablib.Dataset()
        dt_data.headers = ['id', 'name', 'value', 'total', 'start_time', 'end_time', 'announcement', 'condition',
                           'campaign_id',
                           'is_recommand',
                           'recommand_ordering', 'claim_end_time', 'is_new_user', 'doctor_id', 'status']
        print coupons.count()
        for item in coupons:
            # todo 记录原始数据
            row = []
            row.append(item.id)
            row.append(item.name)
            row.append(item.value)
            row.append(item.total)
            row.append(item.start_time)
            row.append(item.end_time)
            row.append(item.announcement)
            row.append(u'' if item.condition is None else item.condition)
            row.append(u'' if item.campaign is None else item.campaign.id)
            row.append(item.is_recommend)
            row.append(item.recommand_ordering)
            row.append(item.claim_end_time)
            row.append(item.is_new_user)
            row.append(u'' if item.doctor is None else item.doctor.id)

            try:
                handle_data(item)
                row.append('success')
                dt_data.append(row)
                print u'{0}执行成功!'.format(item.id)
            except Exception as e:
                row.append('erro')
                dt_data.append(row)
                print traceback.print_exc()
                continue
        open(u'美券数据更新.xlsx', 'wb').write(dt_data.xlsx)
