# -*- coding:utf-8 -*-
'''
梦网短信接口
'''

import datetime
import hashlib
import json
import requests
import traceback
import urllib

from rpc.tool.log_tool import sms_logger

class OweFeeException(Exception):
    message = '梦网账号欠费, 请稍候再试'

class MengWangSMS(object):
    appid = 'JI5583'
    pwd = '987050'
    place_holder = '00000000'
    batch_limit = 1000
    m_domain = 'http://101.251.214.153:8901'
    batch_send_path = '/sms/v2/std/batch_send'
    json_header = {'Content-Type': 'application/json'}
    batch_send_url = m_domain + batch_send_path


    def get_pwd_hash(self):
        '''
        获取加密密码
        '''
        now = datetime.datetime.now()
        now_str = now.strftime('%m%d%H%M%S')
        ori_auth_str = ''.join([self.appid, self.place_holder, self.pwd, now_str])
        return now_str, hashlib.md5(ori_auth_str).hexdigest()


    def get_auth_params(self):
        prms = {}
        prms['userid'] = self.appid
        prms['timestamp'], prms['pwd'] = self.get_pwd_hash()
        return prms


    def format_content(self, content):
        '''
        格式化短信内容
        '''
        try:
            content = content.decode('utf-8')
        except:
            pass

        gbk_content = content.encode('gbk')
        return urllib.quote(gbk_content)


    def batch_send(self, phone_list, content):
        if not phone_list:
            return

        phone_list = filter(None, phone_list)

        phones = [phone_list[i:i+self.batch_limit] for i in range(0, len(phone_list), self.batch_limit)]
        for ps in phones:
            self._batch_send(ps, content)


    def _batch_send(self, phone_list, content):
        phone_str = ','.join([str(x) for x in phone_list])
        query_prms = self.get_auth_params()
        query_prms['mobile'] = phone_str
        query_prms['content'] = self.format_content(content)
        try:
            _res = requests.post(url=self.batch_send_url, data=json.dumps(query_prms), headers=self.json_header, timeout=3)
            json_res = _res.json()
            if json_res and str(json_res.get('result')) == '0':
                sms_logger.info('[SMS_MW]batch_send_sms success, phones:(%s) with content(%s)' % (phone_str, content))
                return True
            else:
                sms_logger.warn('[SMS_MW]batch_send_sms failed, return result is: %s' % _res.content)
                if str(json_res.get('result')) == '-100003':
                    raise OweFeeException()
                return False
        except OweFeeException as e:
            sms_logger.error('[SMS_MW] OWE FEE!!!')
            raise e
        except:
            sms_logger.error(traceback.format_exc())
            return False


mw_sms_sender = MengWangSMS()

mw_batch_send_message = mw_sms_sender.batch_send

