import logging
import json
import requests
from django.conf import settings
from qcloudsms_py import SmsSingleSender, SmsMultiSender
from qcloudsms_py.httpclient import HTTPError
from console.message.models import Messages, MessagesDispatcher

logger = logging.getLogger("")


class MessageObject(object):
    def __init__(self):
        self.appid = settings.SMS_APPID
        self.appkey = settings.SMS_APPKEY
        self.sms_sign = settings.SMS_SIGN
        self.wechat_bot = settings.WECHAT_BOT

    def send_sms_single(self,
                        phone_num=None,
                        template_id=None,
                        template_param_list=None):
        """
        单条发送短信
        :param phone_num: 手机号
        :param template_id: 腾讯云短信模板ID
        :param template_param_list: 短信模板所需参数列表，例如:【验证码：{1}，描述：{2}】，
        则传递参数 [888,666]按顺序去格式化模板
        :return:
        """

        sender = SmsSingleSender(self.appid, self.appkey)
        try:
            response = sender.send_with_param(86,
                                              phone_num,
                                              template_id,
                                              template_param_list,
                                              sign=self.sms_sign)
        except HTTPError as e:
            response = {'result': 1000, 'errmsg': "网络异常发送失败:{}".format(e)}
        return response

    def send_sms_multi(self,
                       phone_num_list=None,
                       template_id=None,
                       param_list=None):
        """
        批量发送短信
        :param phone_num_list:手机号列表
        :param template_id:腾讯云短信模板ID
        :param param_list:短信模板所需参数列表，例如:【验证码：{1}，描述：{2}】，
        则传递参数 [888,666]按顺序去格式化模板
        :return:
        """
        sender = SmsMultiSender(self.appid, self.appkey)
        try:
            phone_num_list = list(filter(None, phone_num_list)) \
                if phone_num_list else []
            response = sender.send_with_param(86,
                                              phone_num_list,
                                              template_id,
                                              param_list,
                                              sign=self.sms_sign)
        except HTTPError as e:
            response = {'result': 1000, 'errmsg': "网络异常发送失败:{}".format(e)}
        return response

    def send_station(self, title, content, sender_id, receive_ids, render_type=1, type=1, enterprise_id=1, links=None):
        receive_list = []
        if not enterprise_id:
            enterprise_id = 1
        try:
            message = Messages.objects.create(title=title, content=content,
                                              render_type=render_type, sender_id=sender_id,
                                              type=type, links=links, enterprise_id=enterprise_id)
            for receive_id in receive_ids:
                receive_list.append(MessagesDispatcher(receive_id=receive_id, message_id=message.id))
            MessagesDispatcher.objects.bulk_create(receive_list)
        except Exception as e:
            print(e)
            logger.debug(e)

    def send_station_model(self, title, content, sender_id, receive_ids, render_type=1, type=1, enterprise_id=1, links=None):
        receive_list = []
        receive_ids = list(set([int(receive_id) for receive_id in receive_ids]))
        try:
            message = Messages.objects.create(title=title, content=content,
                                              render_type=render_type, sender_id=sender_id,
                                              type=type, links=links, enterprise_id=enterprise_id)
            for receive_id in receive_ids:
                receive_list.append(MessagesDispatcher(receive_id=receive_id, message_id=message.id))
            return receive_list
        except Exception as e:
            print(e)
            logger.debug(e)
            return receive_list

    def send_station_multi(self, receive_list):
        try:
            MessagesDispatcher.objects.bulk_create(receive_list)
        except Exception as e:
            print(e)
            logger.debug(e)

    def send_wechat_bot(self, type, content):
        headers = {
            "User-Agent":
                "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 \
                    (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36",
            "Content-Type": "application/json;charset=UTF-8",
            "Connection": "close"
        }
        data = json.dumps({"msgtype": type, type: {"content": content, "mentioned_list":["@all"]}})
        with requests.Session() as s:
            s.post(self.wechat_bot, data, headers=headers)


client = MessageObject()
