package org.ts.ddcs.WxController;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.ts.ddcs.DataTemplate.DataTemplateSzyCA1;
import org.ts.ddcs.Entity.RtuBaseInfo;
import org.ts.ddcs.Log.LogHelper;

import org.ts.ddcs.Service.RtuService;
import org.ts.ddcs.Service.WarningService;
import org.ts.ddcs.Tool.BytesHelp;
import org.ts.ddcs.Tool.DatagramHelp;
import org.ts.ddcs.UserController.service.UserService;
import org.ts.ddcs.Worker.DataProcess;
import org.ts.ddcs.Worker.DataProcessHolder;
import org.ts.ddcs.WxController.entity.ProjectInfo;
import org.ts.ddcs.WxController.entity.ServicePersonInfo;
import org.ts.ddcs.WxController.service.WxService;
import org.ts.ddcs.utils.GBConstants;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.upload.FastImageFile;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;

import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;

@RestController
public class WxController {

    @Autowired
    private WxService wxService;

    @Autowired
    private RtuService rtuService;

    @Autowired
    private WarningService warningService;

    @Value("${run-config.server.projectImplementPhotoPath}")
    private String projectImplementPhotoPath;

    @Value("${run-config.server.imageServerPath}")
    private String imageServerPath;

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${run-config.server.wxAppId}")
    private String wxAppId;

    @Value("${run-config.server.wxSecret}")
    private String wxSecret;

    @Autowired
    private FastFileStorageClient fastFileStorageClient;


    @Autowired
    private UserService userService;

