#!/usr/bin/env python
# -*- coding: utf-8 -*-

import random
import string

from itertools import chain
from datetime import date, datetime, timedelta

from django.core.management import BaseCommand
from django.conf import settings
from django.contrib.auth.models import User

from gm_types.gaia import LOGIN_AUTH_TYPE

from api.models import (
    CouponChannel,
    ChannelGift,
    ChannelGiftUserRelation,
    Person,
)


class Command(BaseCommand):

    def handle(self, *args, **options):

        print("BEGIN")
        str_date_style = raw_input("请输入查询截止日期(注意：字符串类型！)，例如：'2018-08-08', 不输入默认为今天 ：")

        if str_date_style:
            end_time = datetime.strptime(str_date_style, "%Y-%m-%d")
        else:
            end_time = date.today()

        start_time = end_time - timedelta(days=1)

        print(start_time, end_time)

        try:
            channel_gift = ChannelGift.objects.get(
                gift_id=settings.COUPON_SHARE_GIFT_ID,
                business_channel_id=settings.COUPON_SHARE_CHANNEL_ID
            )

            get_channel_gift_user_ids = set(ChannelGiftUserRelation.objects.filter(
                channel_gift=channel_gift,
                user_id__isnull=False,
                created_time__range=[start_time, end_time]
            ).values_list("user_id", flat=True))

            # 由于存在新老用户只要没领过就能领劵的问题，手机号只能这么取了！！！
            user_phone_list = list(User.objects.filter(
                id__in=get_channel_gift_user_ids).values_list("username", flat=True))

            person_phone_list = list(Person.objects.filter(
                user_id__in=get_channel_gift_user_ids).values_list("phone", flat=True))

            print('original_phone_info', set(chain(person_phone_list, user_phone_list)))

            phone_list = []
            for phone in set(chain(person_phone_list, user_phone_list)):
                if not isinstance(phone, str):
                    try:
                        phone = str(phone)
                    except:
                        continue

                if phone.isdigit() and len(phone) == 11 and phone[0] == "1":
                    phone_list.append(phone)

            file_name = '{date}_export_receive_channel_gift_phone_{num}.txt'.format(
                date=date.today().strftime('%Y-%m-%d'),
                num=''.join(random.sample(string.letters + string.digits, 8))
            )
            dir_path = "/tmp/export_receive_channel_gift_phone"

            file_path = "{}/{}".format(dir_path, file_name)

            with open(file_path, "w+") as f:
                f.writelines(["{}\n".format(p) for p in phone_list])

            print(phone_list)

        except ChannelGift.DoesNotExist:
            print("ERROR! CHANNEL_GIFT DoesNotExist")
        print("END")
