# -*- coding: UTF-8 -*-
import json
from datetime import datetime

from django.core.management import BaseCommand
from gm_types.gaia import SPECIAL_MODULE, CAMPAIGN_MODULE
from api.models.special import Special, SpecialLayout
from api.models.campaign import CampaignLayout
from .utils import get_mail

change_time = str(datetime.now().date())


class Command(BaseCommand):
    """
    python manage.py update_20171113_update_coupon_img

    """
    def handle(self, *args, **kwargs):
        error_msg = ''
        result_log = ''
        specials = Special.objects.exclude(coupons='')
        for special in specials:
            try:
                related = json.dumps([{'coupon_id': coupon_id, 'img': ''}for coupon_id in special.coupons.split(',')])
                s = SpecialLayout.objects.create(
                    special_id=special.id,
                    is_visible=special.is_show_coupons,
                    module=SPECIAL_MODULE.COUPONS,
                    related=related)
                result_log += 'special_id:{}, old_msg:{},new_msg:{}'.format(special.id, special.coupons, s.related)
                print 'special:{}'.format(special.id)
            except Exception as e:
                message = '{}:{}'.format(special.id, e.message)
                print message
                error_msg += message + '\n'
                continue

        campaigns = CampaignLayout.objects.filter(module=CAMPAIGN_MODULE.COUPON_FETCH)
        for c in campaigns:
            try:
                related = json.loads(c.related)
                c.related = json.dumps([{'coupon_id': i, 'img': ''} for i in related])
                c.save()
                result_log += 'campaingn_id:{}, old_msg:{},new_msg:{}'.format(c.id, related, c.related)
                print 'campaign:{}'.format(c.id)
            except Exception as e:
                message = '{}:{}'.format(c.id, e.message)
                print message
                error_msg += message + '\n'
                continue
        body = u'{}_coupon_img'.format(change_time)
        get_mail(u'{}_rusult.txt'.format(body), u'{}_result'.format(body), u'chenfeifei@igengmei.com', result_log).send()
        get_mail(u'{}_error.txt'.format(body), u'{}_error'.format(body), u'chenfeifei@igengmei.com', error_msg).send()
        print 'Done!'