    @PostMapping(value = "Wx/Rtu/Basesetting/{rtuCode}")
    @ResponseBody
    public JSONObject rtuBasesettingSetting(@PathVariable(name = "rtuCode") String rtuCode, HttpServletRequest request) {
        JSONObject response = new JSONObject();
        try {
            String openid = request.getParameter("openId");
            String baseSetting = request.getParameter("baseSetting");
            JSONObject settingData = JSONObject.parseObject(baseSetting);
            LogHelper.info(rtuCode + " " + openid + " " + baseSetting);
            response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_OK);
            RedisTemplate redisTemplate = DataProcessHolder.newInstance().dataProcess.redisTemplate;
            HashOperations<String, String, String> opsHash = redisTemplate.opsForHash();
            if (opsHash.hasKey(rtuCode, GBConstants.BASE_KEY_AGREEMENT)) {
                String agreement = opsHash.get(rtuCode, GBConstants.BASE_KEY_AGREEMENT);
                if (agreement.equals(GBConstants.AGREEMENT_KIND_SW)) {
                    String dataContent = "";
                    //测站编码
                    String newRtuCode = settingData.getString("newRtuCode");
                    if (null != newRtuCode && newRtuCode.length() > 0) {
                        byte[] buff = BytesHelp.createBcdBytes((byte) 0x02, newRtuCode);
                        dataContent += BytesHelp.byte2HexStr(buff);
                    }

                    boolean nextIp = false;
                    String ip1 = settingData.getString("ip1");
                    String ip1port = settingData.getString("ip1port");
                    //IP地址1
                    if (ip1 != null && ip1.length() > 0 && ip1port != null && ip1port.length() > 0) {
                        String v = ip1 + ":" + ip1port;
                        byte[] buff = BytesHelp.createIpBytes((byte) 0x04, v);
                        dataContent += BytesHelp.byte2HexStr(buff);
                        nextIp = true;
                    }
                    if (nextIp) {
                        nextIp = false;
                        String ip = settingData.getString("ip2");
                        String ipport = settingData.getString("ip2port");
                        //IP地址2
                        if (ip != null && ip.length() > 0 && ipport != null && ipport.length() > 0) {
                            String v = ip + ":" + ipport;
                            byte[] buff = BytesHelp.createIpBytes((byte) 0x06, v);
                            dataContent += BytesHelp.byte2HexStr(buff);
                            nextIp = true;
                        }
                    }
                    if (nextIp) {
                        String ip = settingData.getString("ip3");
                        String ipport = settingData.getString("ip3port");
                        //IP地址3
                        if (ip != null && ip.length() > 0 && ipport != null && ipport.length() > 0) {
                            String v = ip + ":" + ipport;
                            byte[] buff = BytesHelp.createIpBytes((byte) 0x08, v);
                            dataContent += BytesHelp.byte2HexStr(buff);
                            nextIp = true;
                        }
                    }
                    if (nextIp) {
                        String ip = settingData.getString("ip4");
                        String ipport = settingData.getString("ip4port");
                        //IP地址4
                        if (ip != null && ip.length() > 0 && ipport != null && ipport.length() > 0) {
                            String v = ip + ":" + ipport;
                            byte[] buff = BytesHelp.createIpBytes((byte) 0x0A, v);
                            dataContent += BytesHelp.byte2HexStr(buff);
                        }
                    }

                    String datagram = "7E7E";
                    datagram += rtuCode;
                    datagram += "01";
                    datagram += "0000";
                    datagram += "40";
                    //报文长度
                    byte[] bodyBuff = BytesHelp.int2Bytes(dataContent.length() / 2 + 2 + 6, 2);
                    datagram += "8" + BytesHelp.byte2HexStr(bodyBuff).substring(1);
                    datagram += "02";//起始符
                    datagram += "0001";//流水号
                    SimpleDateFormat timeFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                    datagram += timeFormat.format(new Date()).substring(2);//发报时间
                    datagram += dataContent;
                    //结束符
                    datagram += "05";
                    byte[] buff = BytesHelp.hexStr2Bytes(datagram);
                    byte[] crc16 = BytesHelp.crcFun2014(buff);
                    byte[] datagrambuff = BytesHelp.arrayApend(buff, crc16);//CRC16
                    datagram = BytesHelp.byte2HexStr(datagrambuff);
                    String funcCode = "40";
                    LogHelper.info("Manage-" + rtuCode + "-" + datagram);
                    DataProcess.SubmitCommand(rtuCode, datagram, funcCode, true);
                    DataProcess.DownloadNotify(rtuCode);
                } else if (agreement.equals(GBConstants.AGREEMENT_KIND_SZY)) {
                    String version = null;
                    if (opsHash.hasKey(rtuCode, GBConstants.BASE_KEY_ORGID)) {
                        String orgId = opsHash.get(rtuCode, GBConstants.BASE_KEY_ORGID);
                        if (null != orgId) {
                            if (opsHash.hasKey(orgId, GBConstants.BASE_KEY_VERSION)) {
                                version = opsHash.get(orgId, GBConstants.BASE_KEY_VERSION);
                            }
                        }
                    }
                    if (opsHash.hasKey(rtuCode, GBConstants.BASE_KEY_VERSION)) {
                        version = opsHash.get(rtuCode, GBConstants.BASE_KEY_VERSION);
                    }
                    if (null != version && version.length() > 0 && version.equals(GBConstants.VERSION_KEY_SZY_54)) {
                        String setting = opsHash.get(rtuCode, GBConstants.BASE_KEY_SETTING);
                        if (null != setting) {
                            byte[] settingBuff = BytesHelp.hexStr2Bytes(setting);
                            int count = 0;
                            SimpleDateFormat timeFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                            byte[] dataContent = BytesHelp.hexStr2Bytes("30");
                            dataContent = BytesHelp.arrayApend(dataContent, BytesHelp.hexStr2Bytes(rtuCode));
                            dataContent = BytesHelp.arrayApend(dataContent, BytesHelp.hexStr2Bytes("88"));
                            dataContent = BytesHelp.arrayApend(dataContent, BytesHelp.subBytes(settingBuff, 0, 5));
                            count += 5;
                            int ipNum = 0;
                            String ipContent = "";
                            boolean nextIp = false;
                            String ip1 = settingData.getString("ip1");
                            String ip1port = settingData.getString("ip1port");
                            //IP地址1
                            if (ip1 != null && ip1.length() > 0 && ip1port != null && ip1port.length() > 0) {
                                nextIp = true;
                                ipNum += 1;
                            }
                            if (nextIp) {
                                nextIp = false;
                                String ip = settingData.getString("ip2");
                                String ipport = settingData.getString("ip2port");
                                //IP地址2
                                if (ip != null && ip.length() > 0 && ipport != null && ipport.length() > 0) {
                                    nextIp = true;
                                    ipNum += 1;
                                }
                            }
                            if (nextIp) {
                                String ip = settingData.getString("ip3");
                                String ipport = settingData.getString("ip3port");
                                //IP地址3
                                if (ip != null && ip.length() > 0 && ipport != null && ipport.length() > 0) {
                                    nextIp = true;
                                    ipNum += 1;
                                }
                            }
                            if (nextIp) {
                                String ip = settingData.getString("ip4");
                                String ipport = settingData.getString("ip4port");
                                //IP地址4
                                if (ip != null && ip.length() > 0 && ipport != null && ipport.length() > 0) {
                                    ipNum += 1;
                                }
                            }
                            if (ipNum > 0) {
                                byte[] ipNumBuff = new byte[1];
                                ipNumBuff[0] = (byte) ipNum;
                                dataContent = BytesHelp.arrayApend(dataContent, ipNumBuff);
                                count += 1;
                                dataContent = BytesHelp.arrayApend(dataContent, BytesHelp.subBytes(settingBuff, count, 60));
                                count += 60;
                                byte[] ipbuff = new byte[0];
                                byte[] portbuff = new byte[0];
                                //IP地址
                                for (int i = 1; i <= 4; i++) {
                                    if (i <= ipNum) {
                                        String ip = settingData.getString("ip" + i);
                                        String ipport = settingData.getString("ip" + i + "port");
                                        String[] texts = ip.split("[.]");
                                        String newIp = String.format("%03d", Integer.parseInt(texts[0]));
                                        newIp += "." + String.format("%03d", Integer.parseInt(texts[1]));
                                        newIp += "." + String.format("%03d", Integer.parseInt(texts[2]));
                                        newIp += "." + String.format("%03d", Integer.parseInt(texts[3]));
                                        ipbuff = BytesHelp.arrayApend(ipbuff, newIp.getBytes());
                                        portbuff = BytesHelp.arrayApend(portbuff, BytesHelp.int2Bytes(Integer.parseInt(ipport), 2));
                                    } else {
                                        ipbuff = BytesHelp.arrayApend(ipbuff, "000.000.000.000".getBytes());
                                        portbuff = BytesHelp.arrayApend(portbuff, BytesHelp.int2Bytes(0, 2));
                                    }
                                }
                                dataContent = BytesHelp.arrayApend(dataContent, ipbuff);
                                dataContent = BytesHelp.arrayApend(dataContent, portbuff);
                                count += 60;
                                count += 8;
                                dataContent = BytesHelp.arrayApend(dataContent, BytesHelp.subBytes(settingBuff, count, 44));
                                count += 44;
                                //pw
                                dataContent = BytesHelp.arrayApend(dataContent, BytesHelp.hexStr2Bytes("0000"));
                                count += 2;
                                //tp
                                String tp = timeFormat.format(new Date());
                                dataContent = BytesHelp.arrayApend(dataContent, BytesHelp.hexStr2Bytes(tp.substring(tp.length() - 2, tp.length())));
                                dataContent = BytesHelp.arrayApend(dataContent, BytesHelp.hexStr2Bytes(tp.substring(tp.length() - 4, tp.length() - 2)));
                                dataContent = BytesHelp.arrayApend(dataContent, BytesHelp.hexStr2Bytes(tp.substring(tp.length() - 6, tp.length() - 4)));
                                dataContent = BytesHelp.arrayApend(dataContent, BytesHelp.hexStr2Bytes(tp.substring(tp.length() - 8, tp.length() - 6)));
                                dataContent = BytesHelp.arrayApend(dataContent, BytesHelp.hexStr2Bytes("00"));
                                count += 5;
                                byte[] lenBuff = new byte[1];
                                byte[] crc = new byte[1];
                                crc[0] = BytesHelp.GetCRCByte(dataContent);
                                lenBuff[0] = (byte) dataContent.length;
                                String datagram = "68" + BytesHelp.byte2HexStr(lenBuff) + "68" + BytesHelp.byte2HexStr(dataContent) + BytesHelp.byte2HexStr(crc) + "16";
                                byte[] datagrambuff = BytesHelp.hexStr2Bytes(datagram);
                                String funcCode = "88";
                                LogHelper.info("Manage-" + rtuCode + "-" + datagram);
                                DataProcess.SubmitCommand(rtuCode, datagram, funcCode, true);
                                DataProcess.DownloadNotify(rtuCode);
                            } else {
                                LogHelper.info("rtu setting error:" + rtuCode + "ip配置数量至少1个");
                            }
                        }
                    } else {
                        String newRtuCode = settingData.getString("newRtuCode");
                        if (null != newRtuCode && newRtuCode.length() > 0) {
                            SimpleDateFormat timeFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                            String dataContent = "";
                            String v = settingData.getString("newRtuCode");
                            dataContent += v;
                            dataContent += "0000";
                            String tp = timeFormat.format(new Date());
                            int count = tp.length();
                            dataContent += tp.substring(count - 2, count);
                            count -= 2;
                            dataContent += tp.substring(count - 2, count);
                            count -= 2;
                            dataContent += tp.substring(count - 2, count);
                            count -= 2;
                            dataContent += tp.substring(count - 2, count);
                            count -= 2;
                            dataContent += "00";
                            byte[] lenBuff = new byte[1];
                            String content = "30" + rtuCode + "10" + dataContent;
                            byte[] buff = BytesHelp.hexStr2Bytes(content);
                            byte[] crc = new byte[1];
                            crc[0] = BytesHelp.GetCRCByte(buff);
                            lenBuff[0] = (byte) buff.length;
                            String datagram = "68" + BytesHelp.byte2HexStr(lenBuff) + "68" + content + BytesHelp.byte2HexStr(crc) + "16";
                            byte[] datagrambuff = BytesHelp.hexStr2Bytes(datagram);
                            Date now = new Date();
                            String funcCode = "10";
                            LogHelper.info("Manage-" + rtuCode + "-" + datagram);
                            DataProcess.SubmitCommand(rtuCode, datagram, funcCode, true);
                            DataProcess.DownloadNotify(rtuCode);
                        } else {
                            String dataContent = "";
                            boolean nextIp = false;
                            String ip1 = settingData.getString("ip1");
                            String ip1port = settingData.getString("ip1port");
                            //IP地址1
                            if (ip1 != null && ip1.length() > 0 && ip1port != null && ip1port.length() > 0) {
                                String v = ip1 + ":" + ip1port;
                                byte[] buff = BytesHelp.createIpBytes((byte) 0x04, v);
                                dataContent += BytesHelp.byte2HexStr(buff);
                                nextIp = true;
                            }
                            if (nextIp) {
                                nextIp = false;
                                String ip = settingData.getString("ip2");
                                String ipport = settingData.getString("ip2port");
                                //IP地址2
                                if (ip != null && ip.length() > 0 && ipport != null && ipport.length() > 0) {
                                    String v = ip + ":" + ipport;
                                    byte[] buff = BytesHelp.createIpBytes((byte) 0x06, v);
                                    dataContent += BytesHelp.byte2HexStr(buff);
                                    nextIp = true;
                                }
                            }
                            if (nextIp) {
                                String ip = settingData.getString("ip3");
                                String ipport = settingData.getString("ip3port");
                                //IP地址3
                                if (ip != null && ip.length() > 0 && ipport != null && ipport.length() > 0) {
                                    String v = ip + ":" + ipport;
                                    byte[] buff = BytesHelp.createIpBytes((byte) 0x08, v);
                                    dataContent += BytesHelp.byte2HexStr(buff);
                                    nextIp = true;
                                }
                            }
                            if (nextIp) {
                                String ip = settingData.getString("ip4");
                                String ipport = settingData.getString("ip4port");
                                //IP地址4
                                if (ip != null && ip.length() > 0 && ipport != null && ipport.length() > 0) {
                                    String v = ip + ":" + ipport;
                                    byte[] buff = BytesHelp.createIpBytes((byte) 0x0A, v);
                                    dataContent += BytesHelp.byte2HexStr(buff);
                                }
                            }
                            SimpleDateFormat timeFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                            byte[] lenBuff = new byte[1];
                            String content = "30" + rtuCode + "E7" + dataContent;
                            byte[] buff = BytesHelp.hexStr2Bytes(content);
                            byte[] crc = new byte[1];
                            crc[0] = BytesHelp.GetCRCByte(buff);
                            lenBuff[0] = (byte) buff.length;
                            String datagram = "68" + BytesHelp.byte2HexStr(lenBuff) + "68" + content + BytesHelp.byte2HexStr(crc) + "16";
                            byte[] datagrambuff = BytesHelp.hexStr2Bytes(datagram);
                            Date now = new Date();
                            String funcCode = "E7";
                            LogHelper.info("Manage-" + rtuCode + "-" + datagram);
                            DataProcess.SubmitCommand(rtuCode, datagram, funcCode, true);
                            DataProcess.DownloadNotify(rtuCode);
                        }
                        response.put("msg", "指令已发送");
                    }
                } else {
                    LogHelper.info("dont know agreement");
                    response.put("msg", "测站没设置规约");
                    response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_ERROR);
                }
            } else {
                LogHelper.info("dont know agreement");
                response.put("msg", "测站没设置规约");
                response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_ERROR);
            }
        } catch (Exception e) {
            LogHelper.error(e);
            response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_ERROR);
        }
        return response;
    }

    @PostMapping(value = "Wx/Rtu/Runsetting/{rtuCode}")
    @ResponseBody
    public JSONObject rtuRunsettingSetting(@PathVariable(name = "rtuCode") String rtuCode, HttpServletRequest request) {
        JSONObject response = new JSONObject();
        try {
            String openid = request.getParameter("openId");
            String runSetting = request.getParameter("runSetting");
            JSONObject jsonData = JSONObject.parseObject(runSetting);
            LogHelper.info(rtuCode + " " + openid + " " + runSetting);
            response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_OK);
            JSONObject respones = new JSONObject();

            respones.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_ERROR);
            RedisTemplate redisTemplate = DataProcessHolder.newInstance().dataProcess.redisTemplate;
            HashOperations<String, String, String> opsHash = redisTemplate.opsForHash();
            if (opsHash.hasKey(rtuCode, GBConstants.BASE_KEY_AGREEMENT)) {
                String agreement = opsHash.get(rtuCode, GBConstants.BASE_KEY_AGREEMENT);
                if (agreement.equals(GBConstants.AGREEMENT_KIND_SW)) {

                    String dataContent = "";
                    //定时报时间间隔
                    if (jsonData.containsKey("intervalTime")) {
                        String v = jsonData.getString("intervalTime");
                        byte[] buff = BytesHelp.createValueBytes((byte) 0x20, v, 0, 1);
                        dataContent += BytesHelp.byte2HexStr(buff);
                    }


                    //加报时间间隔
                    if (jsonData.containsKey("addIntervalTime")) {
                        String v = jsonData.getString("addIntervalTime");
                        byte[] buff = BytesHelp.createValueBytes((byte) 0x21, v, 0, 1);
                        dataContent += BytesHelp.byte2HexStr(buff);
                    }


                    //日降水量起始时间
                    if (jsonData.containsKey("rainTime")) {
                        String v = jsonData.getString("rainTime");
                        byte[] buff = BytesHelp.createValueBytes((byte) 0x22, v, 0, 1);
                        dataContent += BytesHelp.byte2HexStr(buff);
                    }


                    //采样间隔
                    if (jsonData.containsKey("collectInterval")) {
                        String v = jsonData.getString("collectInterval");
                        byte[] buff = BytesHelp.createValueBytes((byte) 0x23, v, 0, 2);
                        dataContent += BytesHelp.byte2HexStr(buff);
                    }


                    //数据存储间隔
                    if (jsonData.containsKey("dataSaveInterval")) {
                        String v = jsonData.getString("dataSaveInterval");
                        byte[] buff = BytesHelp.createValueBytes((byte) 0x24, v, 0, 1);
                        dataContent += BytesHelp.byte2HexStr(buff);
                    }


                    //雨量加报阀值
                    if (jsonData.containsKey("rainAddValue")) {
                        String v = jsonData.getString("rainAddValue");
                        byte[] buff = BytesHelp.createValueBytes((byte) 0x27, v, 0, 1);
                        dataContent += BytesHelp.byte2HexStr(buff);
                    }


                    //水位基值
                    if (jsonData.containsKey("waterLevelBase")) {
                        String v = jsonData.getString("waterLevelBase");
                        byte[] buff = BytesHelp.createValueBytes((byte) 0x28, v, 3, 4);
                        dataContent += BytesHelp.byte2HexStr(buff);
                    }


                    //水位修正基值
                    if (jsonData.containsKey("waterLevelCorrectValue")) {
                        String v = jsonData.getString("waterLevelCorrectValue");
                        byte[] buff = BytesHelp.createValueBytes((byte) 0x30, v, 3, 4);
                        dataContent += BytesHelp.byte2HexStr(buff);
                    }


                    //加报水位
                    if (jsonData.containsKey("addWaterLevel")) {
                        String v = jsonData.getString("addWaterLevel");
                        byte[] buff = BytesHelp.createValueBytes((byte) 0x38, v, 2, 2);
                        dataContent += BytesHelp.byte2HexStr(buff);
                    }


                    //水位以上加报阀值
                    if (jsonData.containsKey("addWaterUpValue")) {
                        String v = jsonData.getString("addWaterUpValue");
                        byte[] buff = BytesHelp.createValueBytes((byte) 0x40, v, 2, 2);
                        dataContent += BytesHelp.byte2HexStr(buff);
                    }


                    //水位以下加报阀值
                    if (jsonData.containsKey("addWaterDownValue")) {
                        String v = jsonData.getString("addWaterDownValue");
                        byte[] buff = BytesHelp.createValueBytes((byte) 0x41, v, 2, 2);
                        dataContent += BytesHelp.byte2HexStr(buff);
                    }


                    //流量加报阀值
                    if (jsonData.containsKey("flowValue")) {
                        String v = jsonData.getString("flowValue");
                        byte[] buff = BytesHelp.createValueBytes((byte) 0x42, v, 3, 3);
                        dataContent += BytesHelp.byte2HexStr(buff);
                    }


                    //流速加报阀值
                    if (jsonData.containsKey("flowSpeetValue")) {
                        String v = jsonData.getString("flowSpeetValue");
                        byte[] buff = BytesHelp.createValueBytes((byte) 0x43, v, 3, 3);
                        dataContent += BytesHelp.byte2HexStr(buff);
                    }


                    //闸位加报阀值
                    if (jsonData.containsKey("waterGateValue")) {
                        String v = jsonData.getString("waterGateValue");
                        byte[] buff = BytesHelp.createValueBytes((byte) 0x44, v, 2, 2);
                        dataContent += BytesHelp.byte2HexStr(buff);
                    }


                    if (null != dataContent && dataContent.length() > 0) {

                        String datagram = "7E7E";
                        datagram += rtuCode;
                        datagram += "01";
                        datagram += "0000";
                        datagram += "42";
                        //报文长度
                        byte[] bodyBuff = BytesHelp.int2Bytes(dataContent.length() / 2 + 2 + 6, 2);
                        datagram += "8" + BytesHelp.byte2HexStr(bodyBuff).substring(1);
                        datagram += "02";//起始符
                        datagram += "0001";//流水号
                        SimpleDateFormat timeFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                        datagram += timeFormat.format(new Date()).substring(2);//发报时间
                        datagram += dataContent;
                        //结束符
                        datagram += "05";
                        byte[] buff = BytesHelp.hexStr2Bytes(datagram);
                        byte[] crc16 = BytesHelp.crcFun2014(buff);
                        byte[] datagrambuff = BytesHelp.arrayApend(buff, crc16);//CRC16

                        Date now = new Date();

                        datagram = BytesHelp.byte2HexStr(datagrambuff);
                        String funcCode = "42";
                        LogHelper.info("Manage-" + rtuCode + "-" + datagram);
                        DataProcess.SubmitCommand(rtuCode, datagram, funcCode, true);
                        DataProcess.DownloadNotify(rtuCode);
                        respones.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_OK);
                    }

                } else if (agreement.equals(GBConstants.AGREEMENT_KIND_SZY)) {
                    String datagram = DataTemplateSzyCA1.createDatagram(rtuCode, jsonData);
                    if (null != datagram) {
                        String funcCode = "A1";
                        LogHelper.info("Manage-" + rtuCode + "-" + datagram);
                        DataProcess.SubmitCommand(rtuCode, datagram, funcCode, true);
                        DataProcess.DownloadNotify(rtuCode);
                    } else {
                        LogHelper.info(rtuCode + " 报文产生失败");
                    }
                } else {
                    LogHelper.info("dont know agreement");
                    response.put("msg", "测站没设置规约");
                    response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_ERROR);
                }
            } else {
                LogHelper.info("dont know agreement");
                response.put("msg", "测站没设置规约");
                response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_ERROR);
            }
        } catch (Exception e) {
            LogHelper.error(e);
            response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_ERROR);
        }
        return response;
    }


    /**
     * 恢复出厂设置
     *
     * @param rtuCode
     * @param openId
     * @return
     */
    @GetMapping(value = "Wx/Rtu/Reset/{rtuCode}")
    @ResponseBody
    public JSONObject rtuReset(@PathVariable(name = "rtuCode") String rtuCode, @RequestParam String openId) {
        JSONObject response = new JSONObject();
        try {
            LogHelper.info(openId + " 重启 ：" + rtuCode);
            Date dt = new Date();

            RedisTemplate redisTemplate = DataProcessHolder.newInstance().dataProcess.redisTemplate;
            HashOperations<String, String, String> opsHash = redisTemplate.opsForHash();
            response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_OK);
            if (opsHash.hasKey(rtuCode, GBConstants.BASE_KEY_AGREEMENT)) {
                String agreement = opsHash.get(rtuCode, GBConstants.BASE_KEY_AGREEMENT);
                if (agreement.equals(GBConstants.AGREEMENT_KIND_SW)) {

//                    String datagram=DatagramHelp.DatagramSwClockSet(rtuCode,dt);
//                    String funcCode = "F3";
//                    LogHelper.info("Manage-" + rtuCode + "-" + datagram);
//                    DataProcess.SubmitCommand(rtuCode, datagram, funcCode, true);
//                    DataProcess.DownloadNotify(rtuCode);

                } else if (agreement.equals(GBConstants.AGREEMENT_KIND_SZY)) {
                    String version = null;
                    if (opsHash.hasKey(rtuCode, GBConstants.BASE_KEY_ORGID)) {
                        String orgId = opsHash.get(rtuCode, GBConstants.BASE_KEY_ORGID);
                        if (null != orgId) {
                            if (opsHash.hasKey(orgId, GBConstants.BASE_KEY_VERSION)) {
                                version = opsHash.get(orgId, GBConstants.BASE_KEY_VERSION);
                            }
                        }
                    }
                    if (opsHash.hasKey(rtuCode, GBConstants.BASE_KEY_VERSION)) {
                        version = opsHash.get(rtuCode, GBConstants.BASE_KEY_VERSION);
                    }
                    if (null != version && version.length() > 0 && version.equals(GBConstants.VERSION_KEY_SZY_54)) {

//                        String datagram = DatagramHelp.DatagramSzyClockSet(rtuCode,dt);
//                        String funcCode = "90";
//                        LogHelper.info("Manage-" + rtuCode + "-" + datagram);
//                        DataProcess.SubmitCommand(rtuCode, datagram, funcCode, true);
//                        DataProcess.DownloadNotify(rtuCode);
                    } else {
//                        byte[] respPacket_h = BytesHelp.hexStr2Bytes("680768");  //帧起始符
//                        byte[] respPacket = BytesHelp.hexStr2Bytes("30");//中心站地址
//                        respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.hexStr2Bytes(rtuCode));//遥测站地址
//                        respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.hexStr2Bytes("F3"));//功能码
//                        byte[]crc = new byte[1]; //系统计算的校验码
//                        crc[0] = BytesHelp.GetCRCByte(respPacket);
//                        respPacket = BytesHelp.arrayApend(respPacket_h, respPacket);
//                        respPacket = BytesHelp.arrayApend(respPacket, crc);//CRC
//                        respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.hexStr2Bytes("16"));
//                        String datagram= BytesHelp.byte2HexStr(respPacket);
//                        String funcCode = "F3";
//                        LogHelper.info("Manage-" + rtuCode + "-" + datagram);
//                        DataProcess.SubmitCommand(rtuCode, datagram, funcCode, true);
//                        DataProcess.DownloadNotify(rtuCode);
                    }
                } else {
                    LogHelper.info("dont know agreement");
                    response.put("msg", "测站没设置规约");
                    response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_ERROR);
                }
            } else {
                LogHelper.info("dont know agreement");
                response.put("msg", "测站没设置规约");
                response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_ERROR);
            }
        } catch (Exception e) {
            LogHelper.error(e);
            response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_ERROR);
        }
        return response;
    }

    /**
     * 同步RTU时钟
     *
     * @param rtuCode
     * @param openId
     * @return
     */
    @GetMapping(value = "Wx/Rtu/Reclock/{rtuCode}")
    @ResponseBody
    public JSONObject rtuClock(@PathVariable(name = "rtuCode") String rtuCode, @RequestParam String openId) {
        JSONObject response = new JSONObject();
        try {
            LogHelper.info(openId + " 同步时钟 ：" + rtuCode);
            Date dt = new Date();
            RedisTemplate redisTemplate = DataProcessHolder.newInstance().dataProcess.redisTemplate;
            HashOperations<String, String, String> opsHash = redisTemplate.opsForHash();
            response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_OK);
            if (opsHash.hasKey(rtuCode, GBConstants.BASE_KEY_AGREEMENT)) {
                String agreement = opsHash.get(rtuCode, GBConstants.BASE_KEY_AGREEMENT);
                if (agreement.equals(GBConstants.AGREEMENT_KIND_SW)) {

                    String datagram = DatagramHelp.GetDatagramClockSetSw(rtuCode, dt);
                    String funcCode = "4A";
                    LogHelper.info("Manage-" + rtuCode + "-" + datagram);
                    DataProcess.SubmitCommand(rtuCode, datagram, funcCode, true);
                    DataProcess.DownloadNotify(rtuCode);
                } else if (agreement.equals(GBConstants.AGREEMENT_KIND_SZY)) {

                    String datagram = DatagramHelp.GetDatagramClockSetSzy(rtuCode, dt);
                    String funcCode = "11";
                    LogHelper.info("Manage-" + rtuCode + "-" + datagram);
                    DataProcess.SubmitCommand(rtuCode, datagram, funcCode, true);
                    DataProcess.DownloadNotify(rtuCode);

                } else {
                    LogHelper.info("dont know agreement");
                    response.put("msg", "测站没设置规约");
                    response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_ERROR);
                }
            } else {
                LogHelper.info("dont know agreement");
                response.put("msg", "测站没设置规约");
                response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_ERROR);
            }
        } catch (Exception e) {
            LogHelper.error(e);
            response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_ERROR);
        }
        return response;
    }

    /**
     * 重启RTU
     *
     * @param rtuCode
     * @param openId
     * @return
     */
    @GetMapping(value = "Wx/Rtu/Reboot/{rtuCode}")
    @ResponseBody
    public JSONObject rtuReboot(@PathVariable(name = "rtuCode") String rtuCode, @RequestParam String openId) {
        JSONObject response = new JSONObject();
        try {
            LogHelper.info(openId + " 重启 ：" + rtuCode);
            Date dt = new Date();

            RedisTemplate redisTemplate = DataProcessHolder.newInstance().dataProcess.redisTemplate;
            HashOperations<String, String, String> opsHash = redisTemplate.opsForHash();
            response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_OK);
            if (opsHash.hasKey(rtuCode, GBConstants.BASE_KEY_AGREEMENT)) {
                String agreement = opsHash.get(rtuCode, GBConstants.BASE_KEY_AGREEMENT);
                if (agreement.equals(GBConstants.AGREEMENT_KIND_SW)) {

                    String datagram = DatagramHelp.GetDatagramResetSw(rtuCode, dt);
                    String funcCode = "F3";
                    LogHelper.info("Manage-" + rtuCode + "-" + datagram);
                    DataProcess.SubmitCommand(rtuCode, datagram, funcCode, true);
                    DataProcess.DownloadNotify(rtuCode);
                } else if (agreement.equals(GBConstants.AGREEMENT_KIND_SZY)) {
                    String version = null;
                    if (opsHash.hasKey(rtuCode, GBConstants.BASE_KEY_ORGID)) {
                        String orgId = opsHash.get(rtuCode, GBConstants.BASE_KEY_ORGID);
                        if (null != orgId) {
                            if (opsHash.hasKey(orgId, GBConstants.BASE_KEY_VERSION)) {
                                version = opsHash.get(orgId, GBConstants.BASE_KEY_VERSION);
                            }
                        }
                    }
                    if (opsHash.hasKey(rtuCode, GBConstants.BASE_KEY_VERSION)) {
                        version = opsHash.get(rtuCode, GBConstants.BASE_KEY_VERSION);
                    }
                    if (null != version && version.length() > 0 && version.equals(GBConstants.VERSION_KEY_SZY_54)) {

                        String datagram = DatagramHelp.GetDatagramRebootSzyV1(rtuCode, dt);
                        String funcCode = "90";
                        LogHelper.info("Manage-" + rtuCode + "-" + datagram);
                        DataProcess.SubmitCommand(rtuCode, datagram, funcCode, true);
                        DataProcess.DownloadNotify(rtuCode);
                    } else {

                        String datagram = DatagramHelp.GetDatagramRebootSzyV2(rtuCode, dt);

                        String funcCode = "F3";
                        LogHelper.info("Manage-" + rtuCode + "-" + datagram);
                        DataProcess.SubmitCommand(rtuCode, datagram, funcCode, true);
                        DataProcess.DownloadNotify(rtuCode);
                    }
                } else {
                    LogHelper.info("dont know agreement");
                    response.put("msg", "测站没设置规约");
                    response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_ERROR);
                }
            } else {
                LogHelper.info("dont know agreement");
                response.put("msg", "测站没设置规约");
                response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_ERROR);
            }
        } catch (Exception e) {
            LogHelper.error(e);
            response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_ERROR);
        }
        return response;
    }

    @GetMapping(value = "Wx/Service/Notify")
    @ResponseBody
    public JSONObject WxServiceNotify(@RequestParam(name = "signature") String signature, @RequestParam(name = "timestamp") String timestamp, @RequestParam(name = "nonce") String nonce) {
        String token = "Dh82828800@dahengsi";
        ArrayList tmpArr = new ArrayList();
        tmpArr.add(token);
        tmpArr.add(timestamp);
        tmpArr.add(nonce);
        tmpArr.sort(new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                return 0;
            }
        });

