# -*- coding:utf-8 -*-
"""
功能：发送飞书消息接口
"""

import requests
import json
import logging
import time
import urllib3
urllib3.disable_warnings()
import os
from base_framework.public_tools.read_config import ReadConfig

try:
    JSONDecodeError = json.decoder.JSONDecodeError
except AttributeError:
    JSONDecodeError = ValueError
HERE = os.path.dirname(os.path.abspath(__file__))
msg_config_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'msg_config.ini')
read_config = ReadConfig(filename=msg_config_path)


def get_feishu_config_options():
    """
    功能：获取飞书配置文件信息
    option_key:配置文件中的key
    """
    return read_config.get_options('feishu_user_list')


def get_feishu_config_value(option_key):
    """
    功能：获取飞书配置文件信息
    option_key:配置文件中的key
    """
    return read_config.get_value(sections='feishu_user_list', options=option_key)

def get_user_name_by_email_prefix(email_prefix):
    """
    功能：获取飞书配置文件中的邮箱前缀与中文姓名的对应关系
    email_prefix:邮箱前缀
    返回：对应的中文姓名
    """
    return read_config.get_value(sections='user_name', options=email_prefix)


class FeiShuMessage(object):
    def __init__(self, team='TO', secret=None, pc_slide=False, fail_notice=False):
        """
        机器人初始化
        :param team: 业务组名，用于从msg_config配置文件中读取对应群组的webhook地址
        :param secret:  机器人安全设置页面勾选“加签”时需要传入的密钥
        :param pc_slide:  消息链接打开方式，默认False为浏览器打开，设置为True时为PC端侧边栏打开
        :param fail_notice:  消息发送失败提醒，默认为False不提醒，开发者可以根据返回的消息发送结果自行判断和处理
        """
        super(FeiShuMessage, self).__init__()
        self.headers = {'Content-Type': 'application/json; charset=utf-8'}
        team_name = team.lower() + '_webhook_token'
        if team_name in get_feishu_config_options():
            token = get_feishu_config_value(option_key=team_name)
            self.webhook = "https://open.feishu.cn/open-apis/bot/v2/hook/{0}".format(token)
        else:
            self.webhook = None
            logging.error("Team: {} not in msg_config.ini".format(team))
            return
        self.secret = secret
        self.pc_slide = pc_slide
        self.fail_notice = fail_notice

    def send_text(self, msg):
        """
        消息类型为text类型
        :param msg: 消息内容
        :return: 返回消息发送结果
        """
        data = {"msg_type": "text"}
        if msg and self.webhook:    # 传入msg非空
            data["content"] = {"text": msg}
            if "全部通过" in msg:
                # 不用发飞书消息
                logging.info("+++++++++ 全部构建成功，不发消息 ++++++++")
                return False
        return self.post(data)

    def post(self, data):
        """
        发送消息（内容UTF-8编码）
        :param data: 消息数据（字典）
        :return: 返回消息发送结果
        """
        try:
            post_data = json.dumps(data)
            response = requests.post(self.webhook, headers=self.headers, data=post_data, verify=False)
        except requests.exceptions.HTTPError as exc:
            logging.error("消息发送失败， HTTP error: %d, reason: %s" % (exc.response.status_code, exc.response.reason))
            raise
        except requests.exceptions.ConnectionError:
            logging.error("消息发送失败，HTTP connection error!")
            raise
        except requests.exceptions.Timeout:
            logging.error("消息发送失败，Timeout error!")
            raise
        except requests.exceptions.RequestException:
            logging.error("消息发送失败, Request Exception!")
            raise
        else:
            try:
                result = response.json()
            except JSONDecodeError:
                logging.error("服务器响应异常，状态码：%s，响应内容：%s" % (response.status_code, response.text))
                return {'errcode': 500, 'errmsg': '服务器响应异常'}
            else:
                logging.debug('发送结果：%s' % result)
                # 消息发送失败提醒（errcode 不为 0，表示消息发送异常），默认不提醒，开发者可以根据返回的消息发送结果自行判断和处理
                if self.fail_notice and result.get('errcode', True):
                    time_now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
                    error_data = {
                        "msgtype": "text",
                        "text": {
                            "content": "[注意-自动通知]飞书机器人消息发送失败，时间：%s，原因：%s，请及时跟进，谢谢!" % (
                                time_now, result['errmsg'] if result.get('errmsg', False) else '未知异常')
                        },
                        "at": {
                            "isAtAll": False
                        }
                    }
                    logging.error("消息发送失败，自动通知：%s" % error_data)
                    requests.post(self.webhook, headers=self.headers, data=json.dumps(error_data))
                return result


if __name__ == '__main__':
    fs = FeiShuMessage(team='TO')
    吴勇刚 = "<at user_id='ou_94f57439f58bde9376189a3cabb0b11a'>吴勇刚</at>"
    刘明浩 = "<at user_id='ou_94f57439f58bde9376189a3cabb0b11b'>刘明浩</at>"
    陈慧宗 = "<at user_id='ou_bc2b266b05a428959bfcff3378af2d36'>陈慧宗</at>"
    message = "【TO-SMOKING_NEW】 第【1314】次构建结果：失败【5】个 \n|--{}: 1个\n|--{}: 2个\n|--{}: 3个" \
              "构建报告：...........test..........".format(吴勇刚, 刘明浩, 陈慧宗)
    resp = fs.send_text(msg=message)
    print(resp)