package com.shining.cloud.serviceImpl.information;

import cn.hutool.core.util.StrUtil;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.github.pagehelper.PageHelper;
import com.njcn.enums.LogTypeEnum;
import com.njcn.enums.SeparatorEnum;
import com.njcn.enums.app.MessageEnum;
import com.njcn.enums.app.UserCodeEnum;
import com.njcn.mapper.app.AppInfoSetMapper;
import com.njcn.mapper.configuration.LineMapper;
import com.njcn.mapper.data.EventDetailMapper;
import com.njcn.mapper.user.AppUserMapper;
import com.njcn.mapper.user.DeptsLineMapper;
import com.njcn.mapper.user.UserMapper;
import com.njcn.mapper.user.UserSetMapper;
import com.njcn.pojo.app.AppInfoSet;
import com.njcn.pojo.app.AppSendMsg;
import com.njcn.pojo.commons.RedisDB;
import com.njcn.pojo.commons.WaveData;
import com.njcn.pojo.configuration.Line;
import com.njcn.pojo.data.EventDetail;
import com.njcn.pojo.user.AppUser;
import com.njcn.pojo.user.Depts;
import com.njcn.pojo.user.DeptsLine;
import com.njcn.pojo.user.UserSet;
import com.njcn.pojo.wave.WaveDataDetail;
import com.njcn.service.commons.IWaveService;
import com.njcn.service.log.UserLogDetailService;
import com.njcn.utils.*;
import com.njcn.utils.redis.JedisManager;
import com.shining.cloud.mapper.information.DevMsgMapper;
import com.shining.cloud.mapper.information.EventInfoMapper;
import com.shining.cloud.mapper.information.EventMsgMapper;
import com.shining.cloud.mapper.information.SteadyMsgMapper;
import com.shining.cloud.pojo.common.SmsConstant;
import com.shining.cloud.pojo.information.*;
import com.shining.cloud.service.information.EventMsgService;
import com.shining.cloud.service.information.SteadyAssService;
import com.shining.cloud.service.report.ShiningReportService;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.security.auth.login.AccountException;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

/**
 * @description: 暂态消息ServiceImpl
 * @author: denghuajun
 * @time: 2019-10-17 14:09:47
 **/
@Service
public class EventMsgServiceImpl implements EventMsgService {
    private static final Logger logger = LoggerFactory.getLogger(EventMsgServiceImpl.class);
    @Resource
    private EventMsgMapper eventMsgMapper;

    @Resource
    private EventInfoMapper eventInfoMapper;

    @Resource
    private DeptsLineMapper deptsLineMapper;

    @Resource
    private UserLogDetailService userLogDetailService;

    @Resource
    UserUtil userUtil;

    @Resource
    private UserMapper userMapper;

    @Resource
    private AppInfoSetMapper appInfoSetMapper;

    @Resource
    private EventDetailMapper eventDetailMapper;

    @Resource
    private LineMapper lineMapper;

    @Resource
    private AppUserMapper appUserMapper;

    @Resource
    private SteadyMsgMapper steadyMsgMapper;

    @Resource
    private DevMsgMapper devMsgMapper;

    @Autowired
    private IWaveService waveService;

    @Resource
    private SteadyAssService steadyAssService;

    @Resource
    private UserSetMapper userSetMapper;

    @Autowired
    private JedisManager jedisManager;

    @Override
    public List<EventMsgDetail> eventDetailList(String userIndex, int page, int num) {
        List<Integer> lineIndex = userUtil.ApplistLine(userIndex);
        List<EventMsgDetail> eventMsgs = null;

        if (!lineIndex.isEmpty()) {
            PageHelper.offsetPage((page - 1) * num, num);
            eventMsgs = eventMsgMapper.eventDetailList(userIndex, lineIndex);
        }
        return eventMsgs;
    }

