# coding:utf-8

from __future__ import unicode_literals
import requests
from django.core.management import BaseCommand
from api.models import UserExtra

__author__ = 'chengliang'

msg = 'hello, world! ' + '【更美】'
stime = '2015-09-01 12:00:00'
ext = '1'

black_list = ['13161689643', '18618133328']


class Command(BaseCommand):

    def add_arguments(self, parser):
        parser.add_argument('param', nargs='+', type=str)

    @staticmethod
    def send_sms_md(phone_list, msg):
        """
        漫道短信通道
        """
        data = {'sn': 'SDK-BBX-010-19243',
                'pwd': 'E5D3CF92329CA75E6B794ADE37154616',
                'mobile': phone_list,
                'content': msg.encode('gbk'),
                'ext': ext,
                'stime': stime,
                'rrid': ''}
        response = requests.post('http://sdk.entinfo.cn:8060/webservice.asmx/mt', data)
        return 0

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

        for param in options['param']:

            if param == 'phone.txt':
                f = open(param)
                try:
                    phone_list = f.read().split('\n')
                    for phone in phone_list:
                        if phone in black_list:
                            phone_list.remove(phone)

                    self.send_sms_md(phone_list, msg)

                finally:
                    f.close()

            elif param == 'user.txt':
                f = open(param)
                try:
                    u_ids = f.read().split('\n')
                    users = UserExtra.objects.filter(user_id__in=u_ids)
                    phone_list = []
                    for user in users:
                        phone = user.phone
                        if phone not in black_list:
                            phone_list.append(phone)

                    self.send_sms_md(phone_list, msg)

                finally:
                    f.close()

