package com.pqs9900.serviceImpl.message;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.njcn.pojo.commons.AreaGeneralData;
import com.njcn.pojo.commons.RedisDB;
import com.njcn.utils.*;
import com.njcn.utils.redis.JedisManager;
import com.pqs9900.mapper.message.MessageMapper;
import com.pqs9900.mapper.message.MsgCofMapper;
import com.pqs9900.pojo.message.*;
import com.pqs9900.service.message.MessageService;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class MessageServiceImpl implements MessageService {
    @Autowired
    private AppConfig appConfig;
    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private MsgCofMapper msgCofMapper;

    @Resource
    private JedisManager jedisManager;

    @Autowired
    private UserUtil userUtil;

    private static final Logger logger = LoggerFactory.getLogger(MessageServiceImpl.class);


    @Override
    public String sendMsg(String msg, String phone, List<Integer> list, Date date, Date date2,int inter,Integer[] arr) {
        try {
            //获取token
            String redisToken = getToken();
            if (StrUtil.isBlank(msg)) {
                sendAllUser(redisToken, list, date, date2,inter,arr);
                return "发送短信成功";
            } else {
                String userId = messageMapper.getUserIdByPhone(phone);
                if (userId == null) {
                    return "请选择系统用户手机号";
                } else {
                    return zuzhuang(redisToken, phone, msg, 1);
                }
            }
        }catch (Exception e){
            logger.error("短信异常"+e.getMessage());
            return "发送短信失败";
        }
    }

    private void sendAllUser(String volid, List<Integer> list, Date start, Date end,int inter,Integer[] arr) {
        getMsgTempData(volid, list, start, end,inter,arr);
    }




    private List<MsgTemplateData> getMsgTempData(String volid, List<Integer> l, Date start, Date end,int inter,Integer[] arr) {
        String strStart = "";
        String strEnd = "";
        try {

            strEnd = PubUtils.date2String(end, "yyyy-MM-dd HH:mm:ss");
        } catch (Exception e) {
            logger.error("时间转化产生了异常，异常是" + e.getMessage());
            return null;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(end);
        calendar.add(Calendar.MINUTE,-inter);
        Date aa = calendar.getTime(); //获取当前时间往前推扫描间隔时间

        List<EventdetailInfo> deptList = messageMapper.getAllSendDept();//获取所有可以发送短信的部门用户
        List<MsgTemplateData> templateDataList = new ArrayList<>();
        Set<String> deptL = new HashSet<>();
        for (EventdetailInfo deptObj : deptList) {
            deptL.add(deptObj.getDeptsId());
        }
        Iterator<String> iterator = deptL.iterator();

        while (iterator.hasNext()) {
            Calendar fanwibegin = Calendar.getInstance();
            fanwibegin.add(Calendar.DATE,-2);
            List<UserEventDTO> list = messageMapper.getHasSendEvent(fanwibegin.getTime(),new Date()); //获取发送过的暂降事件和用户

            String deptIndex = iterator.next();  //部门id

            List<String> userList = new ArrayList();
            List<String> phoneList = new ArrayList();
            List<String> eventList = new ArrayList<>();
            List<Integer> lineList = new ArrayList<>();

            MsgTemplateData msgTemplateData = new MsgTemplateData();
            //分割线
            msgTemplateData.setDeptsId(deptIndex);

            for (EventdetailInfo deptObj : deptList) {
                if (deptObj.getDeptsId().equals(deptIndex)) {
                    userList.add(deptObj.getUserId());
                    phoneList.add(deptObj.getPhone());
                }
            }
            if (!CollectionUtil.isEmpty(userList)) {
                userList.stream().distinct().collect(Collectors.toList());
            }
            if (!CollectionUtil.isEmpty(phoneList)) {
                phoneList.stream().distinct().collect(Collectors.toList());
            }
            msgTemplateData.setListUserId(userList);
            msgTemplateData.setListPhone(phoneList);

            Set<Integer> mainList = new HashSet<>();//暂将事件集合


            List<AreaGeneralData> Alist = userUtil.getAreaDataByMsg(deptIndex);



            Date startTime = aa;
            for (AreaGeneralData areaGeneralData : Alist) {
                List<Integer> linelist = areaGeneralData.getLineIndexs();

                if (!CollectionUtil.isEmpty(linelist)) {
                    lineList.addAll(linelist);
                }

            }

           /* List<EventdetailInfo> evenList = new ArrayList<>();
            if(lineList.size()>1000){
                int size =lineList.size()%1000 == 0? lineList.size()/1000 : lineList.size()/1000+1;
                for(int i = 0;i<size;i++){
                    if(lineList.size()>1000){
                        List<Integer> subLineList = lineList.subList(0,1000);
                        List<EventdetailInfo> zanshi = messageMapper.getEventList(start, end, l, subLineList);
                        evenList.addAll(zanshi);
                        subLineList.clear();
                    }else{
                        List<EventdetailInfo> zanshi = messageMapper.getEventList(start, end, l, lineList);
                    }
                }
            }else{
                evenList = messageMapper.getEventList(start, end, l, lineList);
            }*/
            List<EventdetailInfo> evenList  = messageMapper.getEventList(start, end, l, lineList);

            //与user_eve表对比排除已发送暂降事件
            Iterator<EventdetailInfo> infoIterator = evenList.iterator();
            while (infoIterator.hasNext()){
                boolean flag = true;
                EventdetailInfo ee = infoIterator.next();
                for(String user: userList){
                    if(!CollectionUtil.isEmpty(list)){
                        for(UserEventDTO userEventDTO : list){
                            if(userEventDTO.getEventdetailIndex().equals(ee.getEvenIndex()) && userEventDTO.getUserIndex().equals(user)){
                                flag = false;
                                break;
                            }
                        }

                    }
                    if(!flag){
                        break;
                    }
                }
                if(!flag){
                    infoIterator.remove();
                }else{
                    startTime = getRightTime(ee.getdTime(),startTime);
                }
            }
            /*排除最后发送时间前的暂降事件*/
            if(!CollectionUtil.isEmpty(evenList)){
                //存在补招问题，第二天发送的应该剔除前一天补招上来的暂降事件
                Calendar calendarend= Calendar.getInstance();
                calendarend.set(Calendar.HOUR_OF_DAY,arr[1]-1);
                calendarend.set(Calendar.MINUTE,59);
                calendarend.set(Calendar.SECOND,59);
                calendarend.add(Calendar.DAY_OF_MONTH,-1);
                // System.out.println("昨天最后扫描时间"+calendarend.getTime());
                List<UserEventDTO> evenL = new ArrayList<>();
                Iterator<EventdetailInfo> topklist = evenList.iterator();
                while (topklist.hasNext()){
                    EventdetailInfo pk= topklist.next();
                    if(pk.getdTime().before(calendarend.getTime())|| pk.getEventvalue()>0.9){
                        if(CollectionUtil.isNotEmpty(msgTemplateData.getListUserId())) {
                            for (String userid : msgTemplateData.getListUserId()) {
                                UserEventDTO userEventDTO = new UserEventDTO();
                                userEventDTO.setEventdetailIndex(pk.getEvenIndex());
                                userEventDTO.setUserIndex(userid);
                                userEventDTO.setTime(new Date());
                                evenL.add(userEventDTO);
                            }
                        }
                        messageMapper.addHasSendEvent(evenL);
                        //System.out.println("删除的暂降事件"+pk.getdTime());
                        topklist.remove();
                    }else{
                        startTime = getRightTime(pk.getdTime(),startTime);
                    }
                }

            }


            if (CollectionUtil.isEmpty(evenList)) {
                continue;
            }

            try {
                Calendar cc = Calendar.getInstance();
                cc.setTime(startTime);
                cc.set(Calendar.SECOND,0);
                strStart = PubUtils.date2String(cc.getTime(),"yyyy-MM-dd HH:mm:ss");

            } catch (Exception e) {
                e.printStackTrace();
            }
            msgTemplateData.setStartTime(strStart);
            msgTemplateData.setCount(evenList.size());
            msgTemplateData.setListLineId(mainList);
            msgTemplateData.setEndTime(strEnd);




            String[] num = {"①","②","③","④","⑤","⑥","⑦","⑧","⑨","⑩"};
            int dela = 0;//用于判断是那条暂降事件
            StringBuilder stringBuilder = new StringBuilder("");
            if(evenList.size()<=10) {
                eventList.addAll(evenList.stream().map(EventdetailInfo::getEvenIndex).collect(Collectors.toList()));

                for (int i = 0; i < evenList.size(); i++) {
                    BigDecimal d = null;
                    String v = evenList.get(i).getVoltage().substring(0, evenList.get(i).getVoltage().indexOf("kV"));

                    d = new BigDecimal(v).divide(new BigDecimal(1.73), 2, BigDecimal.ROUND_HALF_UP);


                    stringBuilder.append(num[dela] + "、" + evenList.get(i).getStrTime() + " " + evenList.get(i).getBdName() + " " + evenList.get(i).getLineName() + "发生暂降事件,特征幅值:" + new BigDecimal(evenList.get(i).getValue()).setScale(2, BigDecimal.ROUND_HALF_UP) + "p.u.(" + new BigDecimal(evenList.get(i).getValue()).multiply(d).setScale(2, BigDecimal.ROUND_HALF_UP) + " kV)" + ",持续时间:" +
                            (evenList.get(i).getMsTime()) / (1000) + "s;");
                    dela++;
                }
                stringBuilder.append(" 详情请登录海南电网电能质量监测系统查看!");

                msgTemplateData.setTemplate(stringBuilder.toString());
                msgTemplateData.setListEvent(eventList);
                templateDataList.add(msgTemplateData);
            }else {
                stringBuilder.append("于" + msgTemplateData.getStartTime() + "至" + msgTemplateData.getEndTime() + "时间段内共发生"+evenList.size()+"条暂降事件。");

                Map<Integer,EventdetailInfo> mapMap = new HashMap<>();
                for (int i = 0; i < evenList.size(); i++) {
                    if(mapMap.containsKey(evenList.get(i).getLineId())){
                        EventdetailInfo en = mapMap.get(evenList.get(i).getLineId());
                        en.setCount(en.getCount()+1);
                        en.getEvenList().add(evenList.get(i).getEvenIndex());
                        mapMap.put(evenList.get(i).getLineId(),en);
                    }else {
                        EventdetailInfo en = new EventdetailInfo();
                        en.setLineName(evenList.get(i).getLineName());
                        en.setBdName(evenList.get(i).getBdName());
                        en.getEvenList().add(evenList.get(i).getEvenIndex());
                        en.setCount(1);
                        mapMap.put(evenList.get(i).getLineId(),en) ;
                    }
                }
                Iterator<Map.Entry<Integer,EventdetailInfo>> it = mapMap.entrySet().iterator();
                int cal = 1;
                eventList.clear();

                while(it.hasNext()){
                    Map.Entry<Integer, EventdetailInfo> m = it.next();
                    eventList.addAll(m.getValue().getEvenList());
                    stringBuilder.append(m.getValue().getBdName()+" "+m.getValue().getLineName() + "发生" + m.getValue().getCount() + "次暂降事件;");
                    if(cal%15 == 0){
                        if(it.hasNext()){
                            MsgTemplateData msgTemplateData1 = new MsgTemplateData();
                            msgTemplateData1.setDeptsId(deptIndex);
                            msgTemplateData1.setListUserId(userList);
                            msgTemplateData1.setListPhone(phoneList);
                            msgTemplateData1.setStartTime(strStart);
                            msgTemplateData1.setCount(evenList.size());
                            msgTemplateData1.setListLineId(mainList);
                            msgTemplateData1.setListEvent(eventList);
                            msgTemplateData1.setEndTime(strEnd);
                            msgTemplateData1.setTemplate(stringBuilder.toString());
                            templateDataList.add(msgTemplateData1);
                            stringBuilder.setLength(0);
                            stringBuilder.append("续: ");
                            eventList = new ArrayList<>();
                        }else{
                            stringBuilder.append(" 详情请登录海南电网电能质量监测系统查看!");
                            msgTemplateData.setTemplate(stringBuilder.toString());
                            msgTemplateData.setListEvent(eventList);
                            templateDataList.add(msgTemplateData);
                        }


                    }
                    if(mapMap.size() == cal && cal%15 != 0){
                        stringBuilder.append(" 详情请登录海南电网电能质量监测系统查看!");
                        msgTemplateData.setTemplate(stringBuilder.toString());
                        msgTemplateData.setListEvent(eventList);
                        templateDataList.add(msgTemplateData);
                    }
                    cal++;

                }


            }



            // System.out.println("起始时间:"+msgTemplateData.getStartTime()+"结束时间:"+msgTemplateData.getEndTime());



        }

        insertMsgInfo(volid, templateDataList);
        return templateDataList;
    }


    private List<EventdetailInfo> screen(Set<Integer> set, List<EventdetailInfo> list) {
        List<EventdetailInfo> list1 = new ArrayList<>();
        Iterator<Integer> iterator = set.iterator();

        while (iterator.hasNext()) {
            Integer id = iterator.next();
            EventdetailInfo eventdetailInfo = new EventdetailInfo();
            Iterator<EventdetailInfo> iterator1 = list.iterator();

            while (iterator1.hasNext()) {
                EventdetailInfo eventdetailInfo1 = iterator1.next();

                if (id.intValue() == eventdetailInfo1.getLineId().intValue()) {
                    eventdetailInfo.setCount(eventdetailInfo.getCount() + 1);
                    eventdetailInfo.setBdName(eventdetailInfo1.getBdName());
                    eventdetailInfo.setGdName(eventdetailInfo1.getGdName());
                    eventdetailInfo.setLineName(eventdetailInfo1.getLineName());
                    eventdetailInfo.setStrTime(eventdetailInfo1.getStrTime());
                    eventdetailInfo.setValue(eventdetailInfo1.getValue());
                    eventdetailInfo.setMsTime(eventdetailInfo1.getMsTime());
                    eventdetailInfo.setVoltage(eventdetailInfo1.getVoltage());
                    iterator1.remove();
                }
            }

            list1.add(eventdetailInfo);
        }

        return list1;
    }


    public void insertMsgInfo(String volid, List<MsgTemplateData> list) {
        for (MsgTemplateData msgTemplateData : list) {
            String phoneStr = "";
            List<String> phonelist = msgTemplateData.getListPhone();
            String msg = msgTemplateData.getTemplate();

            for (String ph : phonelist) {
                phoneStr += ph + ";";
            }
            String res = "";
            res = zuzhuang(volid, phoneStr, msg, 2);
            //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
           //  if("发送成功".equals(res)){
            List<UserEventDTO> evenL = new ArrayList<>();
            for(String userindex : msgTemplateData.getListUserId()){
                for(String evenindex : msgTemplateData.getListEvent()){
                    UserEventDTO userEventDTO = new UserEventDTO();
                    userEventDTO.setUserIndex(userindex);
                    userEventDTO.setEventdetailIndex(evenindex);
                    userEventDTO.setTime(new Date());
                    evenL.add(userEventDTO);
                }
            }

            messageMapper.addHasSendEvent(evenL);
              //  }

            //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

            for (String userId : msgTemplateData.getListUserId()) {
                String msgIndex = UUID.randomUUID().toString();
                userId = dealStringParam(userId);
                msgIndex = dealStringParam(msgIndex);
                String template = dealStringParam(msgTemplateData.getTemplate());
                if(template.length()>2048){
                    template = template.substring(0,2048);
                }
                if ("发送成功".equals(res)) {
                    messageMapper.insertMsgInfo(userId, new Date(), template, 0, 1, msgIndex);
                } else {
                    messageMapper.insertMsgInfo(userId, new Date(), template, 1, 1, msgIndex);
                }
            }

        }
    }

    /**
     * 判断最新日期
     * @author cdf
     * @date 2021/3/29
     */
    private Date getRightTime(Date edate,Date time){
        if(edate.before(time)){
            return edate;
        }else {
            return time;
        }
    }



   /* private void translateData(List<EventdetailInfo> list2, List<MsgTemplateData> list1, String start, String end) {
        if (list2 == null || list2.size() == 0) {
            return;
        }

        Set<String> set = new HashSet<>();

        for (EventdetailInfo eventdetailInfo : list2) {
            set.add(eventdetailInfo.getDeptsId()); //获取部门Id
        }

        Iterator<String> iterator = set.iterator();

        while (iterator.hasNext()) {
            MsgTemplateData msgTemplateData = new MsgTemplateData(start, end);
            String str = iterator.next();
            msgTemplateData.setDeptsId(str);
            List<String> listPhone = new ArrayList<>();
            List<String> listUserId = new ArrayList<>();
            Map<String, String> map = new HashMap<>();

            for (EventdetailInfo eventdetailInfo : list2) {
                if (eventdetailInfo.getDeptsId().equals(str)) {
                    listPhone.add(eventdetailInfo.getPhone());
                    listUserId.add(eventdetailInfo.getUserId());
                    map.put(eventdetailInfo.getGdName(), eventdetailInfo.getBdName());
                }
            }

            msgTemplateData.setListPhone(listPhone);
            msgTemplateData.setListUserId(listUserId);
            msgTemplateData.setBdGd(map);
            list1.add(msgTemplateData);
        }
    }
*/

    /**
     * @Author chendaofei
     * @Description 获取短信配置
     * @Date 10:16 2020/5/14
     **/
    @Override
    public MsgBaseConfDTO getMsgConfig() {
        MsgBaseConfDTO msgBaseConfDTO = msgCofMapper.getMsgConfig();
        return msgBaseConfDTO;
    }


    /**
     * @Author chendaofei
     * @Description 获取短信配置相关模板
     * @Date 10:17 2020/5/14
     **/
    @Override
    public List<MsgTypeTemplateDTO> getMsgDicdataList() {
        List<MsgTypeTemplateDTO> list = msgCofMapper.getMsgDicdataList(null, null);
        return list;
    }

    /**
     * @Author chendaofei
     * @Description 删除模板
     * @Date 10:18 2020/5/14
     **/
    @Override
    public Integer delMsgDicBytype(String msgIndex) {
        Integer res = msgCofMapper.delMsgDicBytype(msgIndex);
        return res;
    }

    /**
     * @Author chendaofei
     * @Description 修改短信时间段类型模板
     * @Date 10:18 2020/5/14
     **/
    @Override
    public String updateMsgDicState(List<String> list) {
        msgCofMapper.updateMsgDicState2();
        if (!CollectionUtil.isEmpty(list)) {
            msgCofMapper.updateMsgDicState(list);
        }
        return "配置成功";
    }

    /**
     * @Author chendaofei
     * @Description 新增短信时间段类型模板
     * @Date 10:18 2020/5/14
     **/
    @Override
    public String addMsgDicdata(MsgTypeTemplateDTO msgTypeTemplateDTO) {
        Integer type = msgTypeTemplateDTO.getMsgType();
        BigDecimal val_1 = msgTypeTemplateDTO.getValue1();
        BigDecimal val_2 = msgTypeTemplateDTO.getValue2();
        //1,时间模板 2.类型模板
        if (type == 1) {
            //时间范围模板
            List<MsgTypeTemplateDTO> list = msgCofMapper.getMsgDicdataList(type, null);
            if (list != null && list.size() != 0) {
                MsgTypeTemplateDTO mt = new MsgTypeTemplateDTO();
                mt.setValue1(val_1);
                mt.setValue2(val_2);
                list.add(mt);
                try {
                    Boolean flag = checkMunberArea(list);
                    if (flag == false) {
                        return "时间段不可交叉";
                    }
                } catch (Exception e) {
                    return "时间段获取错误";
                }
            }
        } else {
            //类型模板
            Integer res = msgCofMapper.checkHasDicdata(msgTypeTemplateDTO.getMsgName(), type);
            if (res != 0) {
                return "存在该类型请勿重复添加";
            }
        }
        msgCofMapper.addMsgDicdata(msgTypeTemplateDTO);
        return "添加成功";
    }

    @Override
    public List<MsgInfoDTO> getAllMsgList(Integer type, Date startTime, Date endTime) {
        List<MsgInfoDTO> list = messageMapper.getAllMsgList(type, startTime, endTime);
        return list;

    }

    /**
     * @Author chendaofei
     * @Description 删除已发短信
     * @Date 11:50 2020/5/21
     **/
    @Override
    public Boolean deleteMsgList(List<String> list) {
        Integer res = messageMapper.deleteMsgList(list);
        if (res == list.size()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * @Author chendaofei
     * @Description 判断时间段是否交叉
     * @Date 13:58 2020/5/13
     **/
    private Boolean checkMunberArea(List<MsgTypeTemplateDTO> lsitMap) throws Exception {
        Collections.sort(lsitMap, new Comparator<MsgTypeTemplateDTO>() {
            @Override
            public int compare(MsgTypeTemplateDTO o1, MsgTypeTemplateDTO o2) {
                BigDecimal num_1 = o1.getValue1();
                BigDecimal num_2 = o2.getValue1();
                int result = num_1.compareTo(num_2);
                return result;
            }
        });
        for (int i = 0; i < lsitMap.size(); i++) {
            BigDecimal endInt = new BigDecimal(lsitMap.get(i).getValue2().toString());
            for (int j = i + 1; j < lsitMap.size(); j++) {
                BigDecimal toBeginInt = new BigDecimal(lsitMap.get(j).getValue1().toString());
                if (toBeginInt.compareTo(endInt) == -1) {
                    return false;
                }
            }
        }
        return true;
    }


    private String dealStringParam(String param) {
        jedisManager.saveValueByKey(RedisDB.SHORT_TIME_QUERY, "MessageServiceImpldealStringParam", param, RedisDB.SHORT_TIME);
        String result = jedisManager.getValueByKey(RedisDB.SHORT_TIME_QUERY, "MessageServiceImpldealStringParam");
        jedisManager.deleteByKey(RedisDB.SHORT_TIME_QUERY, "MessageServiceImpldealStringParam");
        return result;
    }


    /*解析wsdl返回值*/
    private Map<String, Object> excuForTokenMap(String Xmlres) {
        Map<String, Object> map = new HashMap<>();
        Document doc = null;
        try {
            doc = DocumentHelper.parseText(Xmlres);
        } catch (DocumentException e) {
            return null;
        }
        Element root = doc.getRootElement();
        List<Element> elist = root.elements();
        for (int i = 0; i < elist.size(); i++) {
            Element node = (Element) elist.get(i);
            List el2list = node.elements();
            for (int j = 0; j < el2list.size(); j++) {
                Element element = (Element) el2list.get(j);
                List el3list = element.elements();
                for (int k = 0; k < el3list.size(); k++) {
                    Element ert = (Element) el3list.get(k);
                    map.put(ert.getName(), ert.getText());
                }
            }
        }
        return map;
    }

    /*从redis中获取token*/
    public String getToken() {
        try {
            //先从redis缓存获取，如果没有再调用接口去获取token
            String token = (String) SerializeUtil.deserialize(jedisManager.getValueByKey(RedisDB.NORMALIZ, SerializeUtil.serialize("messageToken")));

            if (token == null || token.isEmpty()) {
                //从第三方获取token并缓存
                token = getSendToken();
                if (token != null && !token.isEmpty()) {
                    jedisManager.saveValueByKey(RedisDB.NORMALIZ, SerializeUtil.serialize("messageToken"), SerializeUtil.serialize(token), -1);
                }

            }
            return token;
        } catch (Exception e) {
            logger.error("获取短信token产生了异常，异常是" + e.getMessage());
            return "";
        }
    }

    /**
     * 获取短信平台的token
     * @author cdf
     * @date 2021/6/9
     */
    private String getSendToken() {
        String wsdl = "<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:impl=\"http://impl.webservice.xuanwu.com\">\n" +
                "   <soapenv:Header/>\n" +
                "   <soapenv:Body>\n" +
                "      <impl:getToken soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\n" +
                "         <username xsi:type=\"soapenc:string\" xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\">" + appConfig.getMsgUser() + "</username>\n" +
                "         <password xsi:type=\"soapenc:string\" xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\">" + appConfig.getMsgPassword() + "</password>\n" +
                "      </impl:getToken>\n" +
                "   </soapenv:Body>\n" +
                "</soapenv:Envelope>";

        String token = null;
        String Xmlres = HttpClientUtils.excuteWsdl("http://10.94.0.107:8090/wireless/services/SmsService?wsdl", wsdl);
        if (Xmlres != null && !Xmlres.isEmpty()) {
            Map<String, Object> map = excuForTokenMap(Xmlres);
            if (map != null) {
                token = (String) map.get("getTokenReturn");
            }
        }
        return token;
    }

    /*
     * 短信组装
     * */
    private String zuzhuang(String token, String phone, String msg, Integer type) {
        //测试发送
        String send = "<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:impl=\"http://impl.webservice.xuanwu.com\">\n" +
                "   <soapenv:Header/>\n" +
                "   <soapenv:Body>\n" +
                "      <impl:sendSms soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\n" +
                "         <token xsi:type=\"soapenc:string\" xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\">" + token + "</token>\n" +
                "         <mobilelist xsi:type=\"soapenc:string\" xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\">" + phone + "</mobilelist>\n" +
                "         <content xsi:type=\"soapenc:string\" xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\">" + msg + "</content>\n" +
                "      </impl:sendSms>\n" +
                "   </soapenv:Body>\n" +
                "</soapenv:Envelope>";
        //不为空则发送

        String issend = HttpClientUtils.excuteWsdl("http://10.94.0.107:8090/wireless/services/SmsService?wsdl", send);

        if (issend != null && !issend.isEmpty()) {

            Map<String, Object> map2 = excuForTokenMap(issend);

            if (map2 != null) {
                String res = (String) map2.get("sendSmsReturn");
                if (res != null && !res.isEmpty()) {
                    Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
                    Boolean flag = pattern.matcher(res).matches();
                    if (flag) {
                        if (type == 1) {
                            //测试
                            Integer result = sendTest(msg, phone, 0);
                            if (result == 0) {
                                return "发送失败";
                            } else {
                                return "发送成功";
                            }

                        } else {
                            return "发送成功";
                        }
                    } else {
                        //可能存在token过期情况
                        Document doc = null;
                        try {
                            doc = DocumentHelper.parseText(res);
                        } catch (DocumentException e) {
                            logger.error("解析xml发生错误" + e.getMessage());
                            return "发送失败";
                        }
                        Element root = doc.getRootElement();
                        Element code = root.element("code");
                        String errrcode = code.getText();
                        if (errrcode.equals("105")) {
                            jedisManager.saveValueByKey(RedisDB.NORMALIZ, SerializeUtil.serialize("messageToken"), SerializeUtil.serialize(""), -1);
                        }
                        return "发送失败";
                    }

                } else {
                    return "发送失败";
                }

            } else {
                return "发送失败";
            }
        } else {
            return "发送失败";
        }
    }

    //模拟测试发送
    private Integer sendTest(String msg, String phone, Integer type) {
        msg = dealStringParam(msg);
        phone = dealStringParam(phone);
        String userId = messageMapper.getUserIdByPhone(phone);
        if (userId == null) {
            return 0;
        }
        String msgIndex = UUID.randomUUID().toString();
        msgIndex = dealStringParam(msgIndex);
        userId = dealStringParam(userId);
        if (type == 0) {
            messageMapper.insertMsgInfo(userId, new Date(), msg, 0, 1, msgIndex);
            return 1;
        } else {
            messageMapper.insertMsgInfo(userId, new Date(), msg, 1, 1, msgIndex);
            return 0;
        }
    }
}