    @Override
    public List<EventMsgDetail> eventDetailAppList(String userIndex, int page, int num) {
        List<Integer> lineIndex = userUtil.ApplistLine(userIndex);
        //获取数据
        List<EventMsgDetail> eventMsgDetails = eventMsgMapper.getEventMsgDetailByLineId(lineIndex, (page - 1) * num + 1, page * num);
        if (CollectionUtils.isEmpty(eventMsgDetails)) {
            return new ArrayList<>();
        }
        Iterator<EventMsgDetail> iterator = eventMsgDetails.iterator();
        while (iterator.hasNext()) {
            //处理推送消息
            EventMsgDetail eventMsgDetail = iterator.next();
            EventMsg eventMsg = eventMsgMapper.getEventMsgByEventId(userIndex, eventMsgDetail.getEventDetailIndex());
            if (Objects.isNull(eventMsg)) {
                iterator.remove();
            } else {
                eventMsgDetail.setEventMsgIndex(eventMsg.getEventMsgIndex());
                eventMsgDetail.setState(eventMsg.getState());
            }
            //处理终端名称
            String name = eventMsgMapper.getDevNameByLineId(eventMsgDetail.getLineIndex());
            eventMsgDetail.setLineInfo(name);
        }
        return eventMsgDetails;
    }


    @Override
    public int getUnState(String userIndex) {
        List<Integer> lineIndex = userUtil.ApplistLine(userIndex);
        int state = 0;
        if (!lineIndex.isEmpty()) {
            state = eventMsgMapper.getUnState(userIndex, lineIndex);
        }
        return state;
    }

    /**
     * 推送暂降消息
     *
     * @param eventDetailIndex 暂降事件索引
     * @param lineId           监测点索引
     *                         1：根据监测点获取绑定的部门
     *                         2：根据部门找到对应的主用户
     *                         3：根据主用户获取所有的app用户
     *                         4：执行推送保存功能
     */
    @Override
    public void sendEventMsg(String eventDetailIndex, int lineId, HttpServletRequest request) throws Exception {
        EventDetail eventDetail;
        eventDetail = eventDetailMapper.selectByIndex(eventDetailIndex);
//        String lineGrade = lineMapper.getLineGradeById(lineId);
//        if (StrUtil.isBlank(lineGrade)) {
//            lineGrade = "不重要";
//        }
        if (null != eventDetail) {
            if (eventDetail.getEventValue() == null || eventDetail.getEventValue() >= 0.9) {
                return;
            }
        }
        DeptsLine deptsLine = new DeptsLine();
        deptsLine.setLineIndex(Long.valueOf(lineId));
        List<DeptsLine> deptsLines = deptsLineMapper.select(deptsLine);
        //查询为空，则无人关注，不做推送处理，但是需要进行日志记录
        if (CollectionUtils.isEmpty(deptsLines)) {
            noUserFocus(eventDetailIndex, lineId);
        }
        //存在则进行筛选用户操作
        List<String> deptsIndexs = new ArrayList<>();
        for (DeptsLine temp : deptsLines) {
            //此处比较麻烦，除了找到当前部门的用户，还需要递归找到当前部门所有父节点的部门
            List<Depts> deptsList = userUtil.getDeptsByNodeUp(temp.getDeptsIndex());
            deptsIndexs.add(temp.getDeptsIndex());
            for (Depts depts : deptsList) {
                if (!deptsIndexs.contains(depts.getDeptsIndex())) {
                    deptsIndexs.add(depts.getDeptsIndex());
                }
            }
        }
        //递归出部门后再继续筛选出设备码
        List<AppUser> appUsers = userMapper.getAllDevcodes(deptsIndexs);
        if (CollectionUtils.isEmpty(appUsers)) {
            noUserFocus(eventDetailIndex, lineId);
        }
        EventInfo eventInfo = new EventInfo();
        eventInfo.setEventDetailIndex(eventDetailIndex);
        eventInfo = eventInfoMapper.selectOne(eventInfo);
        if (null != eventInfo) {
            throw new AccountException(UserCodeEnum.REPEAT_EVENT_INFO.getMsg());
        } else {
            eventInfo = new EventInfo();
            eventInfo.setEventDetailIndex(eventDetailIndex);
            //绘制瞬时波形和RMS波形
            WaveData waveData = waveService.getWavedata(eventDetailIndex, 2);
            if (!CollectionUtils.isEmpty(waveData.getSunData())) {
                //数据筛选,如果是双路电压的话，会存在2个波形数据
                List<WaveDataDetail> waveDataDetails = waveService.filteWaveData(waveData);
                Properties pros = PubUtils.readProperties(getClass().getClassLoader(), "java.properties");
                String url = pros.get("REPORT_PATH").toString() + "eventInfo";
                String path = request.getSession().getServletContext().getRealPath("/appfiles");
                path = path + SeparatorEnum.PARTITION.getSpearator() + "eventInfo";
                Date now = new Date();
                File tmpfile = new File(path);
                if (!tmpfile.exists()) {
                    tmpfile.mkdir();
                }
                //瞬时波形图
                String sunpath = path + SeparatorEnum.PARTITION.getSpearator() + PubUtils.date2String(now, "yyyyMMddHHmmss") + "_" + eventDetailIndex + "shun.png";
                steadyAssService.generateImageShun(waveData, waveDataDetails, path, sunpath);
                eventInfo.setInstantWavePath(url + SeparatorEnum.URL.getSpearator() + PubUtils.date2String(now, "yyyyMMddHHmmss") + "_" + eventDetailIndex + "shun.png");
                //RMS波形图
                path = request.getSession().getServletContext().getRealPath("/appfiles");
                path = path + SeparatorEnum.PARTITION.getSpearator() + "eventInfo";
                String rmspath = path + SeparatorEnum.PARTITION.getSpearator() + PubUtils.date2String(now, "yyyyMMddHHmmss") + "_" + eventDetailIndex + "rms.png";
                steadyAssService.generateImageRMS(waveData, waveDataDetails, path, rmspath);
                eventInfo.setRmsWavePath(url + SeparatorEnum.URL.getSpearator() + PubUtils.date2String(now, "yyyyMMddHHmmss") + "_" + eventDetailIndex + "rms.png");
            }
        }
        eventInfoMapper.insert(eventInfo);
        //获取到设备码开始执行推送并保存库的操作
        //排重设备ID
        List<String> codes = new ArrayList<>();
        for (AppUser appUser : appUsers) {
            if (!codes.contains(appUser.getDevCode())) {
                codes.add(appUser.getDevCode());
                pushEventInfo(eventDetailIndex, appUser.getUserIndex(), StringUtils.isEmpty(appUser.getDevCode()) ? null : appUser.getDevCode());
            }
        }


    }

