package org.ts.ddcs.WxController.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.ts.ddcs.DataItemTemplate.DataItemTemplateInterface;
import org.ts.ddcs.DataTemplate.DataTemplateInterface;
import org.ts.ddcs.DataTemplate.DataTemplateLine;
import org.ts.ddcs.DataTemplate.DataTemplateManager;
import org.ts.ddcs.DataTemplate.TemplateLineNode;
import org.ts.ddcs.Entity.RtuBaseInfo;
import org.ts.ddcs.Log.LogHelper;
import org.ts.ddcs.Tool.BytesHelp;
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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;

/**
 * @author dylan
 */
@Service("WxService")
public class WxServiceImpl implements WxService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostConstruct
    public void init() {
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new StringRedisSerializer());
    }


    @Override
    public JSONArray rtuList(String openId, String rtuCode, String rtuName,String orgId) {
        try {
            LinkedList<String> rtus = new LinkedList<>();
            HashOperations<String, String, String> opsHash = redisTemplate.opsForHash();
            Set<String> keys = opsHash.keys("rtu_online");
            Date d1 = new Date();
            for (String key : keys) {
                boolean isfind=false;
                if (null != rtuCode && rtuCode.length() > 0) {
//                    String newkey1 = key;
//                    String rtutail = key.substring(8, 10) + key.substring(6, 8);
//                    byte[] rtubuff = BytesHelp.hexStr2Bytes(rtutail);
//                    int rtuvalue = BytesHelp.bytes2short(rtubuff);
//                    if (rtuvalue >= 0 && rtuvalue <= 9999) {
//                        rtutail = String.format("%04d", rtuvalue);
//                        newkey1 = key.substring(0, 6) + rtutail;
//                    }
//                    String newkey2 = key;
//                    rtutail = key.substring(6, 10);
//                    rtubuff = BytesHelp.hexStr2Bytes(rtutail);
//                    rtuvalue = BytesHelp.bytes2short(rtubuff);
//                    if (rtuvalue >= 0 && rtuvalue <= 9999) {
//                        rtutail = String.format("%04d", rtuvalue);
//                        newkey2 = key.substring(0, 6) + rtutail;
//                    }
                    if (key.contains(rtuCode)  ) {
                        rtus.addLast(key);
                        isfind=true;
//                        if(opsHash.hasKey(key,"orgId")){
//                           String org = opsHash.get(key,"orgId");
//                            if (org.equals(orgId)){
//                                rtus.addLast(key);
//                            }
//                        }
                    }
                }
                if(!isfind){
                    if (null != rtuName && rtuName.length() > 0) {
                      String  name=  opsHash.get(key,"rtuName");
                         if(null !=name&&name.contains(rtuName)){
                             rtus.addLast(key);
                           //  isfind=true;
                         }
;                    }

                }
            }
            Collections.sort(rtus);
            JSONArray historyList = new JSONArray();
            List<Map<String, Object>> list = new LinkedList<>();
            if (rtus.size() > 0) {
                for (String code : rtus) {

                    JSONObject data = this.RtuBaseInfo(code);
                    data.put("openId", openId);
                    data.put("rtuCode", code);
                    historyList.add(data);
                }
            } else {
                String sql = "SELECT h.ID as id,h.RTU_CODE as rtuCode,h.OPEN_ID as openId  FROM wx_query_rtu_history h LEFT JOIN t_au_user_wx w  on w.OPEN_ID = h.OPEN_ID LEFT JOIN t_au_org_user o on o.USER_ID = w.USER_ID WHERE o.ORG_ID='" + orgId + "' LIMIT 10";
                List<Map<String, Object>> histist = jdbcTemplate.queryForList(sql);

                if (null != histist) {
                    for (Map<String, Object> r : histist) {
                        String id = (String) r.get("id");
                        String code = (String) r.get("rtuCode");
                        JSONObject data = this.RtuBaseInfo(code);
                        data.put("id", id);
                        data.put("openId", openId);
                        data.put("rtuCode", code);
                        historyList.add(data);
                    }
                }
            }
            return historyList;
        } catch (Exception e) {
            LogHelper.error(e);
        }
        return null;
    }


    @Override
    public JSONObject FindRtu(String rtuCode) {
        try {
            HashOperations<String, String, String> opsHash = redisTemplate.opsForHash();
            if (redisTemplate.hasKey(rtuCode)) {
                JSONObject data = new JSONObject();

                data.put("rtuName", opsHash.get(rtuCode, "rtuName"));

                JSONObject baseInfo = new JSONObject();
                JSONObject statusInfo = new JSONObject();
                JSONObject datagramInfo = new JSONObject();


                baseInfo.put("rtuCode", rtuCode);
                baseInfo.put("rtuName", opsHash.get(rtuCode, "rtuName"));
                baseInfo.put("orgName", opsHash.get(rtuCode, "orgName"));
                baseInfo.put("agreement", opsHash.get(rtuCode, "agreement"));


                String lasttime = opsHash.get(rtuCode, "lastTime");
                if (null != lasttime) {
                    datagramInfo.put("lastTime", lasttime);
                    SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    try {
                        Date lt = timeFormat.parse(lasttime);
                        long spaceTime = new Date().getTime() - 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 + "秒";
                        }
                        datagramInfo.put("spaceTime", tm);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }

                if (opsHash.hasKey(rtuCode, "relay")) {
                    String relay = opsHash.get(rtuCode, "relay");
                    if (null != relay && relay.equals("1")) {
                        baseInfo.put("relay", "已配置转发");
                        baseInfo.put("relayIp", opsHash.get(rtuCode, "relayIp"));
                    }
                }

                String masterIp = opsHash.get(rtuCode, "server_master");
                if (null != masterIp) {
                    masterIp = masterIp.replaceAll("_", ".");
                    statusInfo.put("masterIp", masterIp);
                }

                String dataGram = opsHash.get(rtuCode, "datagram");
                if (null != dataGram) {
                    SimpleDateFormat timeFormat2 = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
                    SimpleDateFormat timeFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                    List<String> viewInfoList = new LinkedList<>();
                    byte[] data_gram_buff = BytesHelp.hexStr2Bytes(dataGram);
                    if (dataGram.substring(0, 2).equals("68")) {
                        DataTemplateLine line = DataTemplateManager.newInstance().createTemplateLine(GBConstants.AGREEMENT_KIND_SZY);
                        line.Stream(data_gram_buff);
                        TemplateLineNode macth = line.MacthTemplate();
                        if (null != macth) {
                            DataTemplateInterface dataTemplateInterface = macth.getDataTemplate();
                            StringBuffer dataStr = new StringBuffer(BytesHelp.byte2HexStr(dataTemplateInterface.CollectTime()));
                            String tm = dataStr.toString();
                            if (tm != null && tm.length() > 0) {
                                tm = "20" + tm;
                                Date tm1 = timeFormat.parse(tm);
                                viewInfoList.add("观测时间 " + timeFormat2.format(tm1));
                            }

                            LinkedList<DataItemTemplateInterface> dataItem = dataTemplateInterface.MacthDataItem("wq_river");
                            if (dataItem.size() > 0) {
                                for (DataItemTemplateInterface item : dataItem) {
                                    viewInfoList.add(item.GetDesc() + " " + item.toString());
                                }
                            }

                            dataItem = dataTemplateInterface.MacthDataItem("t_szy_flow_rate");
                            if (dataItem.size() > 0) {
                                for (DataItemTemplateInterface item : dataItem) {
                                    viewInfoList.add(item.GetDesc() + " " + item.toString());
                                }
                            }

                            dataItem = dataTemplateInterface.MacthDataItem("t_szy_warining_info");
                            if (dataItem.size() > 0) {
                                for (DataItemTemplateInterface item : dataItem) {
                                    viewInfoList.add(item.GetDesc() + " " + item.toString());
                                }
                            }
                            dataItem = dataTemplateInterface.MacthDataItem("t_szy_status_info");
                            if (dataItem.size() > 0) {
                                for (DataItemTemplateInterface item : dataItem) {
                                    viewInfoList.add(item.GetDesc() + " " + item.toString());
                                }
                            }

                        }

                    } else {

                        DataTemplateLine line = DataTemplateManager.newInstance().createTemplateLine(GBConstants.AGREEMENT_KIND_SW);
                        line.Stream(data_gram_buff);
                        TemplateLineNode macth = line.MacthTemplate();
                        if (null != macth) {
                            DataTemplateInterface dataTemplateInterface = macth.getDataTemplate();

                            StringBuffer dataStr = new StringBuffer(BytesHelp.byte2HexStr(dataTemplateInterface.CollectTime()));
                            String tm = dataStr.toString();
                            if (tm != null && tm.length() > 0) {
                                tm = "20" + tm + "00";
                                Date tm1 = timeFormat.parse(tm);
                                viewInfoList.add("观测时间 " + timeFormat2.format(tm1));
                            }
                            dataStr = new StringBuffer(BytesHelp.byte2HexStr(dataTemplateInterface.SendPacketTime()));
                            String dt = dataStr.toString();
                            if (dt != null && dt.length() > 0) {
                                dt = "20" + dt;
                                Date dt1 = timeFormat.parse(dt);
                                viewInfoList.add("发报时间 " + timeFormat2.format(dt1));
                            }
                            LinkedList<DataItemTemplateInterface> dataItem = dataTemplateInterface.MacthDataItem("ST_PPTN_R");
                            if (dataItem.size() > 0) {
                                for (DataItemTemplateInterface item : dataItem) {
                                    viewInfoList.add(item.GetDesc() + " " + item.GetDecimal());
                                }
                            }
                            dataItem = dataTemplateInterface.MacthDataItem("st_pptn_r_5_min");
                            if (dataItem.size() > 0) {
                                for (DataItemTemplateInterface item : dataItem) {
                                    viewInfoList.add(item.GetDesc() + " " + item.GetDecimal());
                                }
                            }
                            dataItem = dataTemplateInterface.MacthDataItem("st_river_r");
                            if (dataItem.size() > 0) {
                                for (DataItemTemplateInterface item : dataItem) {
                                    viewInfoList.add(item.GetDesc() + " " + item.GetDecimal());
                                }
                            }
                            dataItem = dataTemplateInterface.MacthDataItem("st_rsvr_r");
                            if (dataItem.size() > 0) {
                                for (DataItemTemplateInterface item : dataItem) {
                                    viewInfoList.add(item.GetDesc() + " " + item.GetDecimal());
                                }
                            }
                            dataItem = dataTemplateInterface.MacthDataItem("t_base_rtu_info");
                            if (dataItem.size() > 0) {
                                for (DataItemTemplateInterface item : dataItem) {
                                    viewInfoList.add(item.GetDesc() + " " + item.toString());
                                }
                            }
                            dataItem = dataTemplateInterface.MacthDataItem("st_ground");
                            if (dataItem.size() > 0) {
                                for (DataItemTemplateInterface item : dataItem) {
                                    viewInfoList.add(item.GetDesc() + " " + item.toString());
                                }
                            }
                            dataItem = dataTemplateInterface.MacthDataItem("wr_water_qa");
                            if (dataItem.size() > 0) {
                                for (DataItemTemplateInterface item : dataItem) {
                                    viewInfoList.add(item.GetDesc() + " " + item.toString());
                                }
                            }
                            dataItem = dataTemplateInterface.MacthDataItem("st_sw_water");
                            if (dataItem.size() > 0) {
                                for (DataItemTemplateInterface item : dataItem) {
                                    viewInfoList.add(item.GetDesc() + " " + item.toString());
                                }
                            }

                        }
                    }

                    datagramInfo.put("infos", viewInfoList);
                }


                if (opsHash.hasKey(rtuCode, GBConstants.REDIS_KEY_RTU_STATUS_DATAGRAM)) {

                    String statusDatagram = opsHash.get(rtuCode, GBConstants.REDIS_KEY_RTU_STATUS_DATAGRAM);
                    if (null != statusDatagram) {
                        byte[] data_gram_buff = BytesHelp.hexStr2Bytes(statusDatagram);
                        DataTemplateLine line = DataTemplateManager.newInstance().createTemplateLine(null);
                        line.Stream(data_gram_buff);
                        TemplateLineNode macth = line.MacthTemplate();
                        if (null != macth) {
                            DataTemplateInterface dataTemplateInterface = macth.getDataTemplate();
                            LinkedList<DataItemTemplateInterface> dataItem = dataTemplateInterface.MacthDataItem("t_base_rtu_info");
                            if (dataItem.size() > 0) {
                                List<String> viewInfoList = new LinkedList<>();
                                for (DataItemTemplateInterface item : dataItem) {
                                    viewInfoList.add(item.GetDesc() + " " + item.toString());
                                }
                                statusInfo.put("status", viewInfoList);
                            }
                        }
                    }

                }

                data.put("baseInfo", baseInfo);
                data.put("statusInfo", statusInfo);
                data.put("datagramInfo", datagramInfo);
                return data;
            }
        } catch (Exception e) {
            LogHelper.error(e);
        }
        return null;
    }

    @Override
    public JSONObject RtuBaseInfo(String rtuCode) {
        try {
            JSONObject baseInfo = new JSONObject();

            HashOperations<String, String, String> opsHash = redisTemplate.opsForHash();
            if (redisTemplate.hasKey(rtuCode)) {

                baseInfo.put("rtuCode", rtuCode);
                if (opsHash.hasKey(rtuCode, "rtuName")) {
                    baseInfo.put("rtuName", opsHash.get(rtuCode, "rtuName"));
                } else {
                    baseInfo.put("rtuName", "");
                }
                if (opsHash.hasKey(rtuCode, "orgName")) {
                    baseInfo.put("orgName", opsHash.get(rtuCode, "orgName"));
                } else {
                    baseInfo.put("orgName", "");
                }
                if (opsHash.hasKey(rtuCode, "projectName")) {
                    baseInfo.put("projectName", opsHash.get(rtuCode, "projectName"));
                } else {
                    baseInfo.put("projectName", "");
                }
                if (opsHash.hasKey(rtuCode, "agreement")) {
                    baseInfo.put("agreement", opsHash.get(rtuCode, "agreement"));
                } else {
                    baseInfo.put("agreement", "");
                }


            }
            return baseInfo;
        } catch (Exception e) {
            LogHelper.error(e);
        }
        return null;
    }

    @Override
    public JSONObject RtuStatusInfo(String rtuCode) {
        try {
            HashOperations<String, String, String> opsHash = redisTemplate.opsForHash();
            if (redisTemplate.hasKey(rtuCode)) {
                JSONObject statusInfo = new JSONObject();
                SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                SimpleDateFormat timeFormat3 = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
                String sql = "SELECT w.ID as id  FROM t_b_rtu_warning w   WHERE w.RTU_CODE ='" + rtuCode + "' AND  w.WARNING_STATUS ='0' ORDER BY w.HAPPEN_TIME DESC  ";
                List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
                if (list != null && list.size() > 0) {
                    statusInfo.put("warning", "设备预警（" + list.size() + ")");
                } else {
                    statusInfo.put("warning", "运行正常");
                }
                String lasttime = opsHash.get(rtuCode, "lastTime");
                if (null != lasttime) {
                    try {
                        Date lt = timeFormat.parse(lasttime);
                        statusInfo.put("lastTime", timeFormat3.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 + "秒";
                        }
                        statusInfo.put("spaceTime", tm);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }


                if (opsHash.hasKey(rtuCode, GBConstants.REDIS_KEY_RTU_STATUS_DATAGRAM)) {

                    String statusDatagram = opsHash.get(rtuCode, GBConstants.REDIS_KEY_RTU_STATUS_DATAGRAM);
                    if (null != statusDatagram) {
                        byte[] data_gram_buff = BytesHelp.hexStr2Bytes(statusDatagram);
                        DataTemplateLine line = DataTemplateManager.newInstance().createTemplateLine(null);
                        line.Stream(data_gram_buff);
                        TemplateLineNode macth = line.MacthTemplate();
                        if (null != macth) {
                            DataTemplateInterface dataTemplateInterface = macth.getDataTemplate();
                            LinkedList<DataItemTemplateInterface> dataItem = dataTemplateInterface.MacthDataItem("t_base_rtu_info");
                            if (dataItem.size() > 0) {
                                List<JSONObject> viewInfoList = new LinkedList<>();
                                for (DataItemTemplateInterface item : dataItem) {
                                    JSONObject info = new JSONObject();
                                    info.put("name", item.GetDesc());
                                    info.put("text", item.toString());
                                    viewInfoList.add(info);
                                }
                                statusInfo.put("status", viewInfoList);
                            }
                        }
                    }
                }
                return statusInfo;
            }
        } catch (Exception e) {
            LogHelper.error(e);
        }
        return null;
    }

    @Override
    public JSONObject RtuLastDatagram(String rtuCode) {
        try {
            HashOperations<String, String, String> opsHash = redisTemplate.opsForHash();
            ListOperations<String, String> opsList = redisTemplate.opsForList();
            SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat timeFormat2 = new SimpleDateFormat("yyyyMMddHHmmss");
            SimpleDateFormat timeFormat3 = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
            String projectId = opsHash.get(rtuCode, GBConstants.REDIS_KEY_RTU_INFO_PROJECT_ID);
            String agreementCode = opsHash.get(GBConstants.REDIS_KEY_PROJECT_PREFIX + projectId, GBConstants.REDIS_KEY_PROJECT_INFO_AGREEMENT_CODE);
            int codeLen = 10;
            if (GBConstants.DICT_CODE_AGREEMENT_SW_NM_EXT.equals(agreementCode)) {
                codeLen = 16;
            }
            List<Map<String, Object>> szyDatagramKind = this.listDict(GBConstants.DICT_SZY_DATAGRAM_KIND);
            List<Map<String, Object>> datagramKind = this.listDict(GBConstants.DICT_SW_DATAGRAM_KIND);

            String key = rtuCode + ":List";
            JSONObject datagramInfo = new JSONObject();
            if (redisTemplate.hasKey(key)) {
                if (opsList.size(key) > 0) {
                    JSONArray datas = new JSONArray();
                    List<String> collectTimes = opsList.range(key, 0, opsList.size(key));
                    for (int i = collectTimes.size(); i > 0; i--) {
                        String tm = collectTimes.get(i - 1);
                        String key_datagram = rtuCode + ":datagram";
                        if (redisTemplate.hasKey(key_datagram)) {
                            Date dt = timeFormat.parse(tm);
                            String key_tm = timeFormat2.format(dt);
                            if (opsHash.hasKey(key_datagram, key_tm)) {
                                String datagram = opsHash.get(key_datagram, key_tm);


                                if (datagram.startsWith("68")) {
                                    String func = datagram.substring(9 * 2, 10 * 2);
                                    if (!func.equals("C0")) {
                                        String kind = "";
                                        for (Map<String, Object> dict : szyDatagramKind) {
                                            String code = (String) dict.get("CODE");
                                            if (code.equals(func)) {
                                                kind = (String) dict.get("NAME");
                                                break;
                                            }
                                        }
                                        JSONObject d = new JSONObject();
                                        d.put("datagram", datagram);
                                        d.put("tm", timeFormat3.format(dt));
                                        d.put("datagramKind", kind);
                                        datas.add(d);
                                    }


//                                    byte[] data_gram_buff = BytesHelp.hexStr2Bytes(datagram);
//                                    DataTemplateLine line = DataTemplateManager.newInstance().createTemplateLine(GBConstants.AGREEMENT_KIND_SZY);
//                                    line.Stream(data_gram_buff);
//                                    TemplateLineNode macth = line.MacthTemplate();
//                                    if (null != macth) {
//                                        BaseDataTemplate dataTemplateInterface = macth.getDataTemplate();
//                                        d.put("datagramKind", dataTemplateInterface.GetViewName());
//                                    }
                                } else {
                                    //取功能码
                                    int count = 3 * 2 + codeLen + 2 * 2;
                                    String func = datagram.substring(count, count + 2);

                                    if (!func.equals("30") && !func.equals("31") && !func.equals("32") && !func.equals("33") && !func.equals("34") && !func.equals("EF")) {
                                        String kind = "";
                                        for (Map<String, Object> dict : datagramKind) {
                                            String code = (String) dict.get("CODE");
                                            if (code.equals(func)) {
                                                kind = (String) dict.get("NAME");
                                                break;
                                            }
                                        }


                                        JSONObject d = new JSONObject();
                                        d.put("datagram", datagram);
                                        d.put("tm", timeFormat3.format(dt));
                                        d.put("datagramKind", kind);
                                        datas.add(d);
                                    }


//                                    byte[] data_gram_buff = BytesHelp.hexStr2Bytes(datagram);
//                                    DataTemplateLine line = DataTemplateManager.newInstance().createTemplateLine(GBConstants.AGREEMENT_KIND_SW);
//                                    line.Stream(data_gram_buff);
//                                    TemplateLineNode macth = line.MacthTemplate();
//                                    if (null != macth) {
//                                        BaseDataTemplate dataTemplateInterface = macth.getDataTemplate();
//                                        d.put("datagramKind", dataTemplateInterface.GetViewName());
//                                    }
                                }


                                //  datas.add(d);
                            }
                        }
                    }
                    datagramInfo.put("datas", datas);
                }


                return datagramInfo;
            }
        } catch (Exception e) {
            LogHelper.error(e);
        }
        return null;
    }

    @Override
    public List<Map<String, Object>> HistoryList(String orgId) {
        try {
            String sql = "SELECT h.ID as id,h.RTU_CODE as rtuCode,h.OPEN_ID as openId  FROM wx_query_rtu_history h LEFT JOIN t_au_user_wx w  on w.OPEN_ID = h.OPEN_ID LEFT JOIN t_au_org_user o on o.USER_ID = w.USER_ID WHERE 1=1 ";
            if (!orgId.equals("402881ec44a043190144a043d7aa0000")) {
                sql += "  AND  o.ORG_ID='" + orgId;
            }
            sql += " LIMIT 10";
            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
            return list;
        } catch (Exception e) {
            LogHelper.error(e);
        }
        return null;
    }

    @Override
    public void RecordFindHistory(String rtuCode, String openId) {
        try {

            String sql = "SELECT ID FROM wx_query_rtu_history   WHERE RTU_CODE='" + rtuCode + "' AND OPEN_ID='" + openId + "'";
            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
            if (null != list && list.size() > 0) {
                sql = "UPDATE wx_query_rtu_history SET UPDATE_TIME = ? WHERE RTU_CODE = ? AND OPEN_ID = ?";
                jdbcTemplate.update(sql, new PreparedStatementSetter() {
                    @Override
                    public void setValues(PreparedStatement preparedStatement) throws SQLException {
                        int index = 0;
                        preparedStatement.setTimestamp(++index, new Timestamp(System.currentTimeMillis()));
                        preparedStatement.setString(++index, rtuCode);
                        preparedStatement.setString(++index, openId);
                    }
                });
            } else {

                String id = UUID.randomUUID().toString().replace("-", "").toLowerCase();
                sql = "INSERT INTO wx_query_rtu_history(ID, RTU_CODE, OPEN_ID) VALUES('" + id + "', '" + rtuCode + "', '" + openId + "')";
                jdbcTemplate.update(sql);
            }

        } catch (Exception e) {
            LogHelper.error(e);
        }
    }

    @Override
    public JSONArray orgTree() {
        try {
//            DriverManagerDataSource dataSource = new DriverManagerDataSource();
//            dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
//            dataSource.setUrl("jdbc:mysql://172.1.0.63:3306/devicebox?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=false");
//            dataSource.setUsername("root");
//            dataSource.setPassword("Dh82828800");
//            JdbcTemplate jdbc = new JdbcTemplate(dataSource);

            String project_sql = "SELECT p.id ,p.project_name as projectName,p.org_id as orgId,o.ORG_NAME as orgName FROM t_base_project p  LEFT JOIN  t_au_org o ON o.ID = p.org_id WHERE p.del_flag ='0' ";

            JSONArray childrenList = new JSONArray();
            // String sql = "SELECT * FROM t_au_org WHERE PARENT_ID ='402881ec44a043190144a043d7aa0000'";
            int index = 1;
            List<Map<String, Object>> ls = jdbcTemplate.queryForList(project_sql);
//            JSONObject tree = new JSONObject();
//            tree.put("title", "大恒");
//            tree.put("id", index);
//            tree.put("field", "402881ec44a043190144a043d7aa0000");
//            tree.put("spread", true);
//            childrenList.add(tree);
            for (Map<String, Object> org : ls) {
                index += 1;
                JSONObject children = new JSONObject();
                children.put("title", (String) org.get("projectName") + "(" + org.get("orgName") + ")");
                children.put("id", index);
                children.put("field", (String) org.get("id"));
                children.put("spread", true);
                childrenList.add(children);
            }
            return childrenList;
        } catch (Exception e) {
            LogHelper.error(e);
        }
        return null;
    }

    @Override
    public JSONArray projectListByOrgId(String orgId) {
        try {
            String project_sql = "SELECT p.id ,p.project_name as projectName,p.org_id as orgId,o.ORG_NAME as orgName FROM t_base_project p  LEFT JOIN  t_au_org o ON o.ID = p.org_id WHERE p.del_flag ='0'  ";
            if (!orgId.equals("402881ec44a043190144a043d7aa0000")) {
                project_sql += " AND p.org_id ='" + orgId + "'";
            }

            JSONArray childrenList = new JSONArray();
            int index = 0;
            List<Map<String, Object>> ls = jdbcTemplate.queryForList(project_sql);
            for (Map<String, Object> org : ls) {
                index += 1;
                JSONObject children = new JSONObject();
                children.put("title", (String) org.get("projectName") + "(" + org.get("orgName") + ")");
                children.put("id", index);
                children.put("projectId", (String) org.get("id"));
                children.put("field", (String) org.get("id"));
                children.put("spread", true);
                childrenList.add(children);
            }
            return childrenList;
        } catch (Exception e) {
            LogHelper.error(e);
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class}, propagation = Propagation.REQUIRED)
    public void report(JSONObject data, String openId) {
        LogHelper.info(data.toJSONString());
        String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
        JSONArray photos = data.getJSONArray("photos");
        if (null != photos && photos.size() > 0) {
            String sql = "UPDATE t_file SET `GROUP_ID` = ?, `STATUS` = ? WHERE `ID` = ?";
            jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement preparedStatement, int i) throws SQLException {
                    JSONObject p = photos.getJSONObject(i);
                    String id = p.getString("id");
                    int index = 0;
                    preparedStatement.setString(++index, uuid);
                    preparedStatement.setBigDecimal(++index, new BigDecimal(1));
                    preparedStatement.setString(++index, id);
                }

                @Override
                public int getBatchSize() {
                    return photos.size();
                }
            });
        }

        String sql = "insert into st_project_report (ID,PROJECT_DESC,OPEN_ID,RTU_CODE,ADDRESS,LNG,LAT,WEATHER,RTU_NAME) values(?,?,?,?,?,?,?,?,?)";
        jdbcTemplate.update(sql, new PreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement preparedStatement) throws SQLException {
                int index = 0;
                preparedStatement.setString(++index, uuid);
                preparedStatement.setString(++index, data.getString("desc"));
                preparedStatement.setString(++index, openId);
                preparedStatement.setString(++index, data.getString("rtuCode"));
//                preparedStatement.setString(++index, data.getString("orgId"));
                preparedStatement.setString(++index, data.getString("address"));
                preparedStatement.setString(++index, data.getString("lng"));
                preparedStatement.setString(++index, data.getString("lat"));
                preparedStatement.setString(++index, data.getString("weather"));
                preparedStatement.setString(++index, data.getString("rtuName"));
            }
        });
    }

    @Override
    public List<Map<String, Object>> WorkList(String openId) {

        String sql = "SELECT r.ID as id,r.PROJECT_DESC as info,r.UPDATE_TIME as ut,r.ORG_ID as orgId FROM st_project_report r WHERE r.OPEN_ID='" + openId + "'  ORDER BY r.UPDATE_TIME DESC";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);

        return list;
    }

    @Override
    public String getOrgName(String orgId) {
        try {
            DriverManagerDataSource dataSource = new DriverManagerDataSource();
            dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
            dataSource.setUrl("jdbc:mysql://172.1.0.63:3306/devicebox?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=false");
            dataSource.setUsername("root");
            dataSource.setPassword("Dh82828800");
            JdbcTemplate jdbc = new JdbcTemplate(dataSource);

            JSONArray childrenList = new JSONArray();
            String sql = "SELECT o.ORG_NAME as orgName FROM t_au_org o WHERE o.ID ='" + orgId + "'";

            List<Map<String, Object>> ls = jdbc.queryForList(sql);
            if (null != ls && ls.size() > 0) {
                Map<String, Object> org = ls.get(0);
                return (String) org.get("orgName");
            }


        } catch (Exception e) {
            LogHelper.error(e);
        }
        return null;
    }

    @Override
    public String getOrgInfoOfUser(String userId) {
        String sql = "SELECT o.ORG_ID FROM  t_au_org_user o WHERE o.USER_ID ='" + userId + "' AND o.SPECIALITY_STATE=1";
        List<Map<String, Object>> ls = jdbcTemplate.queryForList(sql);
        if (null != ls && ls.size() > 0) {
            Map<String, Object> org = ls.get(0);
            return (String) org.get("ORG_ID");
        }
        return null;
    }

    @Override
    public Map<String, Object> reportDetail(String id) {
        String sql = "SELECT r.ID as id,r.PROJECT_DESC as info,r.UPDATE_TIME as ut,r.ORG_ID as orgId FROM st_project_report r WHERE r.ID='" + id + "' ";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        if (null != list && list.size() > 0) {
            Map<String, Object> m = list.get(0);

            sql = "SELECT   p.PHOTO as photo FROM st_project_report_photo p  WHERE p.REPORT_ID='" + (String) m.get("id") + "'  ";

            List<Map<String, Object>> photos = jdbcTemplate.queryForList(sql);
            m.put("photos", photos);
            return m;
        }

        return null;
    }

    @Override
    public Map<String, Object> userByOpenId(String openId) {
        String sql = "SELECT w.OPEN_ID,w.USER_ID FROM t_au_user_wx w WHERE w.OPEN_ID='" + openId + "'";
        List<Map<String, Object>> wxs = jdbcTemplate.queryForList(sql);
        if (null != wxs && wxs.size() > 0) {
            sql = "SELECT * FROM t_au_user u WHERE u.ID = '" + (String) wxs.get(0).get("USER_ID") + "' ";
            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
            if (null != list && list.size() > 0) {
                return list.get(0);
            }
        }
        return null;
    }

    @Override
    public Map<String, Object> user(String user) {
        String sql = "SELECT * FROM t_au_user u WHERE u.LOGIN_ID = '" + user + "'  AND IS_VALID=1";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        if (null != list && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class}, propagation = Propagation.REQUIRED)
    public void updateWx(String openid, String user) {
        String sql = "SELECT u.ID FROM t_au_user u WHERE u.LOGIN_ID ='" + user + "'";
        List<Map<String, Object>> usrs = jdbcTemplate.queryForList(sql);
        if (null != usrs && usrs.size() > 0) {
            sql = "SELECT w.OPEN_ID,w.USER_ID FROM t_au_user_wx w WHERE w.OPEN_ID='" + openid + "'";
            List<Map<String, Object>> wxs = jdbcTemplate.queryForList(sql);
            if (null != wxs && wxs.size() > 0) {
                sql = "UPDATE t_au_user_wx SET `USER_ID` = '" + (String) usrs.get(0).get("ID") + "' WHERE `OPEN_ID` = '" + openid + "'";
            } else {
                sql = " INSERT INTO t_au_user_wx(`OPEN_ID`, `USER_ID`) VALUES ('" + openid + "', '" + (String) usrs.get(0).get("ID") + "')";
            }
            jdbcTemplate.update(sql);
        }
    }

    @Override
    @Transactional(rollbackFor = {Exception.class}, propagation = Propagation.REQUIRED)
    public List<Map<String, Object>> warningList(String rtuCode) {
        String sql = "SELECT w.ID ,w.RTU_CODE ,w.WARNING_INFO ,w.HAPPEN_TIME ,w.RECOVERY_TIME ,w.WARNING_STATUS ,w.WARNING_CONTENT,w.WARNING_CHECK_TIME,w.RECOVERY_TIME,w.WARNING_TYPE   FROM t_b_rtu_warning w   WHERE 1=1 AND w.RTU_CODE='" + rtuCode + "' AND w.WARNING_STATUS='0'";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        return list;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class}, propagation = Propagation.REQUIRED)
    public void SavePhoto(String id, String groupId, String fileName, long fileSize, String ext, String type, String savePath, int status) {
        String sql = "INSERT INTO t_file (`ID`, `GROUP_ID`, `FILE_NAME`, `EXT_NAME`, `CONTENT_TYPE`, `FILE_SIZE`, `SAVED_PATH`, `STATUS`) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";

        jdbcTemplate.update(sql, new PreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement preparedStatement) throws SQLException {
                int index = 0;
                preparedStatement.setString(++index, id);
                preparedStatement.setString(++index, groupId);
                preparedStatement.setString(++index, fileName);
                preparedStatement.setString(++index, ext);
                preparedStatement.setString(++index, type);
                preparedStatement.setBigDecimal(++index, new BigDecimal(fileSize));
                preparedStatement.setString(++index, savePath);
                preparedStatement.setBigDecimal(++index, new BigDecimal(status));
            }
        });
    }

    @Override
    @Transactional(rollbackFor = {Exception.class}, propagation = Propagation.REQUIRED)
    public void rtuLocationInfoUpdate(RtuBaseInfo rtuBaseInfo) {
        String sql = "UPDATE  t_base_rtu_info  SET LOCATION_LON=?,LOCATION_LAT=?   WHERE RTU_CD =?";
        jdbcTemplate.update(sql, new PreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement preparedStatement) throws SQLException {
                int index = 0;
                preparedStatement.setString(++index, rtuBaseInfo.getLng());
                preparedStatement.setString(++index, rtuBaseInfo.getLat());
                preparedStatement.setString(++index, rtuBaseInfo.getRtuCode());
            }
        });
    }

    @Override
    public List<Map<String, Object>> listDict(String id) {
        String sql = "SELECT * FROM t_dict WHERE PARENT_ID='" + id + "'";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        return list;
    }

    @Override
    public List<ProjectInfo> projectListByUserId(String id) {
        String sql = "select l.project_id,p.project_name,o.ID ORG_ID,o.ORG_NAME from basic_service_person_project_link l ";
        sql += " left join basic_project_service_person sp on sp.id = l.person_id ";
        sql += " left join t_base_project p on p.id= l.project_id";
        sql += " left join t_au_org o on o.ID = p.org_id ";
        sql += " where sp.sys_user_id='" + id + "' ";
        sql += " order by o.ID , l.project_id";

        List<ProjectInfo> projectInfos = jdbcTemplate.query(sql, new RowMapper<ProjectInfo>() {
            @Override
            public ProjectInfo mapRow(ResultSet resultSet, int i) throws SQLException {
                ProjectInfo projectInfo = new ProjectInfo();
                projectInfo.setId(resultSet.getString("project_id"));
                projectInfo.setProjectName(resultSet.getString("project_name"));
                projectInfo.setOrgId(resultSet.getString("ORG_ID"));
                projectInfo.setOrgName(resultSet.getString("ORG_NAME"));
                return projectInfo;
            }
        });

        return projectInfos;

    }


    @Override
    public ServicePersonInfo getServicePersonInfoByUserId(String id) {
        String sql = "SELECT p.id,p.sys_user_id,p.person_name,p.tel,p.phone,p.mail,p.remark,o.ORG_NAME,o.ID ORG_ID,u.LOGIN_ID FROM basic_project_service_person p ";
        sql += " LEFT JOIN t_au_user u  ON u.ID = p.sys_user_id ";
        sql += " LEFT JOIN t_au_org_user ou  ON ou.USER_ID = p.sys_user_id ";
        sql += " LEFT JOIN t_au_org o  ON o.ID = ou.ORG_ID ";
        sql += " WHERE p.is_del = 0  AND p.sys_user_id=?";
        List<ServicePersonInfo> list = jdbcTemplate.query(sql, new PreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement preparedStatement) throws SQLException {
                preparedStatement.setString(1, id);
            }
        }, new RowMapper<ServicePersonInfo>() {
            @Override
            public ServicePersonInfo mapRow(ResultSet resultSet, int i) throws SQLException {
                ServicePersonInfo personInfo = new ServicePersonInfo();
                personInfo.setId(resultSet.getString("id"));
                personInfo.setSysUserId(resultSet.getString("sys_user_id"));
                personInfo.setPersonName(resultSet.getString("person_name"));
                personInfo.setTel(resultSet.getString("tel"));
                personInfo.setPhone(resultSet.getString("phone"));
                personInfo.setMail(resultSet.getString("mail"));
                personInfo.setRemark(resultSet.getString("remark"));
                personInfo.setOrgId(resultSet.getString("ORG_ID"));
                personInfo.setOrgName(resultSet.getString("ORG_NAME"));
                personInfo.setLoginId(resultSet.getString("LOGIN_ID"));
                return personInfo;
            }
        });
        if (null != list && list.size() > 0) {
//            ServicePersonInfo personInfo = list.get(0);
//            sql = "select l.project_id,p.project_name from basic_service_person_project_link l ";
//            sql += " left join t_base_project p on p.id=l.project_id ";
//            sql += " where l.person_id='" + personInfo.getId() + "' ";
//
//            List<ProjectInfo> projectInfos = jdbcTemplate.query(sql, new RowMapper<ProjectInfo>() {
//                @Override
//                public ProjectInfo mapRow(ResultSet resultSet, int i) throws SQLException {
//                    ProjectInfo projectInfo = new ProjectInfo();
//                    projectInfo.setId(resultSet.getString("project_id"));
//                    projectInfo.setProjectName(resultSet.getString("project_name"));
//                    return projectInfo;
//                }
//            });
//
//            if (null != projectInfos) {
//                personInfo.setProjectList(projectInfos);
//            } else {
//                personInfo.setProjectList(new LinkedList<>());
//            }
            return list.get(0);
        }
        return null;
    }
}
