#coding: utf-8
# +-------------------------------------------------------------------
# | 宝塔Windows面板
# +-------------------------------------------------------------------
# | Copyright (c) 2015-2020 宝塔软件(https://www.bt.cn) All rights reserved.
# +-------------------------------------------------------------------
# | Author: 沐落 <cjx@bt.cn>
# +-------------------------------------------------------------------
import sys,os,time,json,re
panelPath = os.getenv('BT_PANEL')
os.chdir(panelPath);
sys.path.append("class/")
import public,db,time,html,panelPush

try:
    from BTPanel import cache
except :
    from cachelib import SimpleCache
    cache = SimpleCache()



class bt_boce_push:

    __push = None
    def __init__(self):
        self.__push = panelPush.panelPush()
    
    #-----------------------------------------------------------start 添加推送 ------------------------------------------------------
    """
    @ 获取插件版本信息   
    """
    def get_version_info(self,get):
        """
        获取版本信息
        """
        data = {}
        data['ps'] = ''
        data['version'] = '1.0'
        data['date'] = '2020-07-14'
        data['author'] = '宝塔'
        data['help'] = 'http://www.bt.cn'
        return data

    """
    @获取推送模块配置
    """
    def get_module_config(self,get):

        if not public.M('sqlite_master').where('type=? AND name=?', ('table', 'boce_task')).count():
            return public.returnMsg(False,'未安装拨测插件，请先安装.')

        data = []       
        
        items = ['all']
        slist = public.M('boce_task').where('status=?',(1,)).select()
        for x in slist: items.append(x['name']);

        keys = {'500':'500内部错误','502':'502网关错误','503':'503响应错误','200':'200正常访问','301':'301重定向','302':'302重定向'}
        for skey in items:
            item = {}
           
            item['project'] = skey
            item['title'] = '{}拨测告警'.format(skey)
            if skey == 'all':
                item['title'] = '全部项目'
            item['type'] = 'boce'

            item['keys'] = []                        
            item['multiple'] = True         #可多选
            for x in keys:
                item['keys'].append({'key':x,'val':keys[x]})

            item['push'] = ['dingding','weixin']
            item['helps'] = ['注意：此功能需购买企业版后使用']
            data.append(item)
                
        return data


    #-----------------------------------------------------------end 添加推送 ------------------------------------------------------


    def get_total(self):        
        return True;

    def get_push_data(self,data,total):
        if data['module'] in ['sms']: 
            return public.returnMsg(False,"暂不支持模板，跳过.")   

        if data['project']:   
            pid = public.M('boce_task').where('name=?',(data['project'],)).getField('id')
            if not pid: return public.returnMsg(False,"项目不存在，跳过.")   
                
            slist = public.M('boce_list').where('id>? and pid=?', (data['index'],pid)).select()
        else:
            slist = public.M('boce_list').where('id>?', data['index']).select()
    
        if not len(slist): 
            return public.returnMsg(False,"未查到符合数据，跳过1.")   
       
        index = 0
        sdata = {}        
        for x in slist:       
            if not x['pid'] in sdata:                
                sdata[x['pid']] = {}
                sdata[x['pid']]['id'] = x['id']
                sdata[x['pid']]['list'] = []
            keys = data['key'].split(',')
            
            if len(keys) <= 0: 
                continue

            d_list = json.loads(x['data'])
            for item in d_list:
                if not str(item['http_code']) in keys: continue                    
                sdata[x['pid']]['list'].append(item)              
            index = x['id']
                
        return self.__get_result(data,sdata,index)
        
    """
    @服务停止返回
    """
    def __get_result(self,data,clist,index = 0):
        result = {
            'status':True,
            'msg':'推送',
            'index':index,
            'data':{
                  'title':data['title'],
                  'to_email':'',
                  'sms_type':'',
                  'sms_argv':{},
                  'title':data['title'],
                  'msg':''
            }
        }     
        for m_module in data['module'].split(','):

            if m_module in ['dingding','weixin']:  
                result[m_module] = self.__push.format_msg_data()

                p_msg = ''
                for key in clist:
                    if len(clist[key]['list']) <= 0: continue                    
                    find = public.M('boce_task').where('id=?',(key,)).find()             
                    p_msg += '**项目名称：{}**  \n\n  '.format(find['name'])
                    print(clist[key])
                    for x in clist[key]['list']:
                        if x['http_code'] in [200,301,302]:                        
                            p_msg += ">{} --- {} ms --- {}   \n\n  ".format(x['isp'],x['total_time'],x['http_code'])
                        else:
                            p_msg += ">{} --- {} \n\n  ".format(x['isp'],x['http_code'])
                        
                result[m_module]['msg'] = """#### 堡塔网站拨测提醒\n\n>服务器 ：{} \n\n >推送时间：{}  \n\n {}""".format(public.GetLocalIp(),public.format_date(),p_msg)
        return result