    /**
     * 稳态消息推送
     *
     * @param userIndex 用户索引
     * @param timeID    统计时间
     * @param lineNum   监测点数
     */
    @Override
    public String sendSteadyMsg(String userIndex, Long timeID, Integer lineNum) throws AccountException {
        AppUser appUser = new AppUser();
        appUser.setUserIndex(userIndex);
        appUser = appUserMapper.selectOne(appUser);
        if (null == appUser) {
            throw new AccountException(UserCodeEnum.NO_USER.getMsg());
        }
        AppInfoSet appInfoSet = new AppInfoSet();
        appInfoSet.setUserIndex(userIndex);
        appInfoSet = appInfoSetMapper.selectOne(appInfoSet);
        if (null != appInfoSet) {
            //插入之前需要判断是否重复时间
            SteadyMsg steadyMsg = new SteadyMsg();
            steadyMsg.setTimeID(new Date(timeID));
            steadyMsg.setLineNum(lineNum);
            steadyMsg.setUserIndex(userIndex);
            List<SteadyMsg> steadyMsgs = steadyMsgMapper.select(steadyMsg);
            if (!CollectionUtils.isEmpty(steadyMsgs)) {
                return steadyMsgs.get(0).getSteadyIndex();
            }
            steadyMsg.setLineNum(lineNum);
            steadyMsg.setState(0);
            steadyMsg.setSteadyIndex(UUID.randomUUID().toString());
            steadyMsg.setTimeID(new Date(timeID));
            steadyMsg.setUserIndex(userIndex);
            steadyMsgMapper.insert(steadyMsg);
            if (appInfoSet.getTargetInfo() == 1 && !PubUtils.isBlank(appUser.getDevCode())) {
                //发送稳态消息
                String url = getPushUrl();
                String title = "稳态越限消息";
                String content = PubUtils.timeStamp3Date(timeID, "yyyy-MM-dd") + " 发生稳态越限监测点" + lineNum + "个";
                sendMsg(url, appUser.getDevCode(), title, content, "2");
            }
            return steadyMsg.getSteadyIndex();
        } else {
            throw new AccountException(UserCodeEnum.NO_USER_SETTING.getMsg());
        }
    }


