package com.inspect.metadata.eqpbook.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.inspect.metadata.area.domain.BaseDataArea;
import com.inspect.metadata.area.mapper.BaseDataAreaMapper;
import com.inspect.metadata.eqpbook.domain.BasedataEqpBook;
import com.inspect.metadata.eqpbook.domain.BasedataEqpBookChannel;
import com.inspect.metadata.eqpbook.domain.BasedataEqpBookUp;
import com.inspect.metadata.eqpbook.domain.PatrolDeviceModel;
import com.inspect.metadata.eqpbook.domain.vo.BasedataAreaEquTreeVo;
import com.inspect.metadata.eqpbook.domain.vo.BasedataEqpBookTreeQueryFilterVo;
import com.inspect.metadata.eqpbook.domain.vo.PatrolResult;
import com.inspect.metadata.eqpbook.domain.vo.PatrolTaskFtp;
import com.inspect.metadata.eqpbook.domain.vo.ResultAnalysis;
import com.inspect.metadata.eqpbook.mapper.BasedataEqpBookChannelMapper;
import com.inspect.metadata.eqpbook.mapper.BasedataEqpBookMapper;
import com.inspect.metadata.eqpbook.service.IBasedataEqpBookService;
import com.inspect.metadata.eqpbook.util.BasedataAreaEquTreeVoUtil;
import com.inspect.metadata.montdata.domain.BasedataMontPatDevStaData;
import com.inspect.metadata.patrolpointmnt.domain.BasedataPatrolPoint;
import com.inspect.metadata.station.domain.BasedataStation;
import com.inspect.metadata.station.mapper.BasedataStationMapper;
import com.inspect.base.core.domain.DataMsg;
import com.inspect.base.core.utils.DateUtils;
import com.inspect.base.core.utils.HttpClientUtils;
import com.inspect.base.core.utils.SFTPUtil;
import com.inspect.base.core.utils.StringUtils;
import com.inspect.base.core.utils.bean.BeanUtils;
import com.inspect.base.core.utils.xml.GenXmlByBean;
import com.inspect.base.core.web.domain.AjaxResult;
import com.inspect.base.redis.service.RedisService;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class BasedataEqpBookServiceImpl implements IBasedataEqpBookService {
    @Resource
    private BasedataEqpBookMapper basedataEqpbookMapper;
    @Resource
    BaseDataAreaMapper baseDataAreaMapper;
    @Resource
    BasedataEqpBookChannelMapper basedataEqpbookChannelMapper;
    @Resource
    BasedataStationMapper basedataStationMapper;
    @Resource
    RedisService redisService;
    @Value("${liveSIPB.url}")
    private String mediaserviceUrl;
    @Value("${tcp.client.send}")
    String sendUrl;

    @PostConstruct
    public void init() {
        this.loadingEqpBookCache();
    }

    public BasedataEqpBook selectBasedataEqpBookByEqpBookId(Long eqpBookId) {
        return this.basedataEqpbookMapper.selectBasedataEqpBookByEqpBookId(eqpBookId);
    }

    public List<BasedataEqpBook> selectBasedataEqpBookList(BasedataEqpBook basedataEqpbook) {
        return this.basedataEqpbookMapper.selectBasedataEqpBookList(basedataEqpbook);
    }

    public int insertBasedataEqpBook(BasedataEqpBook basedataEqpbook) {
        basedataEqpbook.setCreateTime(DateUtils.getNowDate());
        int flag = this.basedataEqpbookMapper.insertBasedataEqpBook(basedataEqpbook);
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(basedataEqpbook);
        this.redisService.setCacheObject("basedata_eqpbook_info:" + basedataEqpbook.getPatrolDeviceCode(), jsonObject);
        return flag;
    }

    public int updateBasedataEqpBook(BasedataEqpBook basedataEqpbook) {
        basedataEqpbook.setUpdateTime(DateUtils.getNowDate());
        int flag = this.basedataEqpbookMapper.updateBasedataEqpBook(basedataEqpbook);
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(basedataEqpbook);
        this.redisService.setCacheObject("basedata_eqpbook_info:" + basedataEqpbook.getPatrolDeviceCode(), jsonObject);
        return flag;
    }

    public int deleteBasedataEqpBookByEqpBookIds(Long[] eqpbookIds) {
        return this.basedataEqpbookMapper.deleteBasedataEqpBookByEqpBookIds(eqpbookIds);
    }

    public int deleteBasedataEqpBookByEqpBookId(Long eqpbookId) {
        return this.basedataEqpbookMapper.deleteBasedataEqpBookByEqpBookId(eqpbookId);
    }

    public List<BasedataEqpBook> getUavList() {
        return this.basedataEqpbookMapper.getUavList();
    }

    public List<BasedataAreaEquTreeVo> getAreaEquTreeList(BaseDataArea area) {
        List<BaseDataArea> areas = this.baseDataAreaMapper.selectAreaList(area);
        List<BasedataAreaEquTreeVo> areaEquVos = new ArrayList<>();
        if (!areas.isEmpty()) {
            Iterator<BaseDataArea> iterator = areas.iterator();

            label38:
            while (true) {
                Long areaId;
                BasedataAreaEquTreeVo areaEquTreeVo;
                List eqpbooks;
                do {
                    if (!iterator.hasNext()) {
                        break label38;
                    }

                    BaseDataArea dataArea = iterator.next();
                    areaId = dataArea.getAreaId();
                    areaEquTreeVo = new BasedataAreaEquTreeVo();
                    areaEquTreeVo.setId(String.valueOf(areaId));
                    areaEquTreeVo.setParentId(String.valueOf(dataArea.getParentId()));
                    areaEquTreeVo.setAreaId(areaId);
                    areaEquTreeVo.setLabel(dataArea.getAreaName());
                    areaEquTreeVo.setAreaType(dataArea.getAreaType());
                    areaEquTreeVo.setAreaFlag("Yes");
                    areaEquVos.add(areaEquTreeVo);
                    BasedataEqpBook basedataEqpbook = new BasedataEqpBook();
                    basedataEqpbook.setAreaId(areaId);
                    eqpbooks = this.basedataEqpbookMapper.selectBasedataEqpBookList(basedataEqpbook);
                } while (eqpbooks.size() <= 0);

                Iterator iterator1 = eqpbooks.iterator();

                while (true) {
                    BasedataAreaEquTreeVo areaEquBookTreeVo;
                    List channelList;
                    do {
                        if (!iterator1.hasNext()) {
                            continue label38;
                        }

                        BasedataEqpBook eqpbook = (BasedataEqpBook) iterator1.next();
                        Long eqpbookId = eqpbook.getEqpBookId();
                        areaEquBookTreeVo = new BasedataAreaEquTreeVo();
                        areaEquBookTreeVo.setEqpBookId(eqpbookId);
                        areaEquBookTreeVo.setLabel(eqpbook.getPatrolDeviceName());
                        areaEquBookTreeVo.setId(areaId + "-" + eqpbookId);
                        areaEquBookTreeVo.setParentId(areaEquTreeVo.getId());
                        areaEquBookTreeVo.setPatrolDeviceCode(eqpbook.getPatrolDeviceCode());
                        areaEquBookTreeVo.setPatrolDeviceName(eqpbook.getPatrolDeviceName());
                        areaEquBookTreeVo.setPatrolDeviceType(eqpbook.getType());
                        areaEquBookTreeVo.setPatrolDeviceFlag("Yes");
                        areaEquBookTreeVo.setType(eqpbook.getType());
                        areaEquVos.add(areaEquBookTreeVo);
                        BasedataEqpBookChannel eqpbookChannel = new BasedataEqpBookChannel();
                        eqpbookChannel.setEqpBookId(eqpbookId);
                        channelList = this.basedataEqpbookChannelMapper.selectBasedataEqpBookChannelList(eqpbookChannel);
                    } while (channelList.isEmpty());

                    for (Object object : channelList) {
                        BasedataEqpBookChannel channel = (BasedataEqpBookChannel) object;
                        BasedataAreaEquTreeVo channelTreeVo = new BasedataAreaEquTreeVo();
                        channelTreeVo.setId(areaEquBookTreeVo.getId() + "-" + channel.getChannelId());
                        channelTreeVo.setPatrolDeviceCode(areaEquBookTreeVo.getPatrolDeviceCode());
                        channelTreeVo.setPatrolDeviceName(areaEquBookTreeVo.getPatrolDeviceName());
                        channelTreeVo.setPatrolDeviceType(areaEquBookTreeVo.getPatrolDeviceType());
                        channelTreeVo.setChannelId(channel.getChannelId());
                        channelTreeVo.setChannelCode(channel.getChannelCode());
                        channelTreeVo.setChannelName(channel.getChannelName());
                        channelTreeVo.setLabel(channel.getChannelName());
                        channelTreeVo.setParentId(areaEquBookTreeVo.getId());
                        channelTreeVo.setChannelFlag("Yes");
                        channelTreeVo.setAddress(channel.getAddress());
                        channelTreeVo.setHost(channel.getHost());
                        channelTreeVo.setPort(channel.getPort());
                        areaEquVos.add(channelTreeVo);
                    }
                }
            }
        }

        return (List<BasedataAreaEquTreeVo>) BasedataAreaEquTreeVoUtil.buildAreaTree(areaEquVos);
    }

    public List<BasedataAreaEquTreeVo> selectBasedataEqpbookOnlineList(BasedataEqpBookTreeQueryFilterVo queryFilterVo) {
        List<BasedataAreaEquTreeVo> areaEquVos = new ArrayList();
        String patroldeviceTyepFlag = queryFilterVo.getPatrolDeviceTypeFlag();
        BasedataEqpBook basedataEqpBookQuery = new BasedataEqpBook();
        Map<String, Object> params = new HashMap<>();
        if (null != patroldeviceTyepFlag && patroldeviceTyepFlag.equals("nvr")) {
            params.put("patrolDeviceTypeFlag", "nvr");
        }

        if (null != patroldeviceTyepFlag && patroldeviceTyepFlag.equals("ipc")) {
            params.put("patrolDeviceTypeFlag", "ipc");
        }

        if (null != patroldeviceTyepFlag && patroldeviceTyepFlag.equals("robotAndUav")) {
            params.put("patrolDeviceTypeFlag", "robotAndUav");
        }

        if (null != patroldeviceTyepFlag && patroldeviceTyepFlag.equals("uav")) {
            params.put("patrolDeviceTypeFlag", "uav");
        }

        basedataEqpBookQuery.setParams(params);
        List<BasedataEqpBook> allEqpbookList = this.basedataEqpbookMapper.selectBasedataEqpBookList(basedataEqpBookQuery);
        List<Long> onLineIdArray = new ArrayList<>();
        List<Long> offLineIdArray = new ArrayList<>();
        List<Long> allIdArray = new ArrayList<>();
        HashMap<Long, String> onlineStatusMap = new HashMap<>();
        if (!allEqpbookList.isEmpty()) {

            for (BasedataEqpBook basedataEqpbook : allEqpbookList) {
                allIdArray.add(basedataEqpbook.getEqpBookId());
                String patrolDeviceCode = basedataEqpbook.getPatrolDeviceCode();
                JSONObject jsonObject = this.redisService.getCacheObject("mont_patrol_device_online_status:" + patrolDeviceCode);
                if (null == jsonObject) {
                    offLineIdArray.add(basedataEqpbook.getEqpBookId());
                    onlineStatusMap.put(basedataEqpbook.getEqpBookId(), "0");
                } else {
                    onLineIdArray.add(basedataEqpbook.getEqpBookId());
                    onlineStatusMap.put(basedataEqpbook.getEqpBookId(), "1");
                }
            }
        }

        String isOnlineStatus = queryFilterVo.getOnlineStatus();
        if ("1".equals(isOnlineStatus)) {
            if (onLineIdArray.isEmpty()) {
                return areaEquVos;
            }

            queryFilterVo.setIds(onLineIdArray);
        }

        if ("0".equals(isOnlineStatus)) {
            if (offLineIdArray.isEmpty()) {
                return areaEquVos;
            }

            queryFilterVo.setIds(offLineIdArray);
        }

        if (null == isOnlineStatus || isOnlineStatus.isEmpty()) {
            queryFilterVo.setIds(allIdArray);
        }

        List<BasedataEqpBook> eqpBooks = this.basedataEqpbookMapper.selectBasedataEqpBookOnlineList(queryFilterVo);
        if (!eqpBooks.isEmpty()) {
            HashMap<Long, Long> allAreaIdHashMap = new HashMap<>();
            LinkedHashMap<Long, Long> hashMap = new LinkedHashMap<>();
            Iterator<BasedataEqpBook> iterator = eqpBooks.iterator();

            BasedataEqpBook eqpbook;
            Long eqpbookId;
            while (iterator.hasNext()) {
                eqpbook = iterator.next();
                eqpbookId = eqpbook.getAreaId();
                hashMap.put(eqpbookId, eqpbookId);
            }

            if (!hashMap.isEmpty()) {
                List<Long> areaList = new LinkedList<>();

                for (Long aLong : hashMap.keySet()) {
                    eqpbookId = aLong;
                    this.recursionFnHandAreaForAreaList(areaList, allAreaIdHashMap, eqpbookId);
                }

                if (!areaList.isEmpty()) {
                    this.handAreaEquTreeByList(areaEquVos, areaList);
                }
            }

            iterator = eqpBooks.iterator();

            label87:
            while (true) {
                BasedataAreaEquTreeVo areaEquBookTreeVo;
                List channelList;
                do {
                    if (!iterator.hasNext()) {
                        break label87;
                    }

                    eqpbook = iterator.next();
                    eqpbookId = eqpbook.getEqpBookId();
                    areaEquBookTreeVo = new BasedataAreaEquTreeVo();
                    areaEquBookTreeVo.setEqpBookId(eqpbookId);
                    areaEquBookTreeVo.setLabel(eqpbook.getPatrolDeviceName());
                    areaEquBookTreeVo.setId(eqpbook.getAreaId() + "-" + eqpbookId);
                    areaEquBookTreeVo.setParentId(String.valueOf(eqpbook.getAreaId()));
                    areaEquBookTreeVo.setAreaId(eqpbook.getAreaId());
                    areaEquBookTreeVo.setPatrolDeviceCode(eqpbook.getPatrolDeviceCode());
                    areaEquBookTreeVo.setPatrolDeviceName(eqpbook.getPatrolDeviceName());
                    areaEquBookTreeVo.setPatrolDeviceType(eqpbook.getType());
                    areaEquBookTreeVo.setPatrolDeviceFlag("Yes");
                    areaEquBookTreeVo.setType(eqpbook.getType());
                    if (onlineStatusMap.containsKey(eqpbookId)) {
                        areaEquBookTreeVo.setPatrolDeviceOnlineStatus((String) onlineStatusMap.get(eqpbookId));
                    } else {
                        areaEquBookTreeVo.setPatrolDeviceOnlineStatus("0");
                    }

                    areaEquVos.add(areaEquBookTreeVo);
                    BasedataEqpBookChannel eqpBookChannel = new BasedataEqpBookChannel();
                    eqpBookChannel.setEqpBookId(eqpbookId);
                    channelList = this.basedataEqpbookChannelMapper.selectBasedataEqpBookChannelList(eqpBookChannel);
                } while (channelList.isEmpty());

                BasedataAreaEquTreeVo channelTreeVo;
                for (Iterator iterator1 = channelList.iterator(); iterator1.hasNext(); areaEquVos.add(channelTreeVo)) {
                    BasedataEqpBookChannel channel = (BasedataEqpBookChannel) iterator1.next();
                    channelTreeVo = new BasedataAreaEquTreeVo();
                    channelTreeVo.setId(areaEquBookTreeVo.getId() + "-" + channel.getChannelId());
                    channelTreeVo.setPatrolDeviceCode(areaEquBookTreeVo.getPatrolDeviceCode());
                    channelTreeVo.setPatrolDeviceName(areaEquBookTreeVo.getPatrolDeviceName());
                    channelTreeVo.setPatrolDeviceType(areaEquBookTreeVo.getPatrolDeviceType());
                    channelTreeVo.setAreaId(areaEquBookTreeVo.getAreaId());
                    channelTreeVo.setChannelId(channel.getChannelId());
                    channelTreeVo.setChannelCode(channel.getChannelCode());
                    channelTreeVo.setChannelName(channel.getChannelName());
                    channelTreeVo.setLabel(channel.getChannelName());
                    channelTreeVo.setParentId(areaEquBookTreeVo.getId());
                    channelTreeVo.setChannelFlag("Yes");
                    channelTreeVo.setAddress(channel.getAddress());
                    channelTreeVo.setHost(channel.getHost());
                    channelTreeVo.setPort(channel.getPort());
                    channelTreeVo.setChannelType(channel.getChannelType());
                    boolean hasKey = this.redisService.hasKey("mont_patrol_device_channel_online_status:" + channel.getChannelCode()).booleanValue();
                    if (hasKey) {
                        channelTreeVo.setPatrolDeviceOnlineStatus("1");
                    } else {
                        channelTreeVo.setPatrolDeviceOnlineStatus("0");
                    }
                }
            }
        }

        return (List<BasedataAreaEquTreeVo>) BasedataAreaEquTreeVoUtil.buildAreaTree(areaEquVos);
    }

    private void recursionFnHandArea(List<BasedataAreaEquTreeVo> areaEquVos, HashMap<Long, Long> allAreaIdHashMap, Long areaId) {
        if (!allAreaIdHashMap.containsKey(areaId)) {
            allAreaIdHashMap.put(areaId, areaId);
            BaseDataArea area = this.baseDataAreaMapper.selectAreaById(areaId);
            if (null != area) {
                BasedataAreaEquTreeVo areaEquTreeVo = new BasedataAreaEquTreeVo();
                areaEquTreeVo.setId(String.valueOf(areaId));
                areaEquTreeVo.setAreaId(areaId);
                areaEquTreeVo.setLabel(area.getAreaName());
                areaEquTreeVo.setAreaType(area.getAreaType());
                areaEquTreeVo.setAreaFlag("Yes");
                areaEquVos.add(areaEquTreeVo);
                if (null != area.getParentId()) {
                    areaId = area.getParentId();
                    areaEquTreeVo.setParentId(String.valueOf(areaId));
                    this.recursionFnHandArea(areaEquVos, allAreaIdHashMap, areaId);
                }

            }
        }
    }

    private void recursionFnHandAreaForAreaList(List<Long> areaList, HashMap<Long, Long> allAreaIdHashMap, Long areaId) {
        if (!allAreaIdHashMap.containsKey(areaId)) {
            allAreaIdHashMap.put(areaId, areaId);
            BaseDataArea area = this.baseDataAreaMapper.selectAreaById(areaId);
            if (null != area) {
                areaList.add(areaId);
                if (null != area.getParentId()) {
                    areaId = area.getParentId();
                    this.recursionFnHandAreaForAreaList(areaList, allAreaIdHashMap, areaId);
                }

            }
        }
    }

    private void handAreaEquTreeByList(List<BasedataAreaEquTreeVo> areaEquVos, List<Long> areaList) {
        BaseDataArea areaQu = new BaseDataArea();
        Map<String, Object> params = new HashMap<>();
        params.put("areaIdList", areaList);
        areaQu.setParams(params);
        List<BaseDataArea> areas = this.baseDataAreaMapper.selectAreaList(areaQu);
        if (null != areas && !areas.isEmpty()) {

            for (BaseDataArea area : areas) {
                BasedataAreaEquTreeVo areaEquTreeVo = new BasedataAreaEquTreeVo();
                areaEquTreeVo.setId(String.valueOf(area.getAreaId()));
                areaEquTreeVo.setAreaId(area.getAreaId());
                areaEquTreeVo.setLabel(area.getAreaName());
                areaEquTreeVo.setAreaType(area.getAreaType());
                areaEquTreeVo.setAreaFlag("Yes");
                areaEquTreeVo.setParentId(String.valueOf(area.getParentId()));
                areaEquVos.add(areaEquTreeVo);
            }
        }

    }

    public int synPatrolEqpFromGwbMedia() {
        String url = this.mediaserviceUrl + "/api/v1/device/list";
        String result = null;

        try {
            result = HttpClientUtils.get(url, "");
            JSONObject jsonObject = JSONObject.parseObject(result);
            if (null != jsonObject) {
                JSONArray jsonObjectItems = jsonObject.getJSONArray("DeviceList");
                if (null != jsonObjectItems) {
                    for (int i = 0; i < jsonObjectItems.size(); ++i) {
                        JSONObject item = jsonObjectItems.getJSONObject(i);
                        String patrolDeviceCode = item.getString("ID");
                        String patrolDeviceName = item.getString("Name");
                        BasedataEqpBook basedataEqpbook = new BasedataEqpBook();
                        basedataEqpbook.setPatrolDeviceCode(patrolDeviceCode);
                        List<BasedataEqpBook> eqpbookList = this.basedataEqpbookMapper.selectBasedataEqpBookList(basedataEqpbook);
                        BasedataEqpBook eqpBookEdit;
                        if (!eqpbookList.isEmpty()) {
                            eqpBookEdit = new BasedataEqpBook();
                            eqpBookEdit.setEqpBookId(eqpbookList.get(0).getEqpBookId());
                            eqpBookEdit.setPatrolDeviceCode(patrolDeviceCode);
                            if (!patrolDeviceName.isEmpty()) {
                                eqpBookEdit.setPatrolDeviceName(patrolDeviceName);
                            }

                            eqpBookEdit.setUpdateTime(DateUtils.getNowDate());
                            this.basedataEqpbookMapper.updateBasedataEqpBook(eqpBookEdit);
                        } else {
                            eqpBookEdit = new BasedataEqpBook();
                            eqpBookEdit.setPatrolDeviceCode(patrolDeviceCode);
                            eqpBookEdit.setPatrolDeviceName(patrolDeviceName);
                            eqpBookEdit.setCreateTime(DateUtils.getNowDate());
                            this.basedataEqpbookMapper.insertBasedataEqpBook(eqpBookEdit);
                            System.out.println("eqpbook.id::" + eqpBookEdit.getEqpBookId());
                        }
                    }
                }
            }

            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    public int synPatrolEqpChannelFromGwbMedia() {
        List<BasedataEqpBook> list = this.basedataEqpbookMapper.selectBasedataEqpBookList(null);
        if (list.isEmpty()) {
            return 0;
        } else {

            for (BasedataEqpBook basedataEqpbook : list) {
                Long eqpBookId = basedataEqpbook.getEqpBookId();
                String patrolDeviceCode = basedataEqpbook.getPatrolDeviceCode();
                String url = this.mediaserviceUrl + "/api/v1/device/channellist";

                try {
                    String result = HttpClientUtils.get(url, "serial=" + patrolDeviceCode);
                    JSONObject jsonObject = JSONObject.parseObject(result);
                    if (null != jsonObject) {
                        JSONArray jsonArray = jsonObject.getJSONArray("ChannelList");
                        if (null != jsonArray) {
                            for (int i = 0; i < jsonArray.size(); ++i) {
                                JSONObject item = jsonArray.getJSONObject(i);
                                String channelCode = item.getString("ID");
                                String channelName = item.getString("Name");
                                if (null != channelName && !channelName.isEmpty()) {
                                    BasedataEqpBookChannel eqpBookChannel = new BasedataEqpBookChannel();
                                    eqpBookChannel.setEqpBookId(eqpBookId);
                                    eqpBookChannel.setChannelCode(channelCode);
                                    List<BasedataEqpBookChannel> channelList = this.basedataEqpbookChannelMapper.selectBasedataEqpBookChannelList(eqpBookChannel);
                                    BasedataEqpBookChannel eqpBookChannelInsert;
                                    if (null != channelList && !channelList.isEmpty()) {
                                        eqpBookChannelInsert = channelList.get(0);
                                        eqpBookChannelInsert.setChannelName(channelName);
                                        eqpBookChannelInsert.setUpdateTime(DateUtils.getNowDate());
                                        this.basedataEqpbookChannelMapper.updateBasedataEqpBookChannel(eqpBookChannelInsert);
                                    } else {
                                        eqpBookChannelInsert = new BasedataEqpBookChannel();
                                        eqpBookChannelInsert.setEqpBookId(eqpBookId);
                                        eqpBookChannelInsert.setChannelCode(channelCode);
                                        eqpBookChannelInsert.setChannelName(channelName);
                                        eqpBookChannelInsert.setCreateTime(DateUtils.getNowDate());
                                        this.basedataEqpbookChannelMapper.insertBasedataEqpBookChannel(eqpBookChannelInsert);
                                    }
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    return 0;
                }
            }

            return 1;
        }
    }

    public String checkEqpBookCodeUnique(BasedataEqpBook basedataEqpBook) {
        long eqpBookId = StringUtils.isNull(basedataEqpBook.getEqpBookId()) ? -1L : basedataEqpBook.getEqpBookId();
        BasedataEqpBook info = this.basedataEqpbookMapper.checkEqpBookCodeUnique(basedataEqpBook.getPatrolDeviceCode(), basedataEqpBook.getEqpBookId());
        return StringUtils.isNotNull(info) && info.getEqpBookId() != eqpBookId ? "1" : "0";
    }

    public String checkEqpBookNameUnique(BasedataEqpBook basedataEqpBook) {
        long eqpBookId = StringUtils.isNull(basedataEqpBook.getEqpBookId()) ? -1L : basedataEqpBook.getEqpBookId();
        BasedataEqpBook info = this.basedataEqpbookMapper.checkEqpBookNameUnique(basedataEqpBook.getPatrolDeviceName(), basedataEqpBook.getEqpBookId());
        return StringUtils.isNotNull(info) && info.getEqpBookId() != eqpBookId ? "1" : "0";
    }

    public BasedataEqpBook selectBasedataEqpBookByPatrolDeviceCode(String deviceCode) {
        return this.basedataEqpbookMapper.selectBasedataEqpBookByPatrolDeviceCode(deviceCode);
    }

    public void loadingEqpBookCache() {
        List<BasedataEqpBook> eqpBooks = this.basedataEqpbookMapper.selectBasedataEqpBookList(new BasedataEqpBook());
        if (null != eqpBooks && !eqpBooks.isEmpty()) {

            for (BasedataEqpBook eqpBook : eqpBooks) {
                JSONObject jsonObject = (JSONObject) JSONObject.toJSON(eqpBook);
                this.redisService.setCacheObject("basedata_eqpbook_info:" + eqpBook.getPatrolDeviceCode(), jsonObject);
            }
        }

    }

    @Async
    public void setSendServiceMap(String sendUrl) {
        BasedataEqpBook basedataEqpbook = new BasedataEqpBook();
        basedataEqpbook.setType("20");
        List<BasedataEqpBook> basedataEqpBookList = this.basedataEqpbookMapper.selectBasedataEqpBookList(basedataEqpbook);
        String sendCode = basedataEqpBookList.get(0).getPatrolDeviceCode();
        String file_path = basedataEqpBookList.get(0).getMapFilePath();
        List<BasedataStation> basedataStation = this.basedataStationMapper.selectBasedataStationList(new BasedataStation());
        JSONObject job = getJsonObject(basedataStation, sendCode, file_path);
        System.out.println("地图主动上报上级系统=" + job.toJSONString());
        this.sendMsg(job.toJSONString());
    }

    private static JSONObject getJsonObject(List<BasedataStation> basedataStation, String sendCode, String file_path) {
        String code = basedataStation.get(0).getStationNo();
        String Type = "11";
        String time = DateUtils.getTime();
        JSONObject job = new JSONObject();
        job.put("SendCode", sendCode);
        job.put("ReceiveCode", "");
        job.put("Code", code);
        job.put("Type", Type);
        JSONArray jsonArray = new JSONArray();
        JSONObject item = new JSONObject();
        item.put("time", time);
        item.put("type", "9");
        item.put("file_path", file_path);
        jsonArray.add(item);
        job.put("Items", jsonArray);
        return job;
    }

    @Async
    public void setSendService(String type) {
        if (StringUtils.isEmpty(type)) {
            BasedataEqpBook basedataEqpbook = new BasedataEqpBook();
            basedataEqpbook.setType(type);
            List<BasedataEqpBook> list = this.basedataEqpbookMapper.selectBasedataEqpBookList(basedataEqpbook);
            String modelXml = null;
            if (null != list && !list.isEmpty()) {
                GenXmlByBean<Object> pulseGet = new GenXmlByBean<>();
                PatrolDeviceModel pd = new PatrolDeviceModel();
                List<BasedataEqpBookUp> items = new ArrayList<>();

                for (BasedataEqpBook book : list) {
                    BasedataEqpBookUp up = new BasedataEqpBookUp();
                    BeanUtils.copyBeanProp(up, book);
                    items.add(up);
                }

                pd.setItem(items);
                modelXml = pulseGet.getXml(pd);
            }

            assert modelXml != null;
            InputStream in = new ByteArrayInputStream(modelXml.getBytes());
            PatrolTaskFtp patrolTaskFtp = this.basedataEqpbookMapper.selectPatrolTaskFtpByLineId(3L);
            List<BasedataStation> basedataStation = this.basedataStationMapper.selectBasedataStationList(new BasedataStation());
            basedataEqpbook.setType("20");
            List<BasedataEqpBook> basedataEqpBookList = this.basedataEqpbookMapper.selectBasedataEqpBookList(basedataEqpbook);
            String filename = "EqpBook" + System.currentTimeMillis();
            String mapPath = basedataStation.get(0).getStationNo() + "/Model/";
            DataMsg DataMsg = new DataMsg();
            DataMsg.setIp(patrolTaskFtp.getFtpIp());
            DataMsg.setPort(patrolTaskFtp.getFtpPort());
            DataMsg.setUsername(patrolTaskFtp.getFtpUserName());
            DataMsg.setPassword(patrolTaskFtp.getFtpPwd());
            DataMsg.setBasePath(patrolTaskFtp.getFtpPath());
            DataMsg.setType("0");
            DataMsg.setFilePath(mapPath);
            DataMsg.setFileName(filename + ".xml");
            DataMsg.setInputStream(in);
            DataMsg.setIsImplicit("true");
            SFTPUtil.uploadFileForXml(DataMsg);
            String sendCode = basedataEqpBookList.get(0).getPatrolDeviceCode();
            String code = basedataStation.get(0).getStationNo();
            String time = DateUtils.getTime();
            String file_path = mapPath + filename + ".xml";
            JSONObject job = new JSONObject();
            job.put("SendCode", sendCode);
            job.put("ReceiveCode", "");
            job.put("Code", code);
            job.put("Type", "11");
            JSONArray jsonArray = getJsonArray(type, time, file_path);
            job.put("Items", jsonArray);
            System.out.println("数据变更后上报上级系统=" + job.toJSONString());
            this.sendMsg(job.toJSONString());
        }
    }

    private static JSONArray getJsonArray(String type, String time, String file_path) {
        JSONArray jsonArray = new JSONArray();
        JSONObject item = new JSONObject();
        item.put("time", time);
        if (!"1".equals(type) && !"2".equals(type) && !"3".equals(type)) {
            if ("10".equals(type)) {
                item.put("type", "4");
            } else if ("13".equals(type)) {
                item.put("type", "5");
            } else if ("14".equals(type)) {
                item.put("type", "6");
            } else if ("20".equals(type)) {
                item.put("type", "2");
            }
        } else {
            item.put("type", "3");
        }

        item.put("file_path", file_path);
        jsonArray.add(item);
        return jsonArray;
    }

    public AjaxResult sendMsg(String msg) {
        try {
            String resultJson = HttpClientUtils.postJson(this.sendUrl, msg, null);
            return JSONObject.parseObject(resultJson, AjaxResult.class);
        } catch (Exception e) {
            return AjaxResult.fail(500, "上报消息失败");
        }
    }

    @Async
    public AjaxResult uploadPicMap(InputStream in, String filename, String patroldeviceCode) {
        AjaxResult ajaxResult = new AjaxResult();
        PatrolTaskFtp patrolTaskFtp = this.basedataEqpbookMapper.selectPatrolTaskFtpByLineId(3L);
        List<BasedataStation> list = this.basedataStationMapper.selectBasedataStationList(new BasedataStation());
        String fileType = FilenameUtils.getExtension(filename).toLowerCase();
        filename = "EqpBookMap" + System.currentTimeMillis();
        String mapPath = list.get(0).getStationNo() + "/Map/";
        DataMsg DataMsg = new DataMsg();
        DataMsg.setIp(patrolTaskFtp.getFtpIp());
        DataMsg.setPort(patrolTaskFtp.getFtpPort());
        DataMsg.setUsername(patrolTaskFtp.getFtpUserName());
        DataMsg.setPassword(patrolTaskFtp.getFtpPwd());
        DataMsg.setBasePath(patrolTaskFtp.getFtpPath());
        DataMsg.setType("0");
        DataMsg.setFilePath(mapPath);
        DataMsg.setFileName(filename + "." + fileType);
        DataMsg.setInputStream(in);
        DataMsg.setIsImplicit("true");
        SFTPUtil.uploadFileForXml(DataMsg);
        BasedataEqpBook basedataEqpbook = this.basedataEqpbookMapper.selectBasedataEqpBookByPatrolDeviceCode(patroldeviceCode);
        basedataEqpbook.setMapFilePath(mapPath + filename + "." + fileType);
        basedataEqpbook.setUpdateTime(DateUtils.getNowDate());
        int i = this.basedataEqpbookMapper.updateBasedataEqpBook(basedataEqpbook);
        if (i > 0 && "20".equals(basedataEqpbook.getType())) {
            this.setSendServiceMap(this.sendUrl);
        }

        ajaxResult.put("200", "成功！");
        return ajaxResult;
    }

    public List<Map<String, Integer>> deviceNumList() {
        return this.basedataEqpbookMapper.deviceNumList();
    }

    public List<String> deviceStatusList() {
        return this.basedataEqpbookMapper.deviceStatusList();
    }

    public List<BasedataMontPatDevStaData> deviceStatusListInfo(BasedataMontPatDevStaData basedataMontPatdevstadata) {
        return this.basedataEqpbookMapper.deviceStatusListInfo(basedataMontPatdevstadata);
    }

    public List<String> deviceOlinList() {
        return this.basedataEqpbookMapper.deviceOlinList();
    }

    public List<String> alarmList() {
        return this.basedataEqpbookMapper.alarmList();
    }

    public List<PatrolResult> alarmListInfo(ResultAnalysis resultAnalysis) {
        return this.basedataEqpbookMapper.alarmListInfo(resultAnalysis);
    }

    public List<String> abnormalList() {
        return this.basedataEqpbookMapper.abnormalList();
    }

    public List<PatrolResult> abnormalListInfo(ResultAnalysis resultAnalysis) {
        return this.basedataEqpbookMapper.abnormalListInfo(resultAnalysis);
    }

    public List<BasedataPatrolPoint> getSubtypeData(BasedataPatrolPoint basedataPatrolpoint) {
        return this.basedataEqpbookMapper.getSubtypeData(basedataPatrolpoint);
    }

    public Map<String, Object> selectDevInfoById(String deviceId) {
        return this.basedataEqpbookMapper.selectDevInfoById(deviceId);
    }

    public List<Map<String, Object>> selectBasePointByPointId(String pointId) {
        return this.basedataEqpbookMapper.selectBasePointByPointId(pointId);
    }

    public List<Map<String, Object>> selectBasePointPre(String pointId) {
        return this.basedataEqpbookMapper.selectBasePointPre(pointId);
    }

    public Map<String, String> selectPointInfoById(String deviceId) {
        return this.basedataEqpbookMapper.selectPointInfoById(deviceId);
    }

    public Map<String, Integer> deviceOnlineCount() {
        Map<String, Integer> map = new HashMap<>();
        int onlineCount = 0;
        int tatolCount = 0;
        BasedataEqpBook queryFilterVo = new BasedataEqpBook();
        Map<String, Object> params = new HashMap<>();
        params.put("patroldeviceTypeFlag", "ipc");
        queryFilterVo.setParams(params);
        List<BasedataEqpBook> deviceList = this.basedataEqpbookMapper.selectBasedataEqpBookList(queryFilterVo);
        if (null != deviceList && !deviceList.isEmpty()) {
            Iterator<BasedataEqpBook> iterator = deviceList.iterator();
            label39:
            while (true) {
                while (true) {
                    if (!iterator.hasNext()) {
                        break label39;
                    }

                    BasedataEqpBook eqpBook = iterator.next();
                    String type = eqpBook.getType();
                    String patrolDeviceCode = eqpBook.getPatrolDeviceCode();
                    Long eqpBookId = eqpBook.getEqpBookId();
                    if (!"10".equals(type)) {
                        ++tatolCount;
                        boolean hasKey = this.redisService.hasKey("mont_patrol_device_online_status:" + patrolDeviceCode).booleanValue();
                        if (hasKey) {
                            ++onlineCount;
                        }
                    } else {
                        BasedataEqpBookChannel eqpBookChannel = new BasedataEqpBookChannel();
                        eqpBookChannel.setEqpBookId(eqpBookId);
                        List<BasedataEqpBookChannel> channelList = this.basedataEqpbookChannelMapper.selectBasedataEqpBookChannelList(eqpBookChannel);
                        if (null != channelList && !channelList.isEmpty()) {

                            for (BasedataEqpBookChannel channel : channelList) {
                                ++tatolCount;
                                String channelCode = channel.getChannelCode();
                                boolean hasKey = this.redisService.hasKey("mont_patrol_device_channel_online_status:" + channelCode).booleanValue();
                                if (hasKey) {
                                    ++onlineCount;
                                }
                            }
                        }
                    }
                }
            }
        }

        map.put("tatolCount", tatolCount);
        map.put("onlineCount", onlineCount);
        return map;
    }

    public Map<String, Integer> deviceOnlineCountByType(String type) {
        Map<String, Integer> map = new HashMap<>();
        int onlineCount = 0;
        int tatolCount = 0;
        BasedataEqpBook queryFilterVo = new BasedataEqpBook();
        queryFilterVo.setType(type);
        List<BasedataEqpBook> deviceList = this.basedataEqpbookMapper.selectBasedataEqpBookList(queryFilterVo);
        if (null != deviceList && !deviceList.isEmpty()) {
            Iterator<BasedataEqpBook> iterator = deviceList.iterator();

            label52:
            while (true) {
                do {
                    while (true) {
                        if (!iterator.hasNext()) {
                            break label52;
                        }

                        BasedataEqpBook eqpBook = iterator.next();
                        String patrolDeviceCode = eqpBook.getPatrolDeviceCode();
                        Long eqpBookId = eqpBook.getEqpBookId();
                        if (!"10".equals(type)) {
                            ++tatolCount;
                            boolean hasKey = this.redisService.hasKey("mont_patrol_device_online_status:" + patrolDeviceCode).booleanValue();
                            if (hasKey) {
                                ++onlineCount;
                            }
                            break;
                        }

                        if ("10".equals(type)) {
                            BasedataEqpBookChannel eqpbookChannel = new BasedataEqpBookChannel();
                            eqpbookChannel.setEqpBookId(eqpBookId);
                            List<BasedataEqpBookChannel> channelList = this.basedataEqpbookChannelMapper.selectBasedataEqpBookChannelList(eqpbookChannel);
                            if (null != channelList && !channelList.isEmpty()) {

                                for (BasedataEqpBookChannel channel : channelList) {
                                    ++tatolCount;
                                    String channelCode = channel.getChannelCode();
                                    boolean hasKey = this.redisService.hasKey("mont_patrol_device_channel_online_status:" + channelCode).booleanValue();
                                    if (hasKey) {
                                        ++onlineCount;
                                    }
                                }
                            }
                        }
                    }
                } while (!"20".equals(type) && !"11".equals(type));

                ++onlineCount;
            }
        }

        map.put("tatolCount", tatolCount);
        map.put("onlineCount", onlineCount);
        return map;
    }

    public String queryEqpBookCode(String patrolDeviceCode) {
        return this.basedataEqpbookMapper.queryEqpBookCode(patrolDeviceCode);
    }
}
