package com.inspect.metadata.eqpbook.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.inspect.base.core.utils.ServletUtils;
import com.inspect.metadata.alg.domain.BasedataAlgSubtype;
import com.inspect.metadata.alg.service.IBasedataAlgSubtypeService;
import com.inspect.metadata.area.controller.BaseDataAreaController;
import com.inspect.metadata.area.domain.BaseDataArea;
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.AlarmListVo;
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.ResultAnalysis;
import com.inspect.metadata.eqpbook.domain.vo.resultList;
import com.inspect.metadata.eqpbook.domain.vo.results;
import com.inspect.metadata.eqpbook.service.IBasedataEqpBookChannelService;
import com.inspect.metadata.eqpbook.service.IBasedataEqpBookService;
import com.inspect.metadata.eqpbook.task.FeignTaskClient;
import com.inspect.metadata.montdata.domain.BasedataMontPatDevStaData;
import com.inspect.metadata.mqutil.FeignMsgClient;
import com.inspect.metadata.patrolpointmnt.domain.BasedataPatrolPoint;
import com.inspect.metadata.patrolpointmnt.mapper.BasedataPatrolPointMapper;
import com.inspect.metadata.patrolpointmnt.service.IBasedataPatrolPointService;
import com.inspect.metadata.station.service.IBasedataStationService;
import com.inspect.metadata.threshold.domain.BasedataThresholdModification;
import com.inspect.metadata.threshold.service.IBasedataThresholdModificationService;
import com.inspect.base.core.domain.Response;
import com.inspect.base.core.sftp.SftpClient;
import com.inspect.base.core.utils.StringUtils;
import com.inspect.base.core.utils.bean.BeanUtils;
import com.inspect.base.core.utils.json.XmlToJsonUtil;
import com.inspect.base.core.utils.poi.ExcelUtil;
import com.inspect.base.core.utils.xml.GenXmlByBean;
import com.inspect.base.core.web.controller.BaseController;
import com.inspect.base.core.web.domain.AjaxResult;
import com.inspect.base.core.web.page.TableDataInfo;
import com.inspect.common.log.annotation.Log;
import com.inspect.common.log.enums.BizType;
import com.inspect.base.redis.service.RedisService;
import com.inspect.common.security.annotation.RequiresPermissions;
import com.inspect.common.security.utils.DictUtils;
import com.inspect.ivs.base.feign.IvsFeign;
import com.inspect.ivs.base.feign.view.SipbDeviceListView;
import com.inspect.ivs.base.feign.view.SipbDeviceListView.CameraBriefInfo;
import com.inspect.system.base.domain.SysDictData;
import com.github.pagehelper.PageInfo;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping({"/eqpbook"})
public class BasedataEqpBookController extends BaseController {
    @Resource
    private IBasedataEqpBookService basedataEqpBookService;
    @Resource
    private IBasedataEqpBookChannelService basedataEqpBookChannelService;
    @Resource
    private FeignMsgClient feignMsgClient;
    @Resource
    private IBasedataStationService basedataStationService;
    @Autowired
    private SftpClient sftpClint;
    @Autowired
    private IvsFeign ivsFeign;
    @Value("${tcp.client.send}")
    String sendUrl;
    @Autowired
    RedisService redisService;
    @Autowired
    private IBasedataAlgSubtypeService basedataAlgSubtypeService;
    @Autowired
    private IBasedataPatrolPointService basedataPatrolPointService;
    @Autowired
    private IBasedataThresholdModificationService basedataThresholdModificationService;
    @Autowired
    private FeignTaskClient feignTaskClient;
    @Autowired
    private BaseDataAreaController baseDataAreaController;

    @Resource
    private BasedataPatrolPointMapper basedataPatrolpointMapper;

    @GetMapping({"/list"})
    public TableDataInfo list(BasedataEqpBook basedataEqpbook) {
        String patroldeviceCode = ServletUtils.getParameter("patroldeviceCode");
        if (StringUtils.isNotEmpty(patroldeviceCode)) {
            basedataEqpbook.setPatrolDeviceCode(patroldeviceCode);
        }
        logger.info("---------------list-----------basedataEqpbook:{}", basedataEqpbook);
        if (basedataEqpbook.getPatrolDeviceCode() != null && basedataEqpbook.getPatrolDeviceCode().startsWith("sync:")) {
            // 和许继，无人机同步点位
            String patrolDeviceCode = basedataEqpbook.getPatrolDeviceCode();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("Type", "61");
            jsonObject.put("ReceiveCode", StringUtils.split(patrolDeviceCode, ":")[1]);
            String msg = jsonObject.toJSONString();
            feignTaskClient.sendCommand(msg);
        }
        this.startPage();
        List<BasedataEqpBook> list = this.basedataEqpBookService.selectBasedataEqpBookList(basedataEqpbook);
        return this.getDataTable(list);
    }

    @RequiresPermissions({"basedata:eqpbook:export"})
    @Log(
            title = "基础数据-设备台账主",
            businessType = BizType.EXPORT
    )
    @PostMapping({"/export"})
    public void export(HttpServletResponse response, BasedataEqpBook basedataEqpbook) {
        List<BasedataEqpBook> list = this.basedataEqpBookService.selectBasedataEqpBookList(basedataEqpbook);
        if (null != list && !list.isEmpty()) {

            for (BasedataEqpBook eqpBook : list) {
                String isTransport = eqpBook.getIsTransport();
                if (null != isTransport) {
                    if (isTransport.equals("0")) {
                        eqpBook.setIsTransport("非轮转");
                    } else if (isTransport.equals("1")) {
                        eqpBook.setIsTransport("轮转");
                    }
                }
            }
        }

        ExcelUtil<BasedataEqpBook> util = new ExcelUtil<>(BasedataEqpBook.class);
        util.exportExcel(response, list, "基础数据-设备台账主数据");
    }