    /**
     * 终端消息推送
     *
     * @param userIndex 用户索引
     * @param timeID    统计时间
     * @param alarmNum  警告次数
     * @param comOutNum 通讯状态
     * @param flowNum   流量百分比
     * @param flag      是否强制推送
     */
    @Override
    public String sendTargetMsg(String userIndex, Long timeID, Integer devNum, Integer alarmNum, Integer comOutNum, Float flowNum, int flag) throws Exception {
        AppUser appUser = new AppUser();
        appUser.setUserIndex(userIndex);
        appUser = appUserMapper.selectOne(appUser);
        if (null == appUser) {
            throw new AccountException(UserCodeEnum.NO_USER.getMsg());
        }
        AppInfoSet appInfoSet = new AppInfoSet();
        appInfoSet.setUserIndex(userIndex);
        appInfoSet = appInfoSetMapper.selectOne(appInfoSet);
        if (null != appInfoSet) {
            String url = getPushUrl();
            Date date = new Date(timeID);
            date = PubUtils.string2Date(PubUtils.date2String(date, "yyyy-MM-dd"), "yyyy-MM-dd");
            DevMsg devMsg = new DevMsg();
            devMsg.setUserIndex(userIndex);
            devMsg.setTimeId(date);
            devMsg = devMsgMapper.selectOne(devMsg);
            if (null != devMsg) {
                devMsg = mergeDevMsg(devMsg, devNum, userIndex, date);
                devMsgMapper.updateByPrimaryKey(devMsg);
                if (devNum > 0) {
                    if (appInfoSet.getDeviceInfo() == 1 && flag == 1) {
                        if (alarmNum > 0 || comOutNum > 0 || flowNum > 94) {
                            //推送
                            String title = PubUtils.date2String(date, "yyyy-MM-dd") + "终端异常共" + devNum + "台";
                            String content = "异常情况：" + (StringUtils.isEmpty(alarmNum) ? "" : "终端告警：" + alarmNum + "次  ") + (StringUtils.isEmpty(comOutNum) ? "" : "通讯中断：" + Integer.valueOf(comOutNum) + "次  ") + (StringUtils.isEmpty(flowNum) ? "" : "终端流量：" + Float.valueOf(flowNum) + "%");
                            sendMsg(url, appUser.getDevCode(), title, content, "3");
                        }
                    }
                }
                return devMsg.getDevMsgIndex();
            } else {
                devMsg = mergeDevMsg(null, devNum, userIndex, date);
                devMsgMapper.insert(devMsg);
                if (devNum > 0) {
                    if (appInfoSet.getDeviceInfo() == 1) {
                        if (alarmNum > 0 || comOutNum > 0 || flowNum > 94) {
                            //推送
                            String title = PubUtils.date2String(date, "yyyy-MM-dd") + "终端异常共" + devNum + "台";
                            String content = "异常情况：" + (StringUtils.isEmpty(alarmNum) ? "" : "终端告警：" + alarmNum + "次  ") + (StringUtils.isEmpty(comOutNum) ? "" : "通讯中断：" + Integer.valueOf(comOutNum) + "次  ") + (StringUtils.isEmpty(flowNum) ? "" : "终端流量：" + Float.valueOf(flowNum) + "%");
                            sendMsg(url, appUser.getDevCode(), title, content, "3");
                        }
                    }
                }
                return devMsg.getDevMsgIndex();
            }
        } else {
            throw new AccountException(UserCodeEnum.NO_USER_SETTING.getMsg());
        }
    }

