# -*- coding:utf-8 -*-

import requests
from django.core.management import BaseCommand
from django.conf import settings


class Command(BaseCommand):

    def add_arguments(self, parser):
        parser.add_argument('-r',
                            '--reply',
                            action='store_true',
                            dest='reply',
                            default=False,
                            help='reply message'
                            )
        parser.add_argument('param', nargs='+', type=str)

    '''
    1,短信发送命令 sudo python manage.py send_message_byhaobo phone.list '你好'
    其中 phone.list 是一个文件,里面是按行分割存的手机号, '你好' 是发送的的短信内容
    结果打印id,内容,状态
    2,接受手机回复命令 sudo python manage.py send_message_byhaobo -r reply
    结果打印回复信息,字典格式,信息已转为unicode码,其中'sm'为回应值,其他字段请参考昊博短信文档释义
    '''
    def handle(self, *args, **options):
        msg = '【更美】您好！这里是更美，竭诚为您服务！测试发送,验证码为' + '345678'
        if options['reply']:
            HaoboMessage.get_reply_message()
        if options['param']:
            #if options['param'][0] == 'phone.list':
            param = options['param'][0]
            msg = options['param'][1]
            print "msg is :%s" % str(msg)
            phone_list = []
            for line in open(param):
                phone = line.strip()
                if len(phone) == 11 and phone[0] == '1':
                    phone_list.append(phone)
                if len(phone_list) == 200:
                    try:
                        phone_list.append('18518676745')
                        phone_numbers = ';'.join(phone_list)
                        if HaoboMessage.send_message(phone_numbers, msg):
                            print 'send scuess'
                        else:
                            print 'send fail'
                    except Exception, ex:
                        print 'send fail %s' % str(ex)
                    phone_list = []
                    print phone
            try:
                phone_numbers = ';'.join(phone_list)
                if HaoboMessage.send_message(phone_numbers, msg):
                    print 'send scuess'
                else:
                    print 'send fail'
            except Exception, ex:
                print 'send fail %s' % str(ex)


            #with open(param) as f:
            #    try:
            #        phone_list = f.read().split('\n')
            #        phone_numbers = ';'.join(phone_list)
            #        if HaoboMessage.send_message(phone_numbers, msg):
            #            print 'send scuess'
            #        else:
            #            print 'send fail'
            #    except Exception, ex:
            #        print 'send fail %s' % str(ex)


class HaoboMessage:

    url_prefix = settings.SEND_MESSAGE_URL_PREFIX
    un = settings.SEND_MESSAGE_UN
    pw = settings.SEND_MESSAGE_PWD
    dc = 15
    rd = 1
    op = 'mo'

    @classmethod
    def encode_message_gb2312(cls, message):
        try:
            messgae_gb2313_code = message.decode('utf-8').encode('gb2312')
        except Exception, ex:
            messgae_gb2313_code = message
        message_hex_code = messgae_gb2313_code.encode('hex')
        return message_hex_code

    @classmethod
    def decode_message_unicode(cls, message, decode_type):
        return message.decode('hex').\
            encode('utf-8').decode(decode_type)

    @classmethod
    def send_message(cls, phonenumbers, message):
        request_url = '%s/mt' % cls.url_prefix
        request_param = {
            'un': cls.un,
            'pw': cls.pw,
            'dc': cls.dc,
            'rd': cls.rd,
            'da': phonenumbers,
            'sm': cls.encode_message_gb2312(message)
        }
        request_result = requests.get(request_url, params=request_param)
        result = request_result.text
        print result
        if 'id' in result:
            return True
        return False

    @classmethod
    def handle_reply_str(cls, result_str):
        result_str_list = result_str.split('\r\n')
        for sm in result_str_list:
            if sm == '':
                continue
            sm_message = sm.split('&')
            message_list = []
            dict_message = dict(ls.split('=') for ls in sm_message)
            if 'sm' in dict_message.keys():
                decode_type = 'utf-8'
                if dict_message['dc'] == '0':
                    decode_type = 'ascii'
                elif dict_message['dc'] == '8':
                    decode_type = 'utf-16be'
                else:
                    decode_type = 'gbk'
                dict_message['sm'] = \
                    cls.decode_message_unicode(dict_message['sm'], decode_type)
                print 'phone:%s,message:%s' % \
                      (dict_message['sa'], dict_message['sm'])
                message_list.append(dict_message)
            return message_list

    @classmethod
    def get_reply_message(cls):
        request_url = '%s/mo' % cls.url_prefix
        request_param = {
            'un': cls.un,
            'pw': cls.pw,
            'op': cls.op
        }
        request_result = requests.get(request_url, params=request_param)
        result = request_result.text
        handle_result = cls.handle_reply_str(result)
        return handle_result