    @RequiresPermissions({"basedata:eqpbook:query"})
    @GetMapping({"/{eqpbookId}"})
    public AjaxResult getInfo(@PathVariable("eqpbookId") Long eqpBookId) {
        return AjaxResult.success(this.basedataEqpBookService.selectBasedataEqpBookByEqpBookId(eqpBookId));
    }

    @RequiresPermissions({"basedata:eqpbook:add"})
    @Log(
            title = "基础数据-设备台账主",
            businessType = BizType.INSERT
    )
    @PostMapping
    public AjaxResult add(@RequestBody BasedataEqpBook basedataEqpbook) {
        if ("1".equals(this.basedataEqpBookService.checkEqpBookNameUnique(basedataEqpbook))) {
            return AjaxResult.error("设备'" + basedataEqpbook.getPatrolDeviceName() + "'名称已存在");
        } else if ("1".equals(this.basedataEqpBookService.checkEqpBookCodeUnique(basedataEqpbook))) {
            return AjaxResult.error("设备'" + basedataEqpbook.getPatrolDeviceCode() + "'编码已存在");
        } else {
            int i = this.basedataEqpBookService.insertBasedataEqpBook(basedataEqpbook);
            if (i > 0 && "1,2,310,13,14,20".contains(basedataEqpbook.getType())) {
                this.basedataEqpBookService.setSendService(basedataEqpbook.getType());
            }

            return this.toAjax(i);
        }
    }

    @RequiresPermissions({"basedata:eqpbook:edit"})
    @Log(
            title = "基础数据-设备台账主",
            businessType = BizType.UPDATE
    )
    @PostMapping({"/edit"})
    public AjaxResult edit(@RequestBody BasedataEqpBook basedataEqpbook) {
        int i = this.basedataEqpBookService.updateBasedataEqpBook(basedataEqpbook);
        if (i > 0 && "1,2,310,13,14,20".contains(basedataEqpbook.getType())) {
            this.basedataEqpBookService.setSendService(basedataEqpbook.getType());
        }

        return this.toAjax(i);
    }

    @RequiresPermissions({"basedata:eqpbook:remove"})
    @Log(
            title = "基础数据-设备台账主",
            businessType = BizType.DELETE
    )
    @PostMapping({"/remove/{eqpbookIds}"})
    public AjaxResult remove(@PathVariable("eqpbookIds") Long[] eqpBookIds) {
        List<BasedataEqpBook> basedataEqpBookList = new ArrayList<>();

        int i;
        for (i = 0; i < eqpBookIds.length; ++i) {
            BasedataEqpBook basedataEqpbook = this.basedataEqpBookService.selectBasedataEqpBookByEqpBookId(eqpBookIds[i]);
            basedataEqpBookList.add(basedataEqpbook);
        }

        i = this.basedataEqpBookService.deleteBasedataEqpBookByEqpBookIds(eqpBookIds);

        for (BasedataEqpBook basedataEqpbook : basedataEqpBookList) {
            if (i > 0 && "1,2,310,13,14,20".contains(basedataEqpbook.getType())) {
                this.basedataEqpBookService.setSendService(basedataEqpbook.getType());
            }
        }

        return this.toAjax(i);
    }

    @PostMapping({"/exportTemplate"})
    public void exportTemplate(HttpServletResponse response) {
        ExcelUtil<BasedataEqpBook> util = new ExcelUtil<>(BasedataEqpBook.class);
        util.importTemplateExcel(response, "数据", StringUtils.EMPTY);
    }

    @PostMapping({"/importData"})
    public AjaxResult importData(MultipartFile file) throws Exception {
        StringBuilder successMsg = new StringBuilder();
        ExcelUtil<BasedataEqpBook> util = new ExcelUtil<>(BasedataEqpBook.class);
        List<BasedataEqpBook> userList = util.importExcel(file.getInputStream());
        int i = 0;
        int s = 0;
        List<Object> strR = new ArrayList<>();
        List<Object> strE = new ArrayList<>();
        List<Object> strF = new ArrayList<>();
        for (BasedataEqpBook arr : userList) {
            BasedataEqpBook baseDataEqpbook = new BasedataEqpBook();
            baseDataEqpbook.setPatrolDeviceCode(arr.getPatrolDeviceCode());
            baseDataEqpbook.setPatrolDeviceName(arr.getPatrolDeviceName());
            baseDataEqpbook.setDeviceModel(arr.getDeviceModel());
            ++i;
            if (!StringUtils.isNotEmpty(baseDataEqpbook.getPatrolDeviceCode()) && !StringUtils.isNotEmpty(baseDataEqpbook.getPatrolDeviceName()) && !StringUtils.isNotEmpty(baseDataEqpbook.getDeviceModel())) {
                strE.add(i + ",");
            } else {
                List<BasedataEqpBook> listArr = this.basedataEqpBookService.selectBasedataEqpBookList(baseDataEqpbook);
                if (!listArr.isEmpty()) {
                    strR.add(i + ",");
                } else {
                    int m = this.save(arr);
                    if (m == 1) {
                        ++s;
                    } else {
                        strF.add(i + ",");
                    }
                }
            }
        }

        successMsg.insert(0, "数据入库成功：" + s + " 条；数据已存在第：" + JSONArray.toJSONString(strR) + "行；数据错误第" + JSONArray.toJSONString(strE) + "行；数据入库失败：" + JSONArray.toJSONString(strF) + "行；");
        return AjaxResult.success(successMsg.toString(), StringUtils.EMPTY);

    }