    @Override
    public void sendTerminalMsg(Date date, String userIndex, Integer devNum, Integer alarmNum, Integer comOutNum) throws Exception {
        AppUser appUser = new AppUser();
        appUser.setUserIndex(userIndex);
        appUser = appUserMapper.selectOne(appUser);
        if (null == appUser) {
            throw new AccountException(UserCodeEnum.NO_USER.getMsg());
        }
        AppInfoSet appInfoSet = new AppInfoSet();
        appInfoSet.setUserIndex(userIndex);
        appInfoSet = appInfoSetMapper.selectOne(appInfoSet);
        if (Objects.nonNull(appInfoSet)) {
            if (appInfoSet.getDeviceInfo() == 1) {
                String url = getPushUrl();
                String title = PubUtils.date2String(date, "yyyy-MM-dd") + "终端异常共" + devNum + "台";
                String content = "异常情况：" + (StringUtils.isEmpty(alarmNum) ? "" : "终端告警：" + alarmNum + "次  ") + (StringUtils.isEmpty(comOutNum) ? "" : "通讯中断：" + Integer.valueOf(comOutNum) + "次  ");
                sendMsg(url, appUser.getDevCode(), title, content, "3");
            }
        } else {
            throw new AccountException(UserCodeEnum.NO_USER_SETTING.getMsg());
        }

    }


    /**
     * 合并并入库处理
     */
    private DevMsg mergeDevMsg(DevMsg devMsg, int devNum, String userIndex, Date date) {
        if (null == devMsg) {
            devMsg = new DevMsg();
            devMsg.setDevMsgIndex(UUID.randomUUID().toString());
            devMsg.setUserIndex(userIndex);
            devMsg.setTimeId(date);
        }
        devMsg.setLimitNum(devNum);
        devMsg.setState(0);
        return devMsg;
    }

    /**
     * 执行推送保存消息操作
     *
     * @param eventDetailIndex 暂降事件索引
     * @param userIndex        用户索引
     * @param devCode          手机唯一标识
     */
    private void pushEventInfo(String eventDetailIndex, String userIndex, String devCode) throws Exception {
        //先根据用户获取推送策略
        AppInfoSet appInfoSet = new AppInfoSet();
        appInfoSet.setUserIndex(userIndex);
        appInfoSet = appInfoSetMapper.selectOne(appInfoSet);
        if (null != appInfoSet) {
            EventMsg eventMsg = new EventMsg();
            eventMsg.setEventDetailIndex(eventDetailIndex);
            eventMsg.setEventMsgIndex(UUID.randomUUID().toString());
            eventMsg.setUserIndex(userIndex);
            eventMsg.setState(0);
            //执行保存消息记录操作
            eventMsgMapper.insert(eventMsg);
            if (appInfoSet.getEventInfo() == 1 && !PubUtils.isBlank(devCode)) {
                //推送
                EventDetail eventDetail;
                String content = "发生时刻：";
                eventDetail = eventDetailMapper.selectByIndex(eventDetailIndex);
                if (null != eventDetail) {
                    if (eventDetail.getEventValue() == null || eventDetail.getEventValue() >= 0.9) {
                        return;
                    }
                    Line line = new Line();
                    line.setLineIndex(eventDetail.getLineId());
                    line = lineMapper.selectOne(line);
                    if (null != line) {
                        String url = getPushUrl();
                        String time = PubUtils.date2String(eventDetail.getTimeId(), "yyyy-MM-dd HH:mm:ss") + "." + eventDetail.getMs();
                        content = content + time + ",暂降幅值：" + PubUtils.floatRound(2, eventDetail.getEventValue() * 100) + "%," + "持续时间：" + PubUtils.floatRound(2, Float.valueOf(eventDetail.getPersistTime()) / 1000) + "s。";
                        sendMsg(url, devCode, line.getName() + "监测点发生暂态事件", content, "1");
                        //查询主账户是否开启短信通知 根据监测点ID找到部门找到用户
                        //添加策略，判断当前该事件是否需要短信推送
                        boolean isPush = judgeEventNeedPush(eventDetail, line.getLineIndex());
                        if (isPush) {
                            List<String> phones = userMapper.getPushPhoneNum(line.getLineIndex());
                            if (!CollectionUtils.isEmpty(phones)) {
                                for (String phone : phones) {
                                    sendMobileMessage(line.getName(), PubUtils.date2String(eventDetail.getTimeId(), "yyyy-MM-dd HH:mm:ss"), eventDetail.getMs() + "", PubUtils.floatRound(2, eventDetail.getEventValue() * 100) + "", PubUtils.floatRound(2, Float.valueOf(eventDetail.getPersistTime()) / 1000) + "", phone);
                                }
                            }
                        }
                    }
                }
            }
        }

    }

