import json
from django.core.management.base import NoArgsCommand
from pay.models.yinuo import PolicyHolder, YinuoOrder


class Command(NoArgsCommand):
    def handle(self, *args, **options):
        f = open('policy_holder.txt', 'w')
        for ph in PolicyHolder.objects.iterator():
            qs = YinuoOrder.objects.filter(order__user__id=ph.user_id)
            dic = {
                'user_id': ph.user_id,
                "id_card": ph.id_card,
                'phone': qs.last().order.phone if qs.exists() else None,
                'has_yinuo': qs.exists(),
                'has_zhongan': False,
                'created_time': ph.created_time.strftime("%Y%m%d%H%M%S"),
            }
            f.write(json.dumps(dic))
            print dic
            f.write('\n')
        f.close()
