# coding=utf-8
from django.core.management import BaseCommand
from django.db import connection

from api.models import Order, CouponInfo
from pay.models import ServiceSnapshot
from api.tool.service_tool import get_serviceitem_by_option_id

import json


class Command(BaseCommand):
    def handle(self, *args, **kwargs):
        sss = list(Order.objects.exclude(service_snapshot='').values_list('id'))

        for i in sss:
            oid = i[0]
            snap = Order.objects.filter(id=oid).values_list('service_snapshot', flat=True).first()
            if snap:
                snap_dict = json.loads(snap)

                update_dict = {}

                if snap_dict.has_key('richtext'):
                    update_dict['rich_text'] = snap_dict['richtext']

                if snap_dict.has_key('coupon_id'):
                    coupon_info_id = snap_dict['coupon_id']
                    update_dict['coupon_info_id'] = coupon_info_id #注意，以前保存的

                    coupon_id = None

                    try:
                        coupon_id = CouponInfo.objects.get(id=coupon_info_id).coupon_id
                    except CouponInfo.DoesNotExist:
                        print "CouponInfo.DoesNotExist, id:" + str(coupon_info_id)

                    if coupon_id:
                        update_dict['coupon_id'] = coupon_id

                if snap_dict.has_key('coupon_name'):
                    update_dict['coupon_name'] = snap_dict['coupon_name']

                if snap_dict.has_key('coupon_value'):
                    update_dict['coupon_value'] = snap_dict['coupon_value']

                if snap_dict.has_key('payment_without_coupon'):
                    update_dict['payment_without_coupon'] = snap_dict['payment_without_coupon']

                if update_dict:
                    count = ServiceSnapshot.objects.filter(order_id=oid).update(**update_dict)
                    if count > 0:
                        print "update order_id: " + oid

        print "success!"