    /***
     * 1、监测点等级：极重要----则全部发送；
     * 2、监测点等级：重要----一天内最多通过短信发送10条暂降事件；超过的则暂降小等于80的才发送；
     * 3、监测点等级：普通----一天内最多通过短信发送3条暂降事件；超过的则暂降小等于80的才发送；
     * 4、监测点等级：不重要----一天内最多通过短信发送1条暂降事件；超过的则暂降小等于80的才发送；
     * @author hongawen
     * @date 2023/7/31 10:15
     * @param eventDetail 暂降信息
     * @param lineIndex 监测点索引
     * @return boolean
     */
    private boolean judgeEventNeedPush(EventDetail eventDetail, Long lineIndex) {
        boolean pushFlag = true;
        String valueByKey = jedisManager.getValueByKey(RedisDB.ONE_DAY_QUERY, String.valueOf(lineIndex));
        if (StrUtil.isBlank(valueByKey)) {
            //为空，则最近24小时内没有发生暂降推送
            jedisManager.saveValueByKey(RedisDB.ONE_DAY_QUERY, String.valueOf(lineIndex), "1", RedisDB.ONE_DAY_TIME);
        } else {
            //不为空，根据监测点重要程度来区分次数是否达到上限
            String lineGrade = lineMapper.getLineGradeById(lineIndex);
            if (StrUtil.isBlank(lineGrade)) {
                lineGrade = "不重要";
            }
            if (eventDetail.getEventValue() > 0.80f) {
                int times = Integer.parseInt(valueByKey);
                switch (lineGrade) {
                    case "重要":
                        if (times >= 10) {
                            pushFlag = false;
                        }
                        break;
                    case "普通":
                        if (times >= 3) {
                            pushFlag = false;
                        }
                        break;
                    case "不重要":
                        if (times >= 1) {
                            pushFlag = false;
                        }
                        break;
                    default:
                        break;
                }
                if (pushFlag) {
                    times++;
                    long ttl = jedisManager.ttl(RedisDB.ONE_DAY_QUERY, String.valueOf(lineIndex));
                    jedisManager.saveValueByKey(RedisDB.ONE_DAY_QUERY, String.valueOf(lineIndex), String.valueOf(times), (int) ttl);
                }
            }
        }
        return pushFlag;
    }

    /**
     * 获取推送接口的url
     */
    private String getPushUrl() {
        String url;
        Properties pros = PubUtils.readProperties(getClass().getClassLoader(), "java.properties");
        url = pros.get("APP_PUSH_URL").toString();
        return url;
    }

    /**
     * 无人关注的监测点出现暂降消息处理
     *
     * @param eventDetailIndex 暂降索引
     * @param lineId           监测点索引
     */
    private void noUserFocus(String eventDetailIndex, int lineId) throws AccountException {
        //进行日志保存
        try {
            userLogDetailService.saveUserLog("shiningCloud", "shiningCloud", "暂降推送", lineId + "的暂降消息" + eventDetailIndex + "无人监听", "shiningCloud", "255.255.255.255", LogTypeEnum.SYSTEM.toString(), 0);
        } catch (AccountException e) {
            logger.error("日志保存发生异常，异常是" + e.getMessage());
        }
        //抛出异常，返回调用者
        throw new AccountException(UserCodeEnum.NO_USER_FOCUS.getMsg());
    }