//        sort($tmpArr, SORT_STRING);
//        $tmpStr = implode( $tmpArr );
//        $tmpStr = sha1( $tmpStr );
//
//        if ($tmpStr == $signature ) {
//            return true;
//        } else {
//            return false;
//        }
        return null;
    }

    @GetMapping(value = "Wx/Rtu/History")
    @ResponseBody
    public JSONObject RtuHistory(@RequestParam(name = "openid") String openid) {
        JSONObject response = new JSONObject();
        try {
            response.put("openId", openid);
            Map<String, Object> user = wxService.userByOpenId(openid);
            if (null != user) {
                String orgId = wxService.getOrgInfoOfUser((String) user.get("ID"));
                List<Map<String, Object>> list = wxService.HistoryList(orgId);
                if (null != list) {
                    JSONArray historyList = new JSONArray();
                    for (Map<String, Object> r : list) {
                        String id = (String) r.get("id");
                        String rtuCode = (String) r.get("rtuCode");
                        String openId = (String) r.get("openId");
                        JSONObject data = wxService.RtuBaseInfo(rtuCode);
                        data.put("id", id);
                        data.put("openId", openId);
                        data.put("rtuCode", rtuCode);

                        historyList.add(data);
                    }
                    response.put("data", historyList);
                } else {
                    list = new LinkedList<>();
                    response.put("data", list);
                }
            } else {
                List<Map<String, Object>> list = new LinkedList<>();
                response.put("data", list);
            }
            response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_OK);
        } catch (Exception e) {
            LogHelper.error(e);
            response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_ERROR);
        }
        return response;
    }


    @GetMapping(value = "Wx/Rtu/List")
    @ResponseBody
    public JSONObject RtuList(@RequestParam(name = "rtuCode") String rtuCode, @RequestParam(name = "openId") String openId) {
        JSONObject response = new JSONObject();
        try {
            Map<String, Object> user = wxService.userByOpenId(openId);
            if (null != user) {
                String orgId = wxService.getOrgInfoOfUser((String) user.get("ID"));

                JSONArray list = this.wxService.rtuList(openId, rtuCode, rtuCode, orgId);
                response.put("data", list);
            } else {

                List<Map<String, Object>> list = new LinkedList<>();
                response.put("data", list);
            }
            response.put("rtuCode", rtuCode);
            response.put("openId", openId);
            response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_OK);

        } catch (Exception e) {
            LogHelper.error(e);
            response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_ERROR);
        }
        return response;
    }

    @GetMapping(value = "Wx/Datagram/Text/{datagramHex}")
    @ResponseBody
    public JSONObject toDatagramText(@PathVariable(name = "datagramHex") String datagramHex) {
        JSONObject response = new JSONObject();
        try {
            if (null != datagramHex) {
                JSONObject data = new JSONObject();
                List<JSONObject> datagramText = DatagramHelp.toDatagramString(datagramHex);
                data.put("datagramInfo", datagramText);
                response.put("data", data);
                response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_OK);
            } else {
                response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_ERROR);
            }
        } catch (Exception e) {
            LogHelper.error(e);
            response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_ERROR);
        }
        return response;
    }


    @GetMapping(value = "Wx/Rtu/{rtuCode}")
    @ResponseBody
    public JSONObject RtuInfo(@PathVariable(name = "rtuCode") String rtuCode, @RequestParam(name = "openid") String openid) {
        JSONObject response = new JSONObject();
        try {
            if (null != rtuCode && null != openid) {
                JSONObject data = new JSONObject();
                HashOperations<String, String, String> opsHash = redisTemplate.opsForHash();
                if (redisTemplate.hasKey(rtuCode)) {
                    String rtuName = opsHash.get(rtuCode, "rtuName");
                    if (null != rtuName) {
                        data.put("rtuName", rtuName);
                    } else {
                        data.put("rtuName", rtuCode);
                    }
                    data.put("baseInfo", wxService.RtuBaseInfo(rtuCode));
                    data.put("statusInfo", wxService.RtuStatusInfo(rtuCode));
                    data.put("datagramInfo", wxService.RtuLastDatagram(rtuCode));
                }
                //    JSONObject data = wxService.FindRtu(rtuCode);
                response.put("rtuCode", rtuCode);
                response.put("openId", openid);
                response.put("data", data);
                response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_OK);
                wxService.RecordFindHistory(rtuCode, openid);
            } else {
                response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_ERROR);
            }
        } catch (Exception e) {
            LogHelper.error(e);
            response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_ERROR);
        }
        return response;
    }


    private JSONObject getWxOpenId(String code) {
        try {
            String url = "https://api.weixin.qq.com/sns/jscode2session?appid=";
            url += this.wxAppId;
            url += "&secret=";
            url += this.wxSecret;
            url += "&js_code=";
            url += code;
            url += "&grant_type=authorization_code";
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> wxresponse = restTemplate.getForEntity(url, String.class);
            if (wxresponse.getStatusCode() == HttpStatus.OK) {
                //System.out.println(wxresponse.getBody());
                JSONObject body = JSONObject.parseObject(wxresponse.getBody());
                LogHelper.info("wx get openid " + body.toJSONString());
                if (body.containsKey("openid")) {
                    //正常返回的JSON数据包
//                 {
//                     "openid": "OPENID",
//                         "session_key": "SESSIONKEY",
//                 }

//满足UnionID返回条件时，返回的JSON数据包
//                 {
//                     "openid": "OPENID",
//                         "session_key": "SESSIONKEY",
//                         "unionid": "UNIONID"
//                 }
//
                    return body;
                }
            }
        } catch (Exception e) {
            LogHelper.error(e);
        }
        return null;
    }


    private JSONObject wxUserCheck(String user, String password) {
        JSONObject result = new JSONObject();

        //  String p = DigestUtils.md5DigestAsHex("82828800".getBytes());
        //    p+="swp";
        // p =  MD5Utils.md5(p);
//            p+="fbcacfeba1443b8f428282e6a7af9344";
        //    p  = "dh@82828800";
        //   p = DigestUtils.md5DigestAsHex(p.getBytes());

        //   p =  MD5Utils.md5(p);
        //   user.setSalt(this.randomNumberGenerator.nextBytes().toHex());
        //     String newPassword = (new SimpleHash("md5", p , ByteSource.Util.bytes("fbcacfeba1443b8f428282e6a7af9344"), 2)).toHex();

        Map<String, Object> userInfo = this.wxService.user(user);
        if (null != userInfo) {
            String userPassword = (String) userInfo.get("PASSWORD");
            String salt = (String) userInfo.get("SALT");
            String pw = (new SimpleHash("md5", password, ByteSource.Util.bytes(user + salt), 2)).toHex();
            if (pw.equals(userPassword)) {
                result.put("code", '0');
            } else {
                result.put("code", '1');
                result.put("msg", "密码错误");
            }
        } else {
            result.put("code", '1');
            result.put("msg", "您的账号是无效账号");
        }


//        try {
//            String error = "";
//            Subject subject = SecurityUtils.getSubject();
//            UsernamePasswordToken token = new UsernamePasswordToken(user, password);
//            try {
//                subject.login(token);
//            } catch (UnknownAccountException e) {
//                error = "用户名/密码错误";
//            } catch (IncorrectCredentialsException e) {
//                error = "用户名/密码错误";
//            } catch (AuthenticationException e) {
//                error = "其他错误：" + e.getMessage();
//            } catch (Exception e) {
//                error = "未知错误：" + e.getMessage();
//            }
//            if (StringUtils.isBlank(error)) {
//                UserService ser = JpaApplicationContext.getBean(UserService.class);
//                TAuUser nuser = ser.getUserByLoginId(user);
//                if (nuser.getIsValid() == 0) {
//                    error = "您的账号是无效账号";
//                    result.put("code", '1');
//                    result.put("msg", error);
//                } else {
//                    result.put("code", '0');
//                }
//            } else {
//                result.put("code", '1');
//                result.put("msg", error);
//            }
//        } catch (Exception e) {
//            result.put("code", '1');
//        }
        return result;
    }


    @GetMapping(value = "Wx/Login")
    @ResponseBody
    public JSONObject Login(@RequestParam(name = "code") String code, @RequestParam(name = "user") String user, @RequestParam(name = "password") String password) {
        JSONObject response = new JSONObject();
        try {
            LogHelper.info("wx login code " + code);
            //response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_ERROR);
            //   RestTemplate restTemplate = new RestTemplate();
            //  JSONObject result = restTemplate.getForObject(new URI(DataProcessHolder.newInstance().dataProcess.config.getTaishanNotifyUrl() + "/rtuManage/wx/user?user=" + user + "&password=" + password), JSONObject.class);
            JSONObject result = this.wxUserCheck(user, password);
            if (null != result) {
                if (result.getString("code").equals("0")) {
                    JSONObject wxInfo = this.getWxOpenId(code);
                    if (null != wxInfo) {
                        String openid = wxInfo.getString("openid");
                        if (null != openid) {
                            this.wxService.updateWx(openid, user);
                            response.put("openId", openid);
                            //  response.put("sessionKey", wxInfo.getString("session_key"));
//                             response.put("reg", "1");
//                             response.put("userId", user);
//                             response.put("headIcon", "1.png");
//                             response.put("nick", (String) userInfo.get("USER_NAME"));
                            response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_OK);
                        } else {
                            response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_ERROR);
                            response.put("msg", "获取微信ID失败");
                        }
                    } else {
                        response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_ERROR);
                        response.put("msg", "获取微信ID失败");
                    }
                } else {
                    response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_ERROR);
                    response.put("msg", result.getString("msg"));
                }
            } else {
                response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_ERROR);
                response.put("msg", "验证失败");
            }