    @RequiresPermissions({"basedata:eqpbook:add"})
    @Log(
            title = "基础数据-设备台账主",
            businessType = BizType.INSERT
    )
    public int save(BasedataEqpBook baseDataEqpbook) {

        try {
            int i = this.basedataEqpBookService.insertBasedataEqpBook(baseDataEqpbook);
            if (i > 0 && "1,2,310,13,14,20".contains(baseDataEqpbook.getType())) {
                this.basedataEqpBookService.setSendService(baseDataEqpbook.getType());
            }

            return i;
        } catch (Exception var4) {
            return -1;
        }
    }

    @RequiresPermissions({"basedata:eqpbook:list"})
    @GetMapping({"/getEqpBookListInfoForXml"})
    public String getEqpBookListInfo(BasedataEqpBook basedataEqpbook) {
        List<BasedataEqpBook> list = this.basedataEqpBookService.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);
        }

        return modelXml;
    }

    public static void main(String[] args) {
        BufferedReader bufferedReader = null;
        String string = "";
        String xml = "";

        try {
            for (bufferedReader = new BufferedReader(new FileReader("D:\\task.txt")); (string = bufferedReader.readLine()) != null; xml = xml + string) {
                ;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        JSONObject jsonObject = XmlToJsonUtil.xmlToJsonObject(xml);
        assert jsonObject != null;
        System.out.println(jsonObject.toJSONString());
        Object obj = jsonObject.get("Item");
        JSONArray jsonArray = (JSONArray) obj;
    }

    @GetMapping({"/getTeskMessageByEqpbookId"})
    public AjaxResult getMessageByEqpBookId() {
        BasedataEqpBook basedataEqpbook = new BasedataEqpBook();
        List<BasedataEqpBook> list = this.basedataEqpBookService.selectBasedataEqpBookList(basedataEqpbook);

        for (BasedataEqpBook basedataEqpBookList : list) {
            if (!StringUtils.isEmpty(String.valueOf(basedataEqpBookList.getEqpBookId()))) {
                AjaxResult ajaxResult = this.feignMsgClient.getMessageByEqpBookId(String.valueOf(basedataEqpBookList.getPatrolDeviceCode()));
                List patrolTaskList = (List) ajaxResult.get("data");
                basedataEqpBookList.setPatrolTaskList(patrolTaskList);
            }
        }

        return AjaxResult.success(list);
    }

    @GetMapping({"/getUavList"})
    public AjaxResult getUavList(BasedataEqpBook basedataEqpbook) {
        basedataEqpbook.setType("13");
        List<BasedataEqpBook> list = this.basedataEqpBookService.selectBasedataEqpBookList(basedataEqpbook);
        return AjaxResult.success(list);
    }

    @GetMapping({"/getAreaEqubookTreeSelect"})
    public AjaxResult getAreaEquBookTreeSelect(BaseDataArea area) {
        List<BasedataAreaEquTreeVo> treeVoList = this.basedataEqpBookService.getAreaEquTreeList(area);
        return AjaxResult.success(treeVoList);
    }

    @GetMapping({"/getAreaEqubookTreeSelectForFilter"})
    public AjaxResult getAreaEquBookTreeSelectForFilter(
            @RequestParam("patroldeviceName") String patrolDeviceName,
            @RequestParam("onlineStatus") String onlineStatus,
            @RequestParam("patroldeviceTypeFlag") String patrolDeviceTypeFlag) {
        BasedataEqpBookTreeQueryFilterVo queryFilterVo = new BasedataEqpBookTreeQueryFilterVo();
        queryFilterVo.setPatrolDeviceCode(patrolDeviceName);
        queryFilterVo.setOnlineStatus(onlineStatus);
        queryFilterVo.setPatrolDeviceTypeFlag(patrolDeviceTypeFlag);
        logger.info("[METADATA] filterVo: {}", queryFilterVo);
        List<BasedataAreaEquTreeVo> treeVoList = this.basedataEqpBookService.selectBasedataEqpbookOnlineList(queryFilterVo);
        return AjaxResult.success(treeVoList);
    }

//    @GetMapping({"/getAreaEqubookTreeSelectForFilter"})
//    public AjaxResult getAreaEquBookTreeSelectForFilter(BasedataEqpBookTreeQueryFilterVo queryFilterVo) {
//        logger.info("[METADATA] queryFilterVo: {}", queryFilterVo.toString());
//        List<BasedataAreaEquTreeVo> treeVoList = this.basedataEqpBookService.selectBasedataEqpbookOnlineList(queryFilterVo);
//        return AjaxResult.success(treeVoList);
//    }

    @GetMapping({"/checkPatrolDeviceIsExist/{patrolDeviceCode}"})
    public AjaxResult checkPatrolDeviceIsExist(@PathVariable("patrolDeviceCode") String patrolDeviceCode) {
        BasedataEqpBook basedataEqpbook = new BasedataEqpBook();
        basedataEqpbook.setMainSystemCode(patrolDeviceCode);
        List<BasedataEqpBook> equbookList = basedataEqpBookService.selectBasedataEqpBookList(basedataEqpbook);
        return !equbookList.isEmpty() ? AjaxResult.success("巡视设备鉴权成功", equbookList.get(0)) : AjaxResult.error("巡视设备鉴权失败");
    }

    @GetMapping({"/synPatrolEqp"})
    public AjaxResult synPatrolEqp() {
        int ret = this.basedataEqpBookService.synPatrolEqpFromGwbMedia();
        return ret == 0 ? AjaxResult.error("同步成功") : AjaxResult.success("同步成功");
    }

    @GetMapping({"/synPatrolEqpChannel"})
    public AjaxResult synPatrolEqpChannel() {
        int ret = this.basedataEqpBookService.synPatrolEqpChannelFromGwbMedia();
        return ret == 0 ? AjaxResult.error("同步成功") : AjaxResult.success("同步成功");
    }

    @PostMapping({"/uploadPicMap"})
    public AjaxResult uploadPicMap(@RequestPart("file") MultipartFile file, @RequestPart("patroldeviceCode") String patrolDeviceCode) throws Exception {
        InputStream in = file.getInputStream();
        String filename = file.getOriginalFilename();
        return this.basedataEqpBookService.uploadPicMap(in, filename, patrolDeviceCode);
    }

    @GetMapping({"/downloadPicMap"})
    public AjaxResult downloadPicMap(@RequestParam("patroldeviceCode") String patrolDeviceCode) throws IOException {
        BasedataEqpBook basedataEqpbook = this.basedataEqpBookService.selectBasedataEqpBookByPatrolDeviceCode(patrolDeviceCode);
        Map map = new HashMap<>();
        map.put("path", basedataEqpbook.getMapFilePath());
        return AjaxResult.success(map);
    }

    @GetMapping({"/setSendServiceForMap"})
    public String setSendServiceForMap() {
        BasedataEqpBook basedataEqpbook = new BasedataEqpBook();
        basedataEqpbook.setType("20");
        List<BasedataEqpBook> basedataEqpBookList = this.basedataEqpBookService.selectBasedataEqpBookList(basedataEqpbook);
        return basedataEqpBookList.get(0).getMapFilePath();
    }

    @PostMapping({"sync"})
    public Response syncEqpBookListAndChannel(@RequestBody JSONObject param) {
        String cameraName = param.getString("cameraName");
        List<String> channelNames = param.getJSONArray("params").toJavaList(String.class);
        SipbDeviceListView sipbDeviceListView = this.ivsFeign.channelList();
        String[] splits = new String[]{" ", "/"};
        String[] ivsNames = null;
        Iterator<CameraBriefInfo> iterator = sipbDeviceListView.getChannelList().iterator();

        String channelName;
        String name;
        while (iterator.hasNext()) {
            CameraBriefInfo cameraBriefInfo = iterator.next();
            channelName = cameraBriefInfo.getName();
            for (String split : splits) {
                name = split;
                ivsNames = channelName.split(name);
                if (ivsNames.length > 1) {
                    break;
                }
            }

            channelName = String.join(StringUtils.UNDERLINE, ivsNames);
            cameraBriefInfo.setName(channelName);
        }

        String patroldeviceCode = null;

        for (String s : channelNames) {
            channelName = s;

            for (CameraBriefInfo cameraBriefInfo : sipbDeviceListView.getChannelList()) {
                name = cameraBriefInfo.getName();
                if (name.equals(channelName)) {
                    patroldeviceCode = cameraBriefInfo.getCode();
                    break;
                }
            }
        }

        BasedataEqpBook basedataEqpbook = new BasedataEqpBook();
        basedataEqpbook.setPatrolDeviceCode(patroldeviceCode);
        basedataEqpbook.setPatrolDeviceName(cameraName);
        basedataEqpbook.setVideoNvrCode("c5486fffb1b64e53978bd6d82d96109f");
        basedataEqpbook.setAreaId(1L);
        basedataEqpbook.setType("10");
        basedataEqpbook.setUseMode("2");
        this.basedataEqpBookService.insertBasedataEqpBook(basedataEqpbook);
        for (String s : channelNames) {
            channelName = s;

            for (CameraBriefInfo cameraBriefInfo : sipbDeviceListView.getChannelList()) {
                name = cameraBriefInfo.getName();
                if (name.equals(channelName)) {
                    BasedataEqpBookChannel channel = new BasedataEqpBookChannel();
                    channel.setEqpBookId(basedataEqpbook.getEqpBookId());
                    channel.setPatrolDeviceCode(patroldeviceCode);
                    channel.setChannelCode(cameraBriefInfo.getCode());
                    channel.setChannelName(channelName);
                    channel.setOnlineState(cameraBriefInfo.getStatus());
                    channel.setChannelType("vl");

                    try {
                        this.basedataEqpBookChannelService.insertBasedataEqpBookChannel(channel);
                    } catch (Exception var16) {
                        ;
                    }
                    break;
                }
            }
        }

        return Response.ok();


    }

    @GetMapping({"/deviceNumList"})
    public AjaxResult deviceNumList() {
        List<Map<String, Integer>> deviceNums = this.basedataEqpBookService.deviceNumList();
        List<SysDictData> deviceTypes = DictUtils.getDictCache("device_type");
        List<Map<String, String>> deviceNumList = new ArrayList<>();

        for (int i = 0; i < deviceNums.size(); ++i) {
            if ("11".equals(((Map) deviceNums.get(i)).get("type")) || "12".equals(((Map) deviceNums.get(i)).get("type")) || "20".equals(((Map) deviceNums.get(i)).get("type"))) {
                deviceNums.remove(i);
            }
        }

        deviceTypes.forEach((item) -> {
            deviceNums.forEach((Map) -> {
                if (item.getDictValue().equals(Map.get("type"))) {
                    String typeValue = item.getDictValue();
                    Map<String, Integer> mapCount = this.basedataEqpBookService.deviceOnlineCountByType(typeValue);
                    Map<String, String> map = new HashMap();
                    map.put("type", item.getDictLabel());
                    map.put("onlineNum", String.valueOf(mapCount.get("onlineCount")));
                    map.put("num", String.valueOf(mapCount.get("tatolCount")));
                    deviceNumList.add(map);
                }

            });
        });
        return AjaxResult.success(deviceNumList);
    }

    @GetMapping({"/deviceOnlineCount"})
    public AjaxResult deviceOnlineCount() {
        Map<String, Integer> deviceOnlineMap = this.basedataEqpBookService.deviceOnlineCount();
        return AjaxResult.success(deviceOnlineMap);
    }

    @GetMapping({"/alarmList"})
    public AjaxResult alarmList() {
        List<String> deviceStatusList = this.basedataEqpBookService.deviceStatusList();
        List<String> alarmList = this.basedataEqpBookService.alarmList();
        List<String> abnormalList = this.basedataEqpBookService.abnormalList();
        List<AlarmListVo> alarms = new ArrayList<>();
        AlarmListVo alarmListVo = new AlarmListVo();
        alarmListVo.setAlarmType("设备状态");
        alarmListVo.setDay(deviceStatusList.get(0));
        alarmListVo.setMonth(deviceStatusList.get(1));
        alarmListVo.setHistory(deviceStatusList.get(2));
        alarmListVo.setCode("1");
        alarms.add(alarmListVo);
        AlarmListVo alarmListVo1 = new AlarmListVo();
        alarmListVo1.setAlarmType("巡视告警");
        alarmListVo1.setDay(alarmList.get(0));
        alarmListVo1.setMonth(alarmList.get(1));
        alarmListVo1.setHistory(alarmList.get(2));
        alarmListVo1.setCode("2");
        alarms.add(alarmListVo1);
        AlarmListVo alarmListVo2 = new AlarmListVo();
        alarmListVo2.setAlarmType("巡视异常");
        alarmListVo2.setDay(abnormalList.get(0));
        alarmListVo2.setMonth(abnormalList.get(1));
        alarmListVo2.setHistory(abnormalList.get(2));
        alarmListVo2.setCode("3");
        alarms.add(alarmListVo2);
        return AjaxResult.success(alarms);
    }

    @GetMapping({"/alarmList/status"})
    public TableDataInfo statusList(BasedataMontPatDevStaData basedataMontPatdevstadata) {
        this.startPage();
        List<BasedataMontPatDevStaData> deviceStatusList = this.basedataEqpBookService.deviceStatusListInfo(basedataMontPatdevstadata);
        return this.getDataTable(deviceStatusList);
    }

    @GetMapping({"/alarmList/alarm"})
    public TableDataInfo alarms(PatrolResult PatrolResult) {
        this.startPage();
        ResultAnalysis resultAnalysis = new ResultAnalysis();
        if (StringUtils.isNotEmpty(PatrolResult.getDefectType())) {
            resultAnalysis.setResultContent(PatrolResult.getDefectType());
        }

        if (StringUtils.isNotEmpty(PatrolResult.getBeginTime())) {
            resultAnalysis.setBeginTime(PatrolResult.getBeginTime());
        }

        if (StringUtils.isNotEmpty(PatrolResult.getEndTime())) {
            resultAnalysis.setEndTime(PatrolResult.getEndTime());
        }

        if (StringUtils.isNotEmpty(PatrolResult.getAreaId())) {
            resultAnalysis.setAreaId(PatrolResult.getAreaId());
        }

        if (StringUtils.isNotEmpty(PatrolResult.getMainDevId())) {
            resultAnalysis.setMainDevId(PatrolResult.getMainDevId());
        }

        if (StringUtils.isNotEmpty(PatrolResult.getAlarmType()) && PatrolResult.getAlarmType().equals("1")) {
            resultAnalysis.setResultType("0");
        }

        if (StringUtils.isNotEmpty(PatrolResult.getResStatus())) {
            resultAnalysis.setResStatus(PatrolResult.getResStatus());
        }

        List<PatrolResult> alarmList = this.basedataEqpBookService.alarmListInfo(resultAnalysis);
        if (!alarmList.isEmpty()) {
            for (PatrolResult brr : alarmList) {
                String pointId;
                if (StringUtils.isNotEmpty(brr.getComponentId()) && StringUtils.isEmpty(brr.getDeviceName())) {
                    pointId = this.recursionGetNameId(brr.getComponentId());
                    System.out.println(pointId);
                    if (StringUtils.isNotEmpty(pointId)) {
                        String[] ars = pointId.split(StringUtils.COMMA);
                        if (StringUtils.isNotEmpty(ars[0])) {
                            brr.setDeviceName(ars[0]);
                            brr.setMainDevId(ars[2]);
                        }

                        if (ars.length > 1 && StringUtils.isNotEmpty(ars[1])) {
                            brr.setMaterialId(ars[1]);
                        }
                    }
                }

                if (StringUtils.isNotEmpty(brr.getResStatus())) {
                    if (brr.getResStatus().equals("0")) {
                        Map<String, String> pointInfo = this.basedataEqpBookService.selectPointInfoById(brr.getDeviceId());
                        if (pointInfo != null) {
                            if (StringUtils.isNotEmpty(pointInfo.get("point_impt_level"))) {
                                if (pointInfo.get("point_impt_level").equals("Ⅰ")) {
                                    brr.setWarnlevel("紧急");
                                } else if (pointInfo.get("point_impt_level").equals("Ⅱ")) {
                                    brr.setWarnlevel("严重");
                                } else {
                                    brr.setWarnlevel("一般");
                                }
                            } else {
                                brr.setWarnlevel("一般");
                            }
                        } else {
                            brr.setWarnlevel("一般");
                        }
                    } else {
                        brr.setWarnlevel("正常");
                    }
                }

                List pointPrelist;
                if (StringUtils.isNotEmpty(brr.getResultContent())) {
                    JSONObject parseObject = JSONObject.parseObject(brr.getResultContent());
                    Object jsonArray = parseObject.get("resultList");
                    pointPrelist = JSONArray.parseArray(jsonArray + "", resultList.class);
                    if (!pointPrelist.isEmpty()) {
                        resultList resultList = (resultList) pointPrelist.get(0);
                        if (resultList.getResults() != null && !resultList.getResults().isEmpty()) {
                            List ss = resultList.getResults().stream().map(results::getType).collect(Collectors.toList());
                            List<String> aa = new ArrayList<>();
                            if (ss.size() > 1) {

                                for (Object s : ss) {
                                    String arr = (String) s;
                                    if (StringUtils.isNotEmpty(arr)) {
                                        aa.add(arr);
                                    }
                                }

                                brr.setDefectType(StringUtils.join(aa, StringUtils.COMMA));
                            } else {
                                brr.setDefectType(StringUtils.join(ss, StringUtils.COMMA));
                            }

                            List visibleA = resultList.getResults().stream().map(results::getResImageUrl).filter((getResImageUrl) -> !getResImageUrl.isEmpty()).collect(Collectors.toList());
                            brr.setVisible(visibleA);
                            List<String> infraRedA = new ArrayList<>();
                            List<String> audioA = new ArrayList<>();
                            List<String> videoA = new ArrayList<>();
                            List<String> photoA = new ArrayList<>();
                            brr.setInfraRed(infraRedA);
                            brr.setAudio(audioA);
                            brr.setVideo(videoA);
                            brr.setPhoto(photoA);
                        }
                    }
                }

                if (StringUtils.isNotEmpty(brr.getDeviceId())) {
                    pointId = brr.getDeviceId();
                    List<Map<String, Object>> pointlist = this.basedataEqpBookService.selectBasePointByPointId(pointId);
                    if (pointlist != null && !pointlist.isEmpty()) {
                        Map crr = pointlist.get(0);
                        if (crr != null) {
                            String patrolPointName = (String) crr.get("patrolpoint_name");
                            brr.setPatrolpointName(patrolPointName);
                        }
                    }

                    pointPrelist = this.basedataEqpBookService.selectBasePointPre(pointId);
                    if (pointPrelist != null && !pointPrelist.isEmpty()) {
                        Map drr = (Map) pointPrelist.get(0);
                        if (drr != null && drr.get("channel_code") != null) {
                            String channelCode = (String) drr.get("channel_code");
                            brr.setChannelCode(channelCode);
                        }
                    }
                }
            }
        }

        return this.getDataTable(alarmList);
    }

    public String recursionGetNameId(String devId) {
        String str = "";
        Map<String, Object> basedataDevice = this.basedataEqpBookService.selectDevInfoById(devId);
        if (null != basedataDevice && null != basedataDevice.get("parent_id")) {
            if (basedataDevice.get("power_main_equ_flag").equals("Yes")) {
                return basedataDevice.get("device_name") + "," + basedataDevice.get("phyasset_id") + "," + devId;
            }

            devId = basedataDevice.get("parent_id") + "";
            str = this.recursionGetNameId(devId);
        }

        return str;
    }

    @GetMapping({"/alarmList/abnormal"})
    public TableDataInfo abnormalList(PatrolResult patrolResult) {
        this.startPage();
        ResultAnalysis resultAnalysis = new ResultAnalysis();
        if (StringUtils.isNotEmpty(patrolResult.getDefectType())) {
            resultAnalysis.setResultContent(patrolResult.getDefectType());
        }

        if (StringUtils.isNotEmpty(patrolResult.getBeginTime())) {
            resultAnalysis.setBeginTime(patrolResult.getBeginTime());
        }

        if (StringUtils.isNotEmpty(patrolResult.getEndTime())) {
            resultAnalysis.setEndTime(patrolResult.getEndTime());
        }

        if (StringUtils.isNotEmpty(patrolResult.getAreaId())) {
            resultAnalysis.setAreaId(patrolResult.getAreaId());
        }

        if (StringUtils.isNotEmpty(patrolResult.getMainDevId())) {
            resultAnalysis.setMainDevId(patrolResult.getMainDevId());
        }

        if (StringUtils.isNotEmpty(patrolResult.getAlarmType()) && patrolResult.getAlarmType().equals("1")) {
            resultAnalysis.setResultType("0");
        }

        if (StringUtils.isNotEmpty(patrolResult.getResStatus())) {
            resultAnalysis.setResStatus(patrolResult.getResStatus());
        }

        if (StringUtils.isNotEmpty(patrolResult.getDeviceName())) {
            resultAnalysis.setDeviceName(patrolResult.getDeviceName());
        }

        List<PatrolResult> abnormalList = this.basedataEqpBookService.abnormalListInfo(resultAnalysis);
        if (!abnormalList.isEmpty()) {

            for (PatrolResult brr : abnormalList) {
                String pointId;
                if (StringUtils.isNotEmpty(brr.getComponentId()) && StringUtils.isEmpty(brr.getDeviceName())) {
                    pointId = this.recursionGetNameId(brr.getComponentId());
                    System.out.println(pointId);
                    if (StringUtils.isNotEmpty(pointId)) {
                        String[] ars = pointId.split(StringUtils.COMMA);
                        if (StringUtils.isNotEmpty(ars[0])) {
                            brr.setDeviceName(ars[0]);
                            brr.setMainDevId(ars[2]);
                        }

                        if (ars.length > 1 && StringUtils.isNotEmpty(ars[1])) {
                            brr.setMaterialId(ars[1]);
                        }
                    }
                }

                if (StringUtils.isNotEmpty(brr.getResStatus())) {
                    if (brr.getResStatus().equals("0")) {
                        Map<String, String> pointInfo = this.basedataEqpBookService.selectPointInfoById(brr.getDeviceId());
                        if (pointInfo != null) {
                            if (StringUtils.isNotEmpty(pointInfo.get("point_impt_level"))) {
                                if (pointInfo.get("point_impt_level").equals("Ⅰ")) {
                                    brr.setWarnlevel("紧急");
                                } else if (pointInfo.get("point_impt_level").equals("Ⅱ")) {
                                    brr.setWarnlevel("严重");
                                } else {
                                    brr.setWarnlevel("一般");
                                }
                            } else {
                                brr.setWarnlevel("一般");
                            }
                        } else {
                            brr.setWarnlevel("一般");
                        }
                    } else {
                        brr.setWarnlevel("正常");
                    }
                }

                List pointPrelist;
                if (StringUtils.isNotEmpty(brr.getResultContent())) {
                    JSONObject parseObject = JSONObject.parseObject(brr.getResultContent());
                    Object jsonArray = parseObject.get("resultList");
                    pointPrelist = JSONArray.parseArray(jsonArray + "", resultList.class);
                    if (!pointPrelist.isEmpty()) {
                        resultList resultList = (resultList) pointPrelist.get(0);
                        if (resultList.getResults() != null && !resultList.getResults().isEmpty()) {
                            List ss = resultList.getResults().stream().map(results::getType).collect(Collectors.toList());
                            List<String> aa = new ArrayList<>();
                            if (ss.size() > 1) {

                                for (Object s : ss) {
                                    String arr = (String) s;
                                    if (StringUtils.isNotEmpty(arr)) {
                                        aa.add(arr);
                                    }
                                }

                                brr.setDefectType(StringUtils.join(aa, StringUtils.COMMA));
                            } else {
                                brr.setDefectType(StringUtils.join(ss, StringUtils.COMMA));
                            }

                            List visibleA = resultList.getResults().stream().map(results::getResImageUrl).filter((getResImageUrl) -> !getResImageUrl.isEmpty()).collect(Collectors.toList());
                            brr.setVisible(visibleA);
                            List<String> infraRedA = new ArrayList<>();
                            List<String> audioA = new ArrayList<>();
                            List<String> videoA = new ArrayList<>();
                            List<String> photoA = new ArrayList<>();
                            brr.setInfraRed(infraRedA);
                            brr.setAudio(audioA);
                            brr.setVideo(videoA);
                            brr.setPhoto(photoA);
                        }
                    }
                }

                if (StringUtils.isNotEmpty(brr.getDeviceId())) {
                    pointId = brr.getDeviceId();
                    List<Map<String, Object>> pointlist = this.basedataEqpBookService.selectBasePointByPointId(pointId);
                    if (pointlist != null && !pointlist.isEmpty()) {
                        Map crr = pointlist.get(0);
                        if (crr != null) {
                            String patrolPointName = (String) crr.get("patrol_point_name");
                            brr.setPatrolpointName(patrolPointName);
                        }
                    }

                    pointPrelist = this.basedataEqpBookService.selectBasePointPre(pointId);
                    if (pointPrelist != null && !pointPrelist.isEmpty()) {
                        Map drr = (Map) pointPrelist.get(0);
                        if (drr != null && drr.get("channel_code") != null) {
                            String channel_code = (String) drr.get("channel_code");
                            brr.setChannelCode(channel_code);
                        }
                    }
                }
            }
        }

        return this.getDataTable(abnormalList);
    }

    @GetMapping({"/subtypeData"})
    public TableDataInfo subtypeData(BasedataPatrolPoint basedataPatrolpoint) {
//        List<String> errors = new ArrayList<>();
//        this.startPage();
//        List<BasedataPatrolPoint> subtypeList = this.basedataEqpBookService.getSubtypeData(basedataPatrolpoint);
        List<BasedataPatrolPoint> stdList = new ArrayList<>();
        // 前端传的算法编码
        List<Long> algTypeCodeList = basedataPatrolpoint.getAlgTypeCodeList();
        // 获取算法分类字典（dictCode=字典编码，dictValue=逗号分隔的子类型ID）
        List<SysDictData> algCategoryDict = getSysDictDataList("threshold_alg_type");
        // 构建字典编码（所有可配阈值的算法） -> 子类型ID集合的映射 (例如，"886" -> {"1", "2"})
        Map<Long, Set<String>> labelToSubtypeIds = algCategoryDict.stream()
                .collect(Collectors.toMap(
                        SysDictData::getDictCode,
                        item -> Arrays.stream(item.getDictValue().split(","))
                                .filter(StringUtils::isNotBlank)
                                .collect(Collectors.toSet())
                ));
        logger.info("[META] labelToSubtypeIds : {}", labelToSubtypeIds);
        if (algTypeCodeList == null || algTypeCodeList.size() == 0) {
            algTypeCodeList = new ArrayList<>(labelToSubtypeIds.keySet());
        }

        // 合并所有允许的子类型ID
        Set<String> allowedSubtypeIds = algTypeCodeList.stream()
                .filter(Objects::nonNull)
                .flatMap(dictCode -> labelToSubtypeIds.getOrDefault(dictCode, Collections.emptySet()).stream())
                .collect(Collectors.toSet());

//        subtypeList = subtypeList.stream().filter(point -> {
//            String algSubtypeIds = point.getAlgSubtypeIds();
//            if (StringUtils.isBlank(algSubtypeIds)) {
//                return false;
//            }
//            return Arrays.stream(algSubtypeIds.split(",")).anyMatch(allowedSubtypeIds::contains);
//        }).collect(Collectors.toList());
        this.startPage();
        basedataPatrolpoint.setAlgSubtypeIds(StringUtils.join(allowedSubtypeIds, ","));
        List<BasedataPatrolPoint> subtypeList = this.basedataEqpBookService.getSubtypeData(basedataPatrolpoint);
        // 查询区域信息
        for (BasedataPatrolPoint bp : subtypeList) {
            List<BasedataThresholdModification> subTypeDOList = new ArrayList<>();
            List<JSONObject> jsonArray = JSONArray.parseArray(bp.getAlarmThreshold(), JSONObject.class);
            String[] subs;
            if (bp.getAlgSubtypeIds().contains(StringUtils.COMMA)) {
                subs = bp.getAlgSubtypeIds().split(StringUtils.COMMA);
            } else {
                subs = new String[]{bp.getAlgSubtypeIds()};
            }
            Long relationAreaId = bp.getRelationAreaId();
            if (relationAreaId != null) {
                BaseDataArea areaQuery = new BaseDataArea();
                areaQuery.setAreaIdS(String.valueOf(relationAreaId));
                AjaxResult ajaxResult = baseDataAreaController.selectAreaNameSForTaskByAreaIdSRelation(areaQuery);
                if (ajaxResult.get("code").equals(200)) {
                    bp.setAreaName(ajaxResult.get("data").toString());
                }
            }
            if(jsonArray == null || subs.length != jsonArray.size()) {
                logger.info("问题巡检点位id,{}", bp.getPatrolPointId());
//                errors.add(bp.getPatrolPointId()+"");
                continue;
            }
            List<String> algSubtypeNames = new ArrayList<>();
            for (int k = 0; k < subs.length; ++k) {
                BasedataAlgSubtype basedataAlgSubtype = this.basedataAlgSubtypeService.selectBasedataAlgSubtypeByAlgSubtypeId(Long.valueOf(subs[k]));
                if (null != basedataAlgSubtype) {
                    BasedataThresholdModification std = new BasedataThresholdModification();
                    std.setPatrolPointId(bp.getPatrolPointId());
                    std.setAlgSubtypeId(subs[k]);
                    std.setAlgSubtypeName(basedataAlgSubtype.getAlgSubtypeName());
                    std.setUpperValue(jsonArray.get(k).getString("upperValue"));
                    std.setLowerValue(jsonArray.get(k).getString("lowerValue"));
                    subTypeDOList.add(std);
                    algSubtypeNames.add(basedataAlgSubtype.getAlgSubtypeName());
                }
            }
            bp.setAlgSubtypeName(StringUtils.join(algSubtypeNames, ","));
            if (!subTypeDOList.isEmpty()) {
                bp.setSubTypeDOList(subTypeDOList);
                stdList.add(bp);
            }
        }

        return this.getDataTable1(stdList, subtypeList);
    }

    protected TableDataInfo getDataTable1(List<?> list, List<?> list2) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(200);
        rspData.setRows(list);
        rspData.setMsg("查询成功");
        rspData.setTotal((new PageInfo(list2)).getTotal());
        return rspData;
    }

    private List<SysDictData> getSysDictDataList(String dictType) {
        return basedataPatrolpointMapper.selectDictDataByType(dictType);
    }

    @PostMapping({"/subtypeUpdate"})
    public AjaxResult subtypeUpdate(@RequestBody List<JSONObject> jsonObjects) {
        for (JSONObject jsonObject : jsonObjects) {
            BasedataPatrolPoint bp = jsonObject.toJavaObject(BasedataPatrolPoint.class);
            List<JSONObject> jsonArray = JSONArray.parseArray(bp.getAlarmThreshold(), JSONObject.class);

            for (int i = 0; i < bp.getSubTypeDOList().size(); ++i) {
                jsonArray.get(i).put("upperValue", bp.getSubTypeDOList().get(i).getUpperValue());
                jsonArray.get(i).put("lowerValue", bp.getSubTypeDOList().get(i).getLowerValue());
                this.basedataThresholdModificationService.insertBasedataThresholdModification(bp.getSubTypeDOList().get(i));
            }

            bp.setAlarmThreshold(jsonArray.toString().replaceFirst(",$", StringUtils.EMPTY));
            int i = this.basedataPatrolPointService.updateBasedataPatrolPoint(bp);
        }
        return this.toAjax(true);
    }

    @GetMapping({"/subtypeUpdateRecord"})
    public TableDataInfo subtypeUpdateRecord(BasedataThresholdModification btd) {
        this.startPage();
        logger.info("查询巡检点位报警阈值修改记录,{}",btd.getAlgSubtypeId());
        if (btd.getAlgSubtypeId() != null) {
            String[] subs;
            if (btd.getAlgSubtypeId().contains(StringUtils.COMMA)) {
                subs = btd.getAlgSubtypeId().split(StringUtils.COMMA);
            } else {
                subs = new String[]{btd.getAlgSubtypeId()};
            }
            btd.setAlgSubtypeIds(Arrays.asList(subs));
        }
        List<BasedataThresholdModification> list = this.basedataThresholdModificationService.selectBasedataThresholdModificationList(btd);
        return this.getDataTable(list);
    }

//    @GetMapping({"/queryEqpbookCode"})
    @PostMapping({"/queryEqpbookCode"})
    public String queryEqpBookCode(@RequestBody String patrolDeviceCode) {
        return this.basedataEqpBookService.queryEqpBookCode(patrolDeviceCode);
    }
}