    /**
     * 推送消息
     *
     * @param url                 目标url
     * @param cid                 手机唯一标识
     * @param title               消息头
     * @param content             消息内容
     * @param transmissionContent 消息类别
     */
    private static void sendMsg(String url, String cid, String title, String content, String transmissionContent) {
        String result;
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("cid", cid);
            jsonObject.put("title", title);
            jsonObject.put("content", content);
            jsonObject.put("transmissionContent", transmissionContent);
            result = HttpClientUtils.excutePostJson(url, jsonObject);
            JSONObject resultJson = JSONObject.fromObject(result);
            int resultCode = resultJson.getInt("returnCode");
            if (resultCode != 0) {
                logger.error("推送消息的标题：{},失败，返回体为：{}", title, result);
                throw new AccountException(UserCodeEnum.STEADY_MSG_FAIL.getMsg());
            }
            logger.error("推送消息的标题：{}，结果：{}", title, result);
        } catch (Exception e) {
            logger.error("推送消息发生异常，异常是" + e.getMessage());
        }
    }


    /**
     * 发送手机短信
     *
     * @return 推送的响应
     */
    private static SendSmsResponse sendMobileMessage(String... params) {
        SendSmsResponse sendSmsResponse;
        //开始执行短信发送
        try {
            //设置超时时间-可自行调整
            System.setProperty(SmsConstant.DEFAULT_CONNECT_TIME_OUT, "10000");
            System.setProperty(SmsConstant.DEFAULT_READ_TIME_OUT, "10000");
            IClientProfile profile = DefaultProfile.getProfile(SmsConstant.LOCATION, SmsConstant.ACCESS_KEY_ID, SmsConstant.ACCESS_KEY_SECRET);
            DefaultProfile.addEndpoint(SmsConstant.LOCATION, SmsConstant.LOCATION, SmsConstant.PRODUCT, SmsConstant.DOMAIN);
            IAcsClient acsClient = new DefaultAcsClient(profile);
            SendSmsRequest request = new SendSmsRequest();
            request.setMethod(MethodType.POST);
            request.setPhoneNumbers(params[5]);
            //必填:短信签名-可在短信控制台中找到
            request.setSignName(SmsConstant.SGIN);
            //必填:短信模板-可在短信控制台中找到，发送国际/港澳台消息时，请使用国际/港澳台短信模版
            request.setTemplateCode(MessageEnum.EVENT_MESSAGE_NOTICE.getTemplateCode());
            String messgae = "{\"line\":\"" + params[0] + "\",\"time\":\"" + params[1] + "\",\"ms\":\"" + params[2] + "\",\"eventvalue\":\"" + params[3] + "\",\"persisttime\":\"" + params[4] + "\"}";
            request.setTemplateParam(messgae);
            //请求失败这里会抛ClientException异常
            sendSmsResponse = acsClient.getAcsResponse(request);
            if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
                //成功发送短信验证码后，保存进redis
                logger.info("给用户发送暂降事件短信成功，手机号为：{}", params[5]);
            } else {
                logger.info("给用户发送暂降事件短信失败，手机号为：{}，失败原因为：{}", params[5], sendSmsResponse.getMessage());
            }
        } catch (Exception e) {
            logger.error("发送短信异常：" + e);
            throw new org.apache.shiro.authc.AccountException(UserCodeEnum.SEND_CODE_FAIL.getMsg());
        }
        return sendSmsResponse;
    }

    public static void main(String[] args) {
        try {
            sendMobileMessage("一号点", "2020-08-15 12:22:59", "350", "88.36", "20.2", "13914774158");
        } catch (Exception exception) {
            exception.printStackTrace();
            System.out.println(1);
            System.out.println(1);
        }
    }
}