//            String pw = DigestUtils.md5DigestAsHex(password.getBytes());
//            pw = pw + user + "5393fe06b0e2261f9f252b08202162ce";
//            pw = DigestUtils.md5DigestAsHex(pw.getBytes());//e6513e8a081b6865b23f851bfafc3cea
            // response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_ERROR);

//            Map<String, Object> userInfo = this.wxService.user(user, pw);
//            if (null != userInfo) {
//                response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_OK);
//
//                 this.wxService.updateWx(openid, (String) userInfo.get("ID"));
//
//                JSONObject wxInfo = this.getWxOpenId(code);
//                if (null != wxInfo) {
//                    String openid = wxInfo.getString("openid");
//                    Map<String, Object> userInfo = this.wxService.userByOpenId(openid);
//                    if (null != userInfo) {
//                    response.put("openid", openid);
//                    response.put("session_key", wxInfo.getString("session_key"));
//                    response.put("reg", "1");
//                    response.put("userId", user);
//                      response.put("headIcon", "1.png");
//                     response.put("nick", (String) userInfo.get("USER_NAME"));
//                     response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_OK);
//                    } else {
//                        response.put("openid", openid);
//                        response.put("session_key", wxInfo.getString("session_key"));
//                        response.put("reg", "0");
//                        response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_OK);
//                    }
//                }
//            }


        } catch (Exception e) {
            LogHelper.error(e);
            response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_ERROR);
            response.put("msg", e.getMessage());
        }
        return response;
    }

    @GetMapping(value = "Wx/User/Project/{openId}")
    @ResponseBody
    public JSONObject projectList(@PathVariable(name = "openId") String openId) {
        JSONObject response = new JSONObject();
        try {
            Map<String, Object> user = wxService.userByOpenId(openId);
            if (null != user) {
                ServicePersonInfo personInfo = this.wxService.getServicePersonInfoByUserId((String) user.get("ID"));
                if (null != personInfo) {
                    List<ProjectInfo> projectInfoList = this.wxService.projectListByUserId((String) user.get("ID"));
                    if (null != projectInfoList && projectInfoList.size() > 0) {
                        JSONArray list = new JSONArray();
                        int index = 0;
                        for (ProjectInfo projectInfo : projectInfoList) {
                            index += 1;
                            JSONObject children = new JSONObject();
                            children.put("title", projectInfo.getProjectName() + "(" + projectInfo.getOrgName() + ")");
                            children.put("id", index);
                            children.put("projectId", projectInfo.getId());
                            children.put("field", projectInfo.getOrgId());
                            children.put("spread", true);
                            List<RtuBaseInfo> rtus = rtuService.rtuDataListByProjectId(projectInfo.getId());
                            if (null != rtus) {
                                children.put("rtuNum", rtus.size());
                            } else {
                                children.put("rtuNum", 0);
                            }
                            List<RtuBaseInfo> warningRtus = warningService.warningRtus(projectInfo.getId());
                            if (null != warningRtus) {
                                children.put("warningRtuNum", warningRtus.size());
                            } else {
                                children.put("warningRtuNum", 0);
                            }
                            list.add(children);
                        }
                        response.put("data", list);
                    } else {
                        JSONArray list = new JSONArray();
                        response.put("data", list);
                    }
                } else {
                    String orgId = wxService.getOrgInfoOfUser((String) user.get("ID"));
                    JSONArray list = this.wxService.projectListByOrgId(orgId);
                    if (null != list && list.size() > 0) {
                        for (Object d : list) {
                            JSONObject item = (JSONObject) d;
                            String projectId = item.getString("projectId");
                            List<RtuBaseInfo> rtus = rtuService.rtuDataListByProjectId(projectId);
                            if (null != rtus) {
                                item.put("rtuNum", rtus.size());
                            } else {
                                item.put("rtuNum", 0);
                            }
                            List<RtuBaseInfo> warningRtus = warningService.warningRtus(projectId);
                            if (null != warningRtus) {
                                item.put("warningRtuNum", warningRtus.size());
                            } else {
                                item.put("warningRtuNum", 0);
                            }
                        }
                    }
                    response.put("data", list);
                }
            } else {
                JSONArray list = new JSONArray();
                response.put("data", list);
            }
            response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_OK);
        } catch (Exception e) {
            LogHelper.error(e);
            response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_ERROR);
        }
        return response;
    }


    @GetMapping(value = "Wx/Rtu/Org/List")
    @ResponseBody
    public JSONObject orgList() {
        JSONObject response = new JSONObject();
        try {

            // JSONArray list = this.wxService.orgTree();
            JSONArray list = new JSONArray();
            response.put("data", list);

            response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_OK);
        } catch (Exception e) {
            LogHelper.error(e);
            response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_ERROR);
        }
        return response;
    }


    @GetMapping(value = "Wx/Project/Rtu/Data/{projectId}")
    @ResponseBody
    public JSONObject rtuRealDataList(@PathVariable(name = "projectId") String projectId) {
        JSONObject response = new JSONObject();
        try {
            List<Map<String, Object>> list = new LinkedList<>();
            List<RtuBaseInfo> rtuList = this.rtuService.rtuDataListByProjectId(projectId);
            if (null != rtuList && rtuList.size() > 0) {
                HashOperations<String, String, String> opsHash = redisTemplate.opsForHash();
                int count = 1;
                for (RtuBaseInfo rtu : rtuList) {
                    String rtuCode = rtu.getRtuCode();
                    Map<String, Object> d = new HashMap<>();
                    d.put("indexNumber", String.format("%d", count));
                    // String newkey1 = rtuCode;

//                    LogHelper.info("**************** " + rtuCode);
//                    String rtutail = rtuCode.substring(8, 10) + rtuCode.substring(6, 8);
//                    byte[] rtubuff = BytesHelp.hexStr2Bytes(rtutail);
//                    int rtuvalue = BytesHelp.bytes2short(rtubuff);
//                    if (rtuvalue >= 0 && rtuvalue <= 9999) {
//                        rtutail = String.format("%04d", rtuvalue);
//                        newkey1 = rtuCode.substring(0, 6) + rtutail;
//                    }
//                    String newkey2 = rtuCode;
//                    rtutail = rtuCode.substring(6, 10);
//                    rtubuff = BytesHelp.hexStr2Bytes(rtutail);
//                    rtuvalue = BytesHelp.bytes2short(rtubuff);
//                    if (rtuvalue >= 0 && rtuvalue <= 9999) {
//                        rtutail = String.format("%04d", rtuvalue);
//                        newkey2 = rtuCode.substring(0, 6) + rtutail;
//                    }
                    d.put("rtuCode", rtuCode);
                    d.put("rtuCode1", rtuCode);
                    d.put("rtuCode2", rtuCode);
                    String rtuName = rtu.getRtuName();
                    if (null != rtuName && rtuName.length() > 0) {
                        d.put("rtuName", rtu.getRtuName());
                    } else {
                        d.put("rtuName", "--");
                    }
                    d.put("orgName", rtu.getOrgName());
                    d.put("projectName", rtu.getProjectName());
                    d.put("orgId", rtu.getOrgId());
                    d.put("projectId", rtu.getProjectId());
                    //从缓存中取实时数据
                    //  Map<String, String> values = opsHash.entries(rtuCode);
                    //  String agreement=opsHash.get(rtuCode,"agreement");
                    //  String v = values.get("agreement");
                    // d.put("agreement", agreement);
                    //  d.put("agreementText", "");
                    String lastTime = opsHash.get(rtuCode, "lastTime");
                    //v = values.get("lastTime");
                    // String v=lastTime;
                    if (null != lastTime && lastTime.length() > 0) {
                        SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        Date lt = timeFormat.parse(lastTime);
                        d.put("lastTime", timeFormat.format(lt));
                        long spaceTime = System.currentTimeMillis() - lt.getTime();
                        spaceTime = spaceTime / 1000;
                        String tm = "";
                        long tmpTime = spaceTime / (24 * 60 * 60);
                        if (tmpTime > 0) {
                            tm += tmpTime + "天";
                        }
                        tmpTime = spaceTime % (24 * 60 * 60) / (60 * 60);
                        if (tmpTime > 0) {
                            tm += tmpTime + "小时";
                        }
                        tmpTime = spaceTime % (24 * 60 * 60) % (60 * 60) / 60;
                        if (tmpTime > 0) {
                            tm += tmpTime + "分钟";
                        }
                        tmpTime = spaceTime % (24 * 60 * 60) % (60 * 60) % 60;
                        if (tmpTime > 0) {
                            tm += tmpTime + "秒";
                        }
                        d.put("spaceTime", tm);
                    } else {
                        d.put("lastTime", "");
                        d.put("spaceTime", "");
                    }
                    // v = values.get("datagram");
                    //  d.put("datagram", v);

                    //预警信息
                    // List<Map<String, Object>> warningInfo = wxService.warningList(rtuCode);
                    String warningStatus = rtu.getWarningStatus();
                    if (null != warningStatus && warningStatus.equals("1")) {
                        d.put("warning", 1);
                    } else {
                        d.put("warning", 0);
                    }
                    list.add(d);
                    count++;
                }
            }

            list.sort(new Comparator<Map<String, Object>>() {
                @Override
                public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                    int warning1 = (int) o1.get("warning");
                    int warning2 = (int) o2.get("warning");
                    if (warning1 > warning2) {
                        return -1;
                    } else if (warning1 < warning2) {
                        return 1;
                    }
                    return 0;
                }
            });

            response.put("data", list);
            response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_OK);
        } catch (Exception e) {
            LogHelper.error(e);
            response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_ERROR);
        }
        return response;
    }


    @GetMapping(value = "Wx/Project/Rtu/Data/NavigateInfo/{rtuCode}")
    @ResponseBody
    public JSONObject rtuNavigateInfo(@PathVariable(name = "rtuCode") String rtuCode) {
        JSONObject response = new JSONObject();
        try {
            Map<String, Object> data = new HashMap<>();
            RtuBaseInfo rtuBaseInfo = this.rtuService.rtuInfo(rtuCode);
            if (rtuBaseInfo.getRtuName() != null) {
                data.put("name", rtuBaseInfo.getRtuName());
            } else {
                data.put("name", "");
            }
            if (rtuBaseInfo.getLng() != null) {
                data.put("lng", rtuBaseInfo.getLng());
            } else {
                data.put("lng", "");
            }
            if (rtuBaseInfo.getLat() != null) {
                data.put("lat", rtuBaseInfo.getLat());
            } else {
                data.put("lat", "");
            }
            if (rtuBaseInfo.getAddress() != null) {
                data.put("address", rtuBaseInfo.getAddress());
            } else {
                data.put("address", "");
            }
            response.put("data", data);
            response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_OK);
        } catch (Exception e) {
            LogHelper.error(e);
            response.put(GBConstants.HTTP_REQUEST_KEY_CODE, GBConstants.HTTP_REQUEST_KEY_ERROR);
        }
        return response;
    }

    @RequestMapping(value = "/Wx/Project/Implementation/Upload/Image/{rtuCode}", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject WxUpload(@PathVariable(name = "rtuCode") String rtuCode, @RequestParam("image") MultipartFile image) {
        JSONObject json = new JSONObject();
        if (image != null) {
            try {
                String originalFilename = image.getOriginalFilename();
                long fileSize = image.getSize();
                InputStream input = image.getInputStream();
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len;
                while ((len = input.read(buffer)) > -1) {
                    byteArrayOutputStream.write(buffer, 0, len);
                }
                byteArrayOutputStream.flush();
                ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
                String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
                String[] ofs = originalFilename.split("[.]");
                String toPath = projectImplementPhotoPath;
                File dir = new File(toPath);
                if (!dir.exists()) {
                    dir.mkdir();
                }
                toPath += File.separator + rtuCode;
                dir = new File(toPath);
                if (!dir.exists()) {
                    dir.mkdir();
                }
                String fileName = uuid + "." + ofs[ofs.length - 1];
                File file = new File(toPath + File.separator + fileName);
                FileOutputStream outputStream = new FileOutputStream(file);
                while (true) {
                    byte[] buff = new byte[1024];
                    int r = byteArrayInputStream.read(buff, 0, 1024);
                    if (r > 0) {
                        outputStream.write(buff, 0, r);
                    }
                    if (r <= 0) {
                        break;
                    }
                }
                outputStream.close();
                String ext = ofs[ofs.length - 1];
                String type = "";
                if (ext.equals("jpg") || ext.equals("jpeg")) {
                    type = "image/jpeg";
                } else if (ext.equals("png")) {
                    type = "image/png";
                } else if (ext.equals("bmp")) {
                    type = "image/bmp";
                }
                byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
                FastImageFile fastImageFile = new FastImageFile(byteArrayInputStream, fileSize, ext, null);
                StorePath storePath = fastFileStorageClient.uploadImage(fastImageFile);
                String photoUrlPath = storePath.getFullPath();
                //  String photoUrlPath = "project" + File.separator + "img" + File.separator + imageServerPath + File.separator + rtuCode + File.separator + fileName;
                this.wxService.SavePhoto(uuid, null, originalFilename, image.getSize(), ext, type, photoUrlPath, 2);
                json.put("code", "0");
                json.put("photoUrl", photoUrlPath);
                json.put("fileId", uuid);
            } catch (IOException e) {
                LogHelper.error(e);
                json.put("errMsg", "fail");
                json.put("code", "1");
            }
        } else {
            json.put("errMsg", "canot found image");
            json.put("code", "1");
        }
        return json;
    }

    @PostMapping(value = "/Wx/Porject/Report/{openId}")
    @ResponseBody
    public JSONObject report(@PathVariable(name = "openId") String openId, @RequestBody final JSONObject body) {
        JSONObject json = new JSONObject();
        try {
            this.wxService.report(body, openId);
            if (body.containsKey("isUpdateRtuLocation")) {
                boolean isUpdateRtuLocation = body.getBooleanValue("isUpdateRtuLocation");
                if (isUpdateRtuLocation) {
                    RtuBaseInfo rtuBaseInfo = new RtuBaseInfo();
                    rtuBaseInfo.setRtuCode(body.getString("rtuCode"));
                    rtuBaseInfo.setLng(body.getString("lng"));
                    rtuBaseInfo.setLat(body.getString("lat"));
                    this.wxService.rtuLocationInfoUpdate(rtuBaseInfo);
                }
            }
            json.put("errMsg", "ok");
            json.put("code", "0");
        } catch (Exception e) {
            LogHelper.error(e);
            json.put("code", "1");
        }
        return json;
    }

    @GetMapping(value = "/Wx/Work/List/{openId}")
    @ResponseBody
    public JSONObject workList(@PathVariable(name = "openId") String openId) {
        JSONObject json = new JSONObject();
        try {
            List<Map<String, Object>> list = this.wxService.WorkList(openId);
            if (list != null) {
                SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                for (Map<String, Object> m : list) {
                    Timestamp ut = (Timestamp) m.get("ut");
                    String time = timeFormat.format(new Date(ut.getTime()));
                    m.put("time", time);
                    String orgName = this.wxService.getOrgName((String) m.get("orgId"));
                    m.put("orgName", orgName);
                }
                json.put("data", list);
            } else {
                json.put("data", new LinkedList<>());
            }
            json.put("code", "0");
        } catch (Exception e) {
            LogHelper.error(e);
            json.put("code", "1");
        }
        return json;
    }

    @GetMapping(value = "/Wx/Work/Report/{id}")
    @ResponseBody
    public JSONObject reportDetail(@PathVariable(name = "id") String id) {
        JSONObject json = new JSONObject();
        try {
            Map<String, Object> report = this.wxService.reportDetail(id);
            if (report != null) {
                SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                Timestamp ut = (Timestamp) report.get("ut");
                String time = timeFormat.format(new Date(ut.getTime()));
                report.put("time", time);
                String orgName = this.wxService.getOrgName((String) report.get("orgId"));
                report.put("orgName", orgName);

                json.put("data", report);
                json.put("code", "0");
            } else {
                json.put("code", "1");
            }

        } catch (Exception e) {
            LogHelper.error(e);
            json.put("code", "1");
        }
        return json;
    }
}
