package com.yeejoin.equipmanage.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.dto.OrgMenuDto;
import com.yeejoin.amos.boot.biz.common.excel.ExcelUtil;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.component.robot.AmosRequestContext;
import com.yeejoin.amos.feign.morphic.model.ResourceDTO;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.equipmanage.common.entity.*;
import com.yeejoin.equipmanage.common.entity.dto.EquipTypeAmountPageDTO;
import com.yeejoin.equipmanage.common.entity.dto.RequestBaseDto;
import com.yeejoin.equipmanage.common.entity.vo.*;
import com.yeejoin.equipmanage.common.enums.TrueOrFalseEnum;
import com.yeejoin.equipmanage.common.utils.CommonResponseUtil;
import com.yeejoin.equipmanage.common.utils.StringUtil;
import com.yeejoin.equipmanage.common.vo.*;
import com.yeejoin.equipmanage.fegin.JcsFeign;
import com.yeejoin.equipmanage.mapper.EquipmentSpecificIndexMapper;
import com.yeejoin.equipmanage.mapper.FireFightingSystemMapper;
import com.yeejoin.equipmanage.remote.RemoteSecurityService;
import com.yeejoin.equipmanage.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.foundation.utils.Bean;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author zjw
 * @date 2020-12-16
 */
@RestController
@Api(tags = "消防系统Api")
@RequestMapping(value = "/fire-fighting-system", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Slf4j
public class FireFightingSystemController extends AbstractBaseController {

    @Autowired
    IManufacturerInfoService iManufacturerInfoService;
    @Autowired
    IFireFightingSystemService fireFightingSystemService;
    @Autowired
    IUploadFileService uploadFileService;
    @Lazy
    @Autowired
    IEquipmentSpecificSerivce equipmentSpecificSerivce;
    @Autowired
    IEquipmentIndexService equipmentIndexService;
    @Autowired
    IEquipmentCategoryService equipmentCategoryService;
    @Autowired
    RemoteSecurityService remoteSecurityService;
    @Autowired
    IBuilldService buildService;
    @Autowired
    IEquipmentService iEquipmentService;
    @Autowired
    FireFightingSystemMapper fireFightingSystemMapper;
    @Autowired
    EquipmentSpecificIndexMapper equipmentSpecificIndexMapper;
    @Autowired
    ICarService carService;
    /**
     * 通过装备定义id查找性能指标
     *
     * @return
     */

    @Autowired
    IEquipmentSpecificIndexSerivce equipmentSpecificIndexSerivce;
    @Autowired
    private AmosRequestContext amosAuth;
    @Autowired
    private RedisUtils redisUtils;
    @Value("${equipment.hierarchy}")
    private String hierarchy;
    @Value("${firefightingsystem.detail.url}")
    private String ffsDetailUrl;
    @Value("${firefightingsystem.equip.alarms.url}")
    private String ffsEquipAlarmsUrl;
    @Autowired
    private JcsFeign jcsFeign;
    @Value("${auth-key-fire-system-build:fire_system_build_info}")
    private String systemBuildAuthKey;

    @RequestMapping(value = "/getEquiplistBySystemId", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation("根据系统id查询设备列表")
    public List<EquiplistSpecificBySystemVO> getEquiplistBySystemId(Long systemId) {
        return fireFightingSystemService.getEquiplistBySystemId(systemId);
    }

    @RequestMapping(value = "/getEquiplistBySystemIdPage", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation("根据系统id查询设备列表")
    public IPage<EquiplistSpecificBySystemVO> getEquiplistBySystemIdPage(Long systemId, int size, int current) {
        return fireFightingSystemService.getEquiplistBySystemIdPage(systemId, size, current);
    }

    @RequestMapping(value = "/getEquipcountBySystemId", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation("根据系统id查询分组设备数量")
    public List<EquipCountBySystemVO> getEquipCountBySystemId(
            @RequestParam(value = "systemId", required = false) Long systemId,
            @RequestParam(value = "bizOrgCode", required = false) String bizOrgCode
    ) {
        if (org.apache.commons.lang3.StringUtils.isBlank(bizOrgCode)) {
            ReginParams reginParams = getSelectedOrgInfo();
            bizOrgCode = !ValidationUtil.isEmpty(reginParams.getPersonIdentity()) && org.apache.commons.lang3.StringUtils.isNotEmpty(reginParams.getPersonIdentity().getBizOrgCode()) ? reginParams.getPersonIdentity().getBizOrgCode() : null;
        }
        return fireFightingSystemService.getEquipCountBySystemId(systemId, bizOrgCode);
    }

    @RequestMapping(value = "/getEquipCountPageBySystemId", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation("根据系统id查询分组设备数量")
    public Page<EquipCountBySystemVO> getEquipCountPageBySystemId(
            @RequestParam(value = "systemId", required = false) Long systemId,
            @RequestParam(value = "pageNumber", required = false) Integer pageNumber,
            @RequestParam(value = "pageSize", required = false) Integer pageSize,
            @RequestParam(value = "bizOrgCode", required = false) String bizOrgCode
    ) {
        if (org.apache.commons.lang3.StringUtils.isBlank(bizOrgCode)) {
            ReginParams reginParams = getSelectedOrgInfo();
            bizOrgCode = !ValidationUtil.isEmpty(reginParams.getPersonIdentity()) && org.apache.commons.lang3.StringUtils.isNotEmpty(reginParams.getPersonIdentity().getBizOrgCode()) ? reginParams.getPersonIdentity().getBizOrgCode() : null;
        }
        return fireFightingSystemService.getEquipCountPageBySystemId(systemId, pageNumber, pageSize, bizOrgCode);
    }

    @RequestMapping(value = "/getEquipCountPage", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation("消防器材查询设备数量列表")
    public Page<EquipCountBySystemVO> getEquipCountPage(
            @RequestParam(value = "systemId", required = false) Long systemId,
            @RequestParam(value = "pageNumber", required = false) Integer pageNumber,
            @RequestParam(value = "pageSize", required = false) Integer pageSize,
            @RequestParam(value = "bizOrgCode", required = false) String bizOrgCode) {
        if (org.apache.commons.lang3.StringUtils.isBlank(bizOrgCode)) {
            ReginParams reginParams = getSelectedOrgInfo();
            bizOrgCode = !ValidationUtil.isEmpty(reginParams.getPersonIdentity()) && org.apache.commons.lang3.StringUtils.isNotEmpty(reginParams.getPersonIdentity().getBizOrgCode()) ? reginParams.getPersonIdentity().getBizOrgCode() : null;
        }
        return fireFightingSystemService.getEquipCountPage(systemId, pageNumber, pageSize, bizOrgCode);
    }

    @RequestMapping(value = "/getFireEquipConfigInfo", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation("根据字典查询相关信息")
    public List<EquipCountBySystemVO> getFireEquipConfigInfo(@RequestParam(value = "bizOrgCode", required = false) String bizOrgCode) {
        if (org.apache.commons.lang3.StringUtils.isBlank(bizOrgCode)) {
            ReginParams reginParams = getSelectedOrgInfo();
            bizOrgCode = !ValidationUtil.isEmpty(reginParams.getPersonIdentity()) && org.apache.commons.lang3.StringUtils.isNotEmpty(reginParams.getPersonIdentity().getBizOrgCode()) ? reginParams.getPersonIdentity().getBizOrgCode() : null;
        }
        return fireFightingSystemService.getFireEquipConfigInfo(bizOrgCode);
    }

    @RequestMapping(value = "/getOneById", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation("通过id查询消防系统信息")
    public FireFightingSystemEntity getOneById(Long id) {
        return fireFightingSystemService.getOneById(id);
    }

    @RequestMapping(value = "/{systemCode}/detail", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation("通过id查询消防系统信息")
    public FireFightingSystemEntity getDetailByCode(@PathVariable String systemCode) {
        return fireFightingSystemService.getDetailByCode(systemCode);
    }

    //查询系统下设备状态
    @RequestMapping(value = "/alarmSystem/info", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation("通过systemCode查询消防系统信息")
    public List<Map<String, Object>> getEquip(@RequestParam(required = false) String bizOrgCode,
                                              @RequestParam(required = false) String systemCode) {
        if (StringUtils.isEmpty(bizOrgCode)) {
            ReginParams reginParams = getSelectedOrgInfo();
            ReginParams.PersonIdentity personIdentity = reginParams.getPersonIdentity();
            if (!ValidationUtil.isEmpty(personIdentity)) {
                bizOrgCode = personIdentity.getBizOrgCode();
                if (StringUtils.isEmpty(bizOrgCode)) {
                    return Lists.newArrayList();
                }
            }
        }
        return fireFightingSystemService.getEquip(bizOrgCode, systemCode);
    }

    //查询系统下设备状态
    @RequestMapping(value = "/getFireSystemEquipStatusList", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation("通过systemCode、设备分类编码字符串查询消防系统信息")
    public List<Map<String, Object>> getFireSystemEquipStatusList(@RequestParam(required = false) String bizOrgCode,
                                                                  @RequestParam(required = false) String systemCode,
                                                                  @RequestParam(required = false) String categoryCodes) {
        if (StringUtils.isEmpty(bizOrgCode)) {
            ReginParams reginParams = getSelectedOrgInfo();
            ReginParams.PersonIdentity personIdentity = reginParams.getPersonIdentity();
            if (!ValidationUtil.isEmpty(personIdentity)) {
                bizOrgCode = personIdentity.getBizOrgCode();
                if (StringUtils.isEmpty(bizOrgCode)) {
                    return Lists.newArrayList();
                }
            }
        }
        return fireFightingSystemService.getFireSystemEquipStatusList(bizOrgCode, systemCode, categoryCodes);
    }

    /**
     * 生产厂商列表（不分页）
     *
     * @return
     */
    @GetMapping(value = "/manufacturerList")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "生产厂商列表(不分页)")
    public List<ManufacturerInfo> getEquiplistBySystemId() {
        return iManufacturerInfoService.list();
    }

    /**
     * 装备卡片删除
     *
     * @return
     */
    @DeleteMapping(value = "/delEquipmentSpecific")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "DELETE", value = "装备卡片删除")
    public Boolean delEquipmentSpecific(Long id) {
        EquipmentSpecific equipmentSpecific = equipmentSpecificSerivce.getById(id);
        Boolean result = equipmentSpecificSerivce.delEquipmentSpecific(id);
        // 同步刷新，不在异步，原因速度3秒左右
        this.refreshCount(equipmentSpecific.getBizOrgCode());
        return result;
    }

    /**
     * 装备卡片批量删除
     *
     * @return
     */
    @DeleteMapping(value = "/delEquipmentSpecificByIds")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "DELETE", value = "装备卡片批量删除")
    @Transactional
    public ResponseModel delEquipmentSpecific(@RequestBody List<Long> specificIds) {
        if (CollectionUtils.isEmpty(specificIds)) {
            throw new BadRequest("所选装备不能为空");
        }
        Set<String> bizOrgCodes = new HashSet<>();
        specificIds.forEach(specId -> {
            EquipmentSpecific equipmentSpecific = equipmentSpecificSerivce.getById(specId);
            equipmentSpecificSerivce.delEquipmentSpecificByIdNew(equipmentSpecific);
            bizOrgCodes.add(equipmentSpecific.getBizOrgCode());
        });
        bizOrgCodes.forEach(this::refreshCount);
        return CommonResponseUtil.success(Boolean.TRUE);
    }

    private void refreshCount(String bizOrgCode) {
        equipmentSpecificSerivce.refreshStaData();
        try {
            fireFightingSystemService.refreshEquipmentTypeAndCount(bizOrgCode);
        } catch (Exception e) {
            log.error("刷新装备分类树缓存失败" + e.getMessage());
        }
    }

    @GetMapping(value = "/getPrefList")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "通过装备定义id查找性能指标")
    public Map<String, Object> getPrefList(Long equipmentId, Long specificId) {
        HashMap<String, List> map = new HashMap<>();
        List<EquProperty> properALlList = new ArrayList<>();
        List<String> list = equipmentIndexService.getGruopName(equipmentId);
        list.forEach(x -> {
            QueryWrapper<EquipmentIndex> wrapper = new QueryWrapper<>();
            wrapper.eq("equipment_id", equipmentId);
            wrapper.eq("group_name", x);
            wrapper.orderByAsc("sort_num");
            List<EquProperty> properList = new ArrayList<>();
            equipmentIndexService.list(wrapper).forEach(y -> {
                EquProperty equProperty = new EquProperty();
                equProperty.setEquipmentIndexId(y.getId());
                equProperty.setIsIot(y.getIsIot());
                equProperty.setPerfQuotaName(y.getPerfQuotaName());
                equProperty.setEquipmentIndexName(y.getPerfQuotaName());
                equProperty.setGroupName(y.getGroupName());
                equProperty.setValue(y.getPerfValue());
                equProperty.setUnitName(y.getUnitName());
                equProperty.setEquipmentIndexKey(y.getPerfQuotaDefinitionId());
                properList.add(equProperty);
            });
            properALlList.addAll(properList);
            map.put(x, properList);
        });
        QueryWrapper<EquipmentIndex> wrappernull = new QueryWrapper<>();
        wrappernull.isNull("group_name").or().eq("group_name", " ");
        wrappernull.eq("equipment_id", equipmentId);
        wrappernull.orderByAsc("sort_num");
        List<EquProperty> properList = new ArrayList<>();
        equipmentIndexService.list(wrappernull).forEach(y -> {
            EquProperty equProperty = new EquProperty();
            equProperty.setEquipmentIndexId(y.getId());
            equProperty.setPerfQuotaName(y.getPerfQuotaName());
            equProperty.setEquipmentIndexName(y.getPerfQuotaName());
            equProperty.setIsIot(y.getIsIot());
            equProperty.setGroupName(y.getGroupName());
            equProperty.setValue(y.getPerfValue());
            equProperty.setUnitName(y.getUnitName());
            equProperty.setEquipmentIndexKey(y.getPerfQuotaDefinitionId());
            properList.add(equProperty);
        });
        properALlList.addAll(properList);
        properALlList.forEach(e -> {
            List<EquipmentIndexVO> equipmentIndexList = equipmentSpecificIndexMapper.getEquipIndexByIndexId(e.getEquipmentIndexId(), specificId);
            if (equipmentIndexList.size() > 0) {
                if (StringUtil.isNotEmpty(equipmentIndexList.get(0).getValue())) {
                    e.setValue(equipmentIndexList.get(0).getValue());
                } else {
                    e.setValue("");
                }
            } else {
                e.setValue("");
            }
        });
        //判断map中是否有key为’其他‘的数据，提取单独处理
        List<EquProperty> otherProperList = map.get("其他");
        if (otherProperList != null && otherProperList.size() > 0) {
            otherProperList.addAll(properList);
            map.put("其他", otherProperList);
        } else {
            map.put("其他", properList);
        }
        Equipment byId = iEquipmentService.getById(equipmentId);

        Map<String, Object> re = new HashMap<>();
        re.put("res", map);
        re.put("pre", byId.getPrefQuota());
        return re;
    }

    /**
     * 九大类下装备，通过code截取
     *
     * @return
     */
    @PostMapping(value = "/getEquipTypeAmount")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "九大类下装备，通过code截取", notes = "九大类下装备信息列表")
    public IPage<EquipTypeImgAmountVO> getEquipTypeAmount(@RequestBody EquipTypeAmountPageDTO equipTypeAmountPage) {
        String[] result = hierarchy.split(",");
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < result.length; i++) {
            map.put(i, Integer.valueOf(result[i]));
        }
        if (StringUtil.isNotEmpty(equipTypeAmountPage.getEquipmentClassificationCode())) {
            QueryWrapper<EquipmentCategory> equipmentCategoryQueryWrapper = new QueryWrapper<>();
            equipmentCategoryQueryWrapper.eq("code", equipTypeAmountPage.getEquipmentClassificationCode());
            equipmentCategoryQueryWrapper.eq("industry_code", equipTypeAmountPage.getIndustryCode());
            EquipmentCategory equipmentCategory = equipmentCategoryService.getOne(equipmentCategoryQueryWrapper);
            if (equipmentCategory == null) {
                throw new RuntimeException("装备定义code有误");
            }
            int inhierarchy = 1;
            for (int i = 0; i < result.length + 1; i++) {
                //进来先判断是否默认就是空，如果为空第一层
                if (equipmentCategory.getParentId() == null) {
                    //判断是否是最下面的子节点
                    if (i >= 4) {
                        inhierarchy = 8;
                    } else {
                        inhierarchy = map.get(i);
                    }
                    break;
                } else {
                    //查找到循环几次为空
                    equipmentCategory = equipmentCategoryService.getById(equipmentCategory.getParentId());
                }
            }

            return fireFightingSystemService.getColaCategoryAmountList(inhierarchy, equipTypeAmountPage.getEquipmentClassificationCode().substring(0, inhierarchy), equipTypeAmountPage);
        } else {
            return fireFightingSystemService.getColaCategoryAmountList(0, null, equipTypeAmountPage);
        }

    }


    @GetMapping(value = "/getEquipTypeAmountCar")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "九大类下装备，通过code截取", notes = "九大类下装备信息列表")
    public IPage<EquipTypeImgAmountVO> getEquipTypeAmountCarByGet(EquipTypeAmountPageDTO equipTypeAmountPage) {
        String[] result = hierarchy.split(",");
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < result.length; i++) {
            map.put(i, Integer.valueOf(result[i]));
        }
        if (equipTypeAmountPage.getCurrent() != null && equipTypeAmountPage.getSize() != null) {
            equipTypeAmountPage.setPage(new Page<>(equipTypeAmountPage.getCurrent(), equipTypeAmountPage.getSize()));
        }
        if (StringUtil.isNotEmpty(equipTypeAmountPage.getEquipmentClassificationCode())) {
            QueryWrapper<EquipmentCategory> equipmentCategoryQueryWrapper = new QueryWrapper<>();
            equipmentCategoryQueryWrapper.eq("code", equipTypeAmountPage.getEquipmentClassificationCode());
            equipmentCategoryQueryWrapper.eq("industry_code", equipTypeAmountPage.getIndustryCode());
            EquipmentCategory equipmentCategory = equipmentCategoryService.getOne(equipmentCategoryQueryWrapper);
            if (equipmentCategory == null) {
                throw new RuntimeException("装备定义code有误");
            }
            int inhierarchy = 1;
            for (int i = 0; i < result.length + 1; i++) {
                //进来先判断是否默认就是空，如果为空第一层
                if (equipmentCategory.getParentId() == null) {
                    //判断是否是最下面的子节点
                    if (i >= 4) {
                        inhierarchy = 8;
                    } else {
                        inhierarchy = map.get(i);
                    }
                    break;
                } else {
                    //查找到循环几次为空
                    equipmentCategory = equipmentCategoryService.getById(equipmentCategory.getParentId());
                }
            }
            return fireFightingSystemService.getColaCategoryAmountCarList(inhierarchy, equipTypeAmountPage.getEquipmentClassificationCode().substring(0, inhierarchy), equipTypeAmountPage);
        } else {
            return fireFightingSystemService.getColaCategoryAmountCarList(0, null, equipTypeAmountPage);
        }

    }


    @PostMapping(value = "/iot/getEquipTypeAmount")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "九大类下装备，通过code截取", notes = "九大类下装备信息列表")
    public IPage<EquipTypeImgAmountVO> iotgetEquipTypeAmount(@RequestBody EquipTypeAmountPageDTO equipTypeAmountPage) {
        equipTypeAmountPage.setIsIot("1");
        String[] result = hierarchy.split(",");
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < result.length; i++) {
            map.put(i, Integer.valueOf(result[i]));
        }
        if (StringUtil.isNotEmpty(equipTypeAmountPage.getEquipmentClassificationCode())) {
            QueryWrapper<EquipmentCategory> equipmentCategoryQueryWrapper = new QueryWrapper<>();
            equipmentCategoryQueryWrapper.eq("code", equipTypeAmountPage.getEquipmentClassificationCode());
            equipmentCategoryQueryWrapper.eq("industry_code", equipTypeAmountPage.getIndustryCode());
            EquipmentCategory equipmentCategory = equipmentCategoryService.getOne(equipmentCategoryQueryWrapper);
            if (equipmentCategory == null) {
                throw new RuntimeException("装备定义code有误");
            }
            int inhierarchy = 1;
            for (int i = 0; i < result.length + 1; i++) {
                //进来先判断是否默认就是空，如果为空第一层
                if (equipmentCategory.getParentId() == null) {
                    //判断是否是最下面的子节点
                    if (i >= 4) {
                        inhierarchy = 8;
                    } else {
                        inhierarchy = map.get(i);
                    }
                    break;
                } else {
                    //查找到循环几次为空
                    equipmentCategory = equipmentCategoryService.getById(equipmentCategory.getParentId());
                }
            }

            return fireFightingSystemService.getColaCategoryAmountListIot(inhierarchy, equipTypeAmountPage.getEquipmentClassificationCode().substring(0, inhierarchy), equipTypeAmountPage);
        } else {
            return fireFightingSystemService.getColaCategoryAmountListIot(0, null, equipTypeAmountPage);
        }

    }


    @PostMapping(value = "/getEquipTypeAmountCar")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "九大类下装备，通过code截取", notes = "九大类下装备信息列表")
    public IPage<EquipTypeImgAmountVO> getEquipTypeAmountCar(@RequestBody EquipTypeAmountPageDTO equipTypeAmountPage) {
        String[] result = hierarchy.split(",");
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < result.length; i++) {
            map.put(i, Integer.valueOf(result[i]));
        }
        if (StringUtil.isNotEmpty(equipTypeAmountPage.getEquipmentClassificationCode())) {
            QueryWrapper<EquipmentCategory> equipmentCategoryQueryWrapper = new QueryWrapper<>();
            equipmentCategoryQueryWrapper.eq("code", equipTypeAmountPage.getEquipmentClassificationCode());
            equipmentCategoryQueryWrapper.eq("industry_code", equipTypeAmountPage.getIndustryCode());
            EquipmentCategory equipmentCategory = equipmentCategoryService.getOne(equipmentCategoryQueryWrapper);
            if (equipmentCategory == null) {
                throw new RuntimeException("装备定义code有误");
            }
            int inhierarchy = 1;
            for (int i = 0; i < result.length + 1; i++) {
                //进来先判断是否默认就是空，如果为空第一层
                if (equipmentCategory.getParentId() == null) {
                    //判断是否是最下面的子节点
                    if (i >= 4) {
                        inhierarchy = 8;
                    } else {
                        inhierarchy = map.get(i);
                    }
                    break;
                } else {
                    //查找到循环几次为空
                    equipmentCategory = equipmentCategoryService.getById(equipmentCategory.getParentId());
                }
            }

            return fireFightingSystemService.getColaCategoryAmountCarList(inhierarchy, equipTypeAmountPage.getEquipmentClassificationCode().substring(0, inhierarchy), equipTypeAmountPage);
        } else {
            return fireFightingSystemService.getColaCategoryAmountCarList(0, null, equipTypeAmountPage);
        }

    }

    @GetMapping(value = "/getEquipTypeAmountCarJxiop")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "九大类下装备，通过code截取", notes = "九大类下装备信息列表")
    public IPage<EquipTypeImgAmountVO> getEquipTypeAmountCarJxiopGet(EquipTypeAmountPageDTO equipTypeAmountPage) {
    	  String[] result = hierarchy.split(",");
          Map<Integer, Integer> map = new HashMap<>();
          for (int i = 0; i < result.length; i++) {
              map.put(i, Integer.valueOf(result[i]));
          }
          if (equipTypeAmountPage.getCurrent() != null && equipTypeAmountPage.getSize() != null) {
              equipTypeAmountPage.setPage(new Page<>(equipTypeAmountPage.getCurrent(), equipTypeAmountPage.getSize()));
          }
          log.info("orgCode当前值为start：：" + equipTypeAmountPage.getBizOrgCode());
          ReginParams reginParams = JSONObject.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
          if (ObjectUtils.isEmpty(equipTypeAmountPage.getBizOrgCode())) {
              if (!ObjectUtils.isEmpty(reginParams.getCompany().getOrgCode())) {
                  equipTypeAmountPage.setBizOrgCode(reginParams.getCompany().getOrgCode());
              } else {
                  equipTypeAmountPage.setBizOrgCode("-1");
              }
          } else {
              if (!ObjectUtils.isEmpty(reginParams.getCompany().getOrgCode()) && (equipTypeAmountPage.getBizOrgCode().startsWith(reginParams.getCompany().getOrgCode()))) {

              } else {
                  equipTypeAmountPage.setBizOrgCode(reginParams.getCompany().getOrgCode());
              }
          }
          log.info("orgCode当前值为：：" + equipTypeAmountPage.getBizOrgCode());
          if (StringUtil.isNotEmpty(equipTypeAmountPage.getEquipmentClassificationCode())) {
              QueryWrapper<EquipmentCategory> equipmentCategoryQueryWrapper = new QueryWrapper<>();
              equipmentCategoryQueryWrapper.eq("code", equipTypeAmountPage.getEquipmentClassificationCode());
              equipmentCategoryQueryWrapper.eq("industry_code", equipTypeAmountPage.getIndustryCode());
              EquipmentCategory equipmentCategory = equipmentCategoryService.getOne(equipmentCategoryQueryWrapper);
              if (equipmentCategory == null) {
                  throw new RuntimeException("装备定义code有误");
              }
              int inhierarchy = 1;
              for (int i = 0; i < result.length + 1; i++) {
                  //进来先判断是否默认就是空，如果为空第一层
                  if (equipmentCategory.getParentId() == null) {
                      //判断是否是最下面的子节点
                      if (i >= 4) {
                          inhierarchy = 8;
                      } else {
                          inhierarchy = map.get(i);
                      }
                      break;
                  } else {
                      //查找到循环几次为空
                      equipmentCategory = equipmentCategoryService.getById(equipmentCategory.getParentId());
                  }
              }
              return fireFightingSystemService.getColaCategoryAmountCarListJxiop(inhierarchy, equipTypeAmountPage.getEquipmentClassificationCode().substring(0, inhierarchy), equipTypeAmountPage);
          } else {
              return fireFightingSystemService.getColaCategoryAmountCarListJxiop(0, null, equipTypeAmountPage);
          }
    }


    @PostMapping(value = "/getEquipTypeAmountCarJxiop")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "九大类下装备，通过code截取-江西电建", notes = "九大类下装备信息列表-江西电建")
    public IPage<EquipTypeImgAmountVO> getEquipTypeAmountCarJxiop(@RequestBody EquipTypeAmountPageDTO equipTypeAmountPage) {
        String[] result = hierarchy.split(",");
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < result.length; i++) {
            map.put(i, Integer.valueOf(result[i]));
        }
        log.info("orgCode当前值为start：：" + equipTypeAmountPage.getBizOrgCode());
        ReginParams reginParams = JSONObject.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        if (ObjectUtils.isEmpty(equipTypeAmountPage.getBizOrgCode())) {
            if (!ObjectUtils.isEmpty(reginParams.getCompany().getOrgCode())) {
                equipTypeAmountPage.setBizOrgCode(reginParams.getCompany().getOrgCode());
            } else {
                equipTypeAmountPage.setBizOrgCode("-1");
            }
        } else {
            if (!ObjectUtils.isEmpty(reginParams.getCompany().getOrgCode()) && (equipTypeAmountPage.getBizOrgCode().startsWith(reginParams.getCompany().getOrgCode()))) {

            } else {
                equipTypeAmountPage.setBizOrgCode(reginParams.getCompany().getOrgCode());
            }
        }
        log.info("orgCode当前值为：：" + equipTypeAmountPage.getBizOrgCode());
        if (StringUtil.isNotEmpty(equipTypeAmountPage.getEquipmentClassificationCode())) {
            QueryWrapper<EquipmentCategory> equipmentCategoryQueryWrapper = new QueryWrapper<>();
            equipmentCategoryQueryWrapper.eq("code", equipTypeAmountPage.getEquipmentClassificationCode());
            equipmentCategoryQueryWrapper.eq("industry_code", equipTypeAmountPage.getIndustryCode());
            EquipmentCategory equipmentCategory = equipmentCategoryService.getOne(equipmentCategoryQueryWrapper);
            if (equipmentCategory == null) {
                throw new RuntimeException("装备定义code有误");
            }
            int inhierarchy = 1;
            for (int i = 0; i < result.length + 1; i++) {
                //进来先判断是否默认就是空，如果为空第一层
                if (equipmentCategory.getParentId() == null) {
                    //判断是否是最下面的子节点
                    if (i >= 4) {
                        inhierarchy = 8;
                    } else {
                        inhierarchy = map.get(i);
                    }
                    break;
                } else {
                    //查找到循环几次为空
                    equipmentCategory = equipmentCategoryService.getById(equipmentCategory.getParentId());
                }
            }

            return fireFightingSystemService.getColaCategoryAmountCarListJxiop(inhierarchy, equipTypeAmountPage.getEquipmentClassificationCode().substring(0, inhierarchy), equipTypeAmountPage);
        } else {
            return fireFightingSystemService.getColaCategoryAmountCarListJxiop(0, null, equipTypeAmountPage);
        }
    }

    @PostMapping(value = "/getEquipTypeAmountEqu")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "九大类下装备，通过code截取", notes = "九大类下装备信息列表")
    public IPage<EquipTypeImgAmountVO> getEquipTypeAmountEqu(@RequestBody EquipTypeAmountPageDTO equipTypeAmountPage) {
        String[] result = hierarchy.split(",");
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < result.length; i++) {
            map.put(i, Integer.valueOf(result[i]));
        }
        if (StringUtil.isNotEmpty(equipTypeAmountPage.getEquipmentClassificationCode())) {
            QueryWrapper<EquipmentCategory> equipmentCategoryQueryWrapper = new QueryWrapper<>();
            equipmentCategoryQueryWrapper.eq("code", equipTypeAmountPage.getEquipmentClassificationCode());
            equipmentCategoryQueryWrapper.eq("industry_code", equipTypeAmountPage.getIndustryCode());
            List<EquipmentCategory> equipmentCategoryList = equipmentCategoryService.list(equipmentCategoryQueryWrapper);
            if (CollectionUtils.isEmpty(equipmentCategoryList)) {
                throw new RuntimeException("装备定义code有误");
            }
            EquipmentCategory equipmentCategory = equipmentCategoryList.get(0);
            int inhierarchy = 1;
            int flag = 0;
            for (int i = 0; i < result.length + 1; i++) {
                //进来先判断是否默认就是空，如果为空第一层
                if (equipmentCategory.getParentId() == null) {
                    //判断是否是最下面的子节点
                    if (i >= 4) {
                        inhierarchy = 8;
                    } else {
                        inhierarchy = map.get(i);
                    }
                    flag = i;
                    break;
                } else {
                    //查找到循环几次为空
                    equipmentCategory = equipmentCategoryService.getById(equipmentCategory.getParentId());
                }
            }
            if (flag == 0) {
                String classificationCode = equipTypeAmountPage.getEquipmentClassificationCode().replaceAll("0+$", "").trim();
                return fireFightingSystemService.getColaCategoryAmountEquList(inhierarchy, classificationCode, equipTypeAmountPage);
            } else {
                String classificationCode = equipTypeAmountPage.getEquipmentClassificationCode().replaceAll("0+$", "").trim();
                return fireFightingSystemService.getColaCategoryAmountEquList(inhierarchy, classificationCode.length() % 2 == 0 ? classificationCode : classificationCode + "0", equipTypeAmountPage);
            }
//            return fireFightingSystemService.getColaCategoryAmountEquList(inhierarchy, equipTypeAmountPage.getEquipmentClassificationCode(), equipTypeAmountPage);

//            String classificationCode = equipTypeAmountPage.getEquipmentClassificationCode().replaceAll("0+$", "");
//            return fireFightingSystemService.getColaCategoryAmountEquList(inhierarchy, classificationCode.length() % 2 == 0 ? classificationCode : classificationCode + "0", equipTypeAmountPage);
        } else {
            if (null != equipTypeAmountPage.getIsDefect() && 1 == equipTypeAmountPage.getIsDefect()) {
                ReginParams reginParams = getSelectedOrgInfo();
                if (StringUtils.isEmpty(equipTypeAmountPage.getBizOrgCode())) {
                    equipTypeAmountPage.setBizOrgCode(reginParams.getPersonIdentity().getBizOrgCode());
                }
            }
            return fireFightingSystemService.getColaCategoryAmountEquList(0, null, equipTypeAmountPage);
        }

    }

    @PostMapping(value = "/getMonitoringUnitList")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "查询监测部件列表", notes = "查询监测部件列表")
    public IPage<EquipTypeImgAmountVO> getMonitoringUnitList(
            @RequestBody EquipTypeAmountPageDTO equipTypeAmountPage,
            @RequestParam(value = "useSource", required = false) String useSource
    ) {
        return equipmentSpecificSerivce.getMonitoringUnitList(equipTypeAmountPage, useSource);
    }

    @GetMapping(value = "/getMonitoringCount")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "查询监测部件列表", notes = "查询监测部件列表")
    public List<Map<String, Object>> getMonitoringCount(String bizOrgCode) {
        return equipmentSpecificSerivce.getMonitoringCount(bizOrgCode);
    }


    /**
     * 添加系统
     *
     * @return
     */
    @PostMapping(value = "/save")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "添加", notes = "添加")
    public ResponseModel save(@RequestBody FireFightingSystemVo vo) {
        String orgCode = getOrgCode();
        vo.setOrgCode(orgCode);
        try {
            String code = vo.getCode();
            // BUG 2940  litw 2021年9月18日
            QueryWrapper<FireFightingSystemEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("code", code);
            FireFightingSystemEntity entity = fireFightingSystemService.getOne(queryWrapper);
            if (null != entity) {
                throw new BadRequest("系统编号已存在，请重新填写");
            }
            return CommonResponseUtil.success(fireFightingSystemService.save(vo));
        } catch (Exception e) {
            return CommonResponseUtil.failure(e.getMessage());
        }
    }

    @GetMapping(value = "/listAndCount")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "查询消防设施管理信息", notes = "查询消防设施管理信息")
    public Map<String, Object> queryEquipmentInfoAndCount(
            @RequestParam(value = "equipmentName", required = false) String equipmentName,
            @RequestParam(value = "equipmentCode", required = false) String equipmentCode,
            @RequestParam(value = "construction", required = false) String construction,
            @RequestParam(value = "maintenance", required = false) String maintenance,
            @RequestParam(value = "bizOrgCode", required = false) String bizOrgCode,
            @RequestParam(value = "systemStatus", required = false) String systemStatus,
            @RequestParam(value = "formGroupId", required = false) String formGroupId,
            @RequestParam(value = "controBoxBuildId", required = false) String controBoxBuildId,
            @RequestParam(value = "current") int current,
            @RequestParam(value = "size") int pageSize,
            @RequestParam(value = "nameOrCode", required = false) String nameOrCode, @RequestParam(value = "companyId", required = false) String companyId,
            @ApiParam(value = "缺陷管理新增页面用，其余地方可忽略 1-是缺陷管理 0-不是") @RequestParam(required = false) Integer isDefect,
            @ApiParam(value = "接口调用源，web端调用/卡片调用") @RequestParam(value = "invokeSource", required = false) String invokeSource
    ) {
        if (null != isDefect && 1 == isDefect) {
            ReginParams reginParams = getSelectedOrgInfo();
            if (org.apache.commons.lang3.ObjectUtils.isEmpty(reginParams) || org.apache.commons.lang3.ObjectUtils.isEmpty(reginParams.getPersonIdentity()) || StringUtils.isEmpty(reginParams.getPersonIdentity().getBizOrgCode())) {
                return new HashMap<>();
            }
            if (StringUtils.isEmpty(bizOrgCode)) {
                bizOrgCode = reginParams.getPersonIdentity().getBizOrgCode();
            }
        }
        if (current > 0) {
            current = (current - 1) * pageSize;
        }
        if (StringUtil.isNotEmpty(companyId)) {
            String token = getToken();
            String appKey = getAppKey();
            String product = getProduct();
            ResponseModel<JSONObject> obj = jcsFeign.getUnitById(appKey, product, token, companyId);
            JSONObject result = obj.getResult();
            if (result.containsKey("bizOrgCode")) {
                companyId = result.get("bizOrgCode").toString();
            }

        }
        return fireFightingSystemService.queryEquipmenInfoAndCount(equipmentName, equipmentCode, construction, maintenance, bizOrgCode, formGroupId, current, pageSize, controBoxBuildId, companyId, nameOrCode, systemStatus, invokeSource);
    }

    /**
     * 修改系统
     *
     * @return
     */
    @PutMapping(value = "/updateById")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "PUT", value = "修改", notes = "修改")
    public ResponseModel updateByIdJournal(@RequestBody FireFightingSystemVo vo) {
        try {
            return CommonResponseUtil.success(fireFightingSystemService.update(vo));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return CommonResponseUtil.failure(e.getMessage());
        }
    }


    @PostMapping(value = "/scene-create")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "创建画布")
    public FireFightingSystemVo createMorphic(@RequestBody FireFightingSystemVo model) {
        ReginParams selectedOrgInfo = getSelectedOrgInfo();
        String orgCode = selectedOrgInfo.getCompany().getOrgCode();
        model.setOrgCode(orgCode);
        return fireFightingSystemService.createMorphic(model);
    }


    @PutMapping(value = "/scene-save")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "更新保存画布")
    public ResourceDTO updateMorphic(@RequestBody ResourceDTO resourceDTO) {
        return fireFightingSystemService.updateMorphic(resourceDTO);
    }


    /**
     * 删除画布
     *
     * @return
     */
    @DeleteMapping(value = "/isDeleteCanvas")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "DELETE", value = "删除画布")
    public Boolean isDeleteCanvas(@RequestBody Long id) {
        return fireFightingSystemService.isDeleteCanvas(id);
    }


    /**
     * 获取点位图，区域树数据
     */
    //重复接口及地址 影响项目启动 若后续有问题需要使用 更改接口地址
    /*@TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "获取点位图，区域树数据", notes = "消防系统点位图使用")
    @GetMapping(value = "/point/tree")
    public List<PointTreeVo> getPointTree(@RequestParam(required = false) String systemId) {
        return fireFightingSystemService.getPointTree(systemId, getOrgCode());
    }
*/

    /**
     * 设备指标数据查询
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/getSpeIndex", method = RequestMethod.GET)
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "根据id查询", notes = "根据id查询")
    public List<SpeIndexVo> selectById(Long id) {
        return fireFightingSystemService.getSpeIndex(id, 1);
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "消防系统列表查询（不分页）", notes = "下拉使用")
    @GetMapping(value = "/list")
    public List<FireFightingSystemEntity> listAll(@RequestParam(value = "bizOrgCode", required = false) String bizOrgCode) {
        String name = "";
        if (StringUtils.isEmpty(bizOrgCode)) {
            ReginParams reginParams = getSelectedOrgInfo();
            ReginParams.PersonIdentity personIdentity = reginParams.getPersonIdentity();
            if (!ValidationUtil.isEmpty(personIdentity)) {
                bizOrgCode = personIdentity.getBizOrgCode();
            }
        } else {
            name = "其他系统";
        }
        if (StringUtil.isNotEmpty(bizOrgCode)) {
            QueryWrapper<FireFightingSystemEntity> qw = new QueryWrapper<>();
            qw.lambda().likeRight(FireFightingSystemEntity::getBizOrgCode, bizOrgCode).ne(FireFightingSystemEntity::getName, name);
            return fireFightingSystemService.list(qw);
        }
        return new ArrayList<>();
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "消防系统列表查询（不分页）", notes = "下拉使用")
    @GetMapping(value = "/systems")
    public List<FireFightingSystemEntity> systems(@RequestParam(value = "bizOrgCode", required = false) String bizOrgCode) {
        if (StringUtils.isEmpty(bizOrgCode)) {
            ReginParams reginParams = getSelectedOrgInfo();
            ReginParams.PersonIdentity personIdentity = reginParams.getPersonIdentity();
            if (!ValidationUtil.isEmpty(personIdentity)) {
                bizOrgCode = personIdentity.getBizOrgCode();
            }
        }
        Wrapper<FireFightingSystemEntity> wrapper = Wrappers.<FireFightingSystemEntity>lambdaQuery()
                .likeRight(FireFightingSystemEntity::getBizOrgCode, bizOrgCode)
                .isNotNull(FireFightingSystemEntity::getName)
                .isNotNull(FireFightingSystemEntity::getSystemType);
        return fireFightingSystemService.list(wrapper);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "消防系统树和消防建筑树", notes = "树菜单")
    @GetMapping(value = "/getBuildingTreeAndSystemTree")
    public Map<String, List> getBuildingTreeAndSystemTree(RequestBaseDto dto) {
        Map<String, List> map = new HashMap<>();
        List<BuildingTreeVo> buildingTrees = buildService.getBuildingTreeByBizOrgCode(dto.getBizOrgCode());
        LambdaQueryWrapper<FireFightingSystemEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByAsc(FireFightingSystemEntity::getRecDate);
        lambdaQueryWrapper.likeRight(StringUtil.isNotEmpty(dto.getBizOrgCode()), FireFightingSystemEntity::getBizOrgCode, dto.getBizOrgCode());
        List<FireFightingSystemEntity> systemTree = fireFightingSystemService.list(lambdaQueryWrapper);
        systemTree.forEach(action -> {
            action.setDetailListPaneApi(ffsEquipAlarmsUrl);
            action.setDetailPaneApi(ffsDetailUrl);
        });
        map.put("buildingTree", buildingTrees.get(0).getChildren());
        map.put("systemTree", systemTree);
        return map;
    }

    /**
     * 消防系统公司树
     *
     * @param
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/companyTreeBySystem")
    @ApiOperation(httpMethod = "GET", value = "消防系统公司树", notes = "消防系统公司树")
    public ResponseModel<List<OrgMenuDto>> companyTreeByUserAndType() {
        return ResponseHelper.buildResponse(jcsFeign.getCompanyDeptTreeWithAuth(systemBuildAuthKey, "COMPANY").getResult());
    }


    /**
     * 装备卡片删除
     *
     * @return
     */
    @DeleteMapping(value = "/deleteSystem")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "DELETE", value = "装备卡片删除")
    public Boolean deleteSystem(@RequestBody Long id) {
        return fireFightingSystemService.deleteSystem(id);
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "按照组态格式获取设备详情", notes = "按照组态格式获取设备详情")
    @GetMapping(value = "/getSystemById")
    public Map<String, Object> getSystemById(Long id) {
        String bizOrgCode = "";
        ReginParams reginParams = getSelectedOrgInfo();
        ReginParams.PersonIdentity personIdentity = reginParams.getPersonIdentity();
        if (!ValidationUtil.isEmpty(personIdentity)) {
           bizOrgCode = personIdentity.getBizOrgCode();
        }
        FireFightingSystemEntity fireFightingSystem = fireFightingSystemService.getById(id);
        List<AlarmDataVO> list1 = fireFightingSystemService.getSystemById(id, bizOrgCode);
        Map<String, Object> res = new LinkedHashMap<>();
        Boolean status = Boolean.TRUE;
        List<Object> ite = new ArrayList<>();
        Map<String, String> map1 = new HashMap<>();
        if (fireFightingSystem != null) {
            list1.add(new AlarmDataVO("责任人", fireFightingSystem.getChargePersonName(), false));
            FireFightingSystemVo fireFightingSystemVo = fireFightingSystemMapper.getFightingSysInfo(fireFightingSystem.getCode(), fireFightingSystem.getId());
            map1.put("value", "异常".equals(fireFightingSystemVo.getStatus()) ? "false" : "true");
        } else {
            list1.add(new AlarmDataVO("责任人", ":", false));
            map1.put("value", status.toString());
        }
        map1.put("key", "系统状态");
        map1.put("highLight", "true");
        ite.addAll(list1);
        ite.add(map1);
        Map<String, String> map2 = new HashMap<>();
        map2.put("key", "系统运行状态");
        map2.put("value", "1".equals(fireFightingSystem!=null?fireFightingSystem.getSystemRunState():null) ? "运行" : "停止");
        map2.put("highLight", "true");
        res.put("items", ite);
        res.put("title", "基本信息");
        ite.add(map2);
        if(fireFightingSystem!=null){
            fireFightingSystem.setSystemRunState("1".equals(fireFightingSystem.getSystemRunState()) ? "运行" : "停止");
        }
        Map<String, Object> fireSystem = Bean.BeantoMap(fireFightingSystem);
        fireSystem.put("detailId", fireFightingSystem.getId());
        Map<String, Object> state = new HashMap<>();
        state.put("detail", fireSystem);
        state.put("pageType", "look");
        state.put("sysDesc", fireFightingSystem!=null?fireFightingSystem.getSystemDescribe():null);
        res.put("state", state);
        return res;
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "按照组态格式获取系统报警，或者建筑报警列表", notes = "按照组态格式获取系统报警，或者建筑报警列表")
    @GetMapping(value = "/getEquipmentAlarmBySystemIdOrSourceIdVO/{Systemtype}/{id}")
    public IPage<EquipmentAlarmBySystemIdOrSourceIdVO> getEquipmentAlarmBySystemIdOrSourceIdVO(Integer pageSize, Integer current, Integer confirmType, String createDate, String type, @PathVariable String Systemtype, @PathVariable Long id, String equipmentId) {
        Page<EquipmentAlarmBySystemIdOrSourceIdVO> page = new Page();
        page.setCurrent(current);
        page.setSize(pageSize);
        if (("building").equals(Systemtype)) {
            return fireFightingSystemService.getEquipmentAlarmBySystemIdOrSourceIdVO(page, id, null, confirmType, createDate, type, equipmentId);
        } else if ("system".equals(Systemtype)) {
            return fireFightingSystemService.getEquipmentAlarmBySystemIdOrSourceIdVO(page, null, id, confirmType, createDate, type, equipmentId);
        } else {
            return page;
        }
    }

    /**
     * 可乐根据左侧行业树过滤
     *
     * @return
     */
    @PostMapping(value = "/cola/getEquipTypeAmount")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "过滤行业分类下设备列表", notes = "行业树信息列表")
    public IPage<EquipTypeImgAmountVO> getEquipTypeAmounts(@RequestBody EquipTypeAmountPageDTO equipTypeAmountPage) {

        String[] result = hierarchy.split(",");
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < result.length; i++) {
            map.put(i, Integer.valueOf(result[i]));
        }
        if (StringUtil.isNotEmpty(equipTypeAmountPage.getEquipmentClassificationCode())) {
            QueryWrapper<EquipmentCategory> equipmentCategoryQueryWrapper = new QueryWrapper<>();
            equipmentCategoryQueryWrapper.eq("code", equipTypeAmountPage.getEquipmentClassificationCode());
            equipmentCategoryQueryWrapper.eq("industry_code", equipTypeAmountPage.getIndustryCode());
            EquipmentCategory equipmentCategory = equipmentCategoryService.getOne(equipmentCategoryQueryWrapper);
            if (equipmentCategory == null) {
                throw new RuntimeException("装备定义code有误");
            }
            int inhierarchy = 1;
            for (int i = 0; i < result.length; i++) {
                //进来先判断是否默认就是空，如果为空第一层
                if (equipmentCategory.getParentId() == null) {
                    inhierarchy = map.get(i);
                    break;
                } else {
                    equipmentCategory = equipmentCategoryService.getById(equipmentCategory.getParentId());
                }
            }
            return fireFightingSystemService.getColaCategoryAmountList(inhierarchy, equipTypeAmountPage.getEquipmentClassificationCode().substring(0, inhierarchy), equipTypeAmountPage);
        } else {
            return fireFightingSystemService.getColaCategoryAmountList(0, null, equipTypeAmountPage);
        }
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation("查询消防系统在装备定义的分类")
    @GetMapping("/system-category")
    public List<EquipmentManageVo> getSystemCategory() {
        return fireFightingSystemService.getSystemCategory();
    }

    /**
     * 获取公司部门系统树
     *
     * @return list
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "根据登陆人获取公司部门系统树", notes = "根据登陆人获取公司部门系统树")
    @GetMapping(value = "/companySystemTreeByUser")
    public List<FireFightingSystemTreeVo> getSystemTree() {
        ReginParams reginParams = getSelectedOrgInfo();
        ReginParams.PersonIdentity personIdentity = reginParams.getPersonIdentity();
        String bizOrgCode = personIdentity.getBizOrgCode();
        return fireFightingSystemService.getSystemTreeByOrgCode(bizOrgCode);
    }

    /**
     * 获取人员部门树7
     *
     * @return list
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "根据登陆人获取公司部门树", notes = "根据登陆人获取公司部门树")
    @GetMapping(value = "/companyTreeByUserAndType")
    public List<OrgMenuDto> companyTreeByUserAndType(@RequestParam(required = false) String type) {
        return fireFightingSystemService.companyTreeByUserAndType(type);
    }

    /**
     * 获取系统分类树
     *
     * @return list
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "获取系统分类树", notes = "获取系统分类树")
    @GetMapping(value = "/systemTypeTree")
    public List<FireFightingSystemTypeTreeVo> systemTypeTree(@RequestParam(required = false) String bizOrgCode) {
        return fireFightingSystemService.systemTypeTree(bizOrgCode);
    }

    /**
     * 根据bizOrgCode获取系统列表不分页
     *
     * @return list
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "获取系统分类树", notes = "获取系统分类树")
    @GetMapping(value = "/systemListByBziOrgCode")
    public List<FireFightingSystemEntity> systemListByBziOrgCode(@RequestParam(required = false) String bizOrgCode) {
        return fireFightingSystemService.systemListByBziOrgCode(bizOrgCode);
    }


    /**
     * 获取点位图，区域树数据
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @ApiOperation(value = "获取点位图，区域树数据", notes = "消防系统点位图使用")
    @GetMapping(value = "/point/tree")
    public List<PointTreeVo> getPointTree(@RequestParam(required = false) String systemId,
                                          @RequestParam(required = false) String bizOrgCode,
                                          @RequestParam(required = false) String type) {
        RequestContext.setAppKey(amosAuth.getAppKey());
        RequestContext.setProduct(amosAuth.getProduct());
        RequestContext.setToken(amosAuth.getToken());
        return fireFightingSystemService.getPointTree(systemId, bizOrgCode, type);
    }

    @RequestMapping(value = "/{systemCode}/system/detail", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @ApiOperation("通过系统code查询消防系统及部件信息")
    public Map<String, Object> getSystemDetailByCode(@PathVariable String systemCode) {
        return fireFightingSystemService.getSystemDetailByCode(systemCode);
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @ApiOperation(httpMethod = "GET", value = "获取系统分类树", notes = "获取系统分类树")
    @GetMapping(value = "/systemAndEquipmentTreeByBziOrgCode")
    public List<OrgMenuDto> systemAndEquipmentTreeByBziOrgCode() {
        RequestContext.setAppKey(amosAuth.getAppKey());
        RequestContext.setProduct(amosAuth.getProduct());
        RequestContext.setToken(amosAuth.getToken());
        return fireFightingSystemService.systemAndEquipmentTreeByBziOrgCode();
    }

    /**
     * 获取装备类型和统计值
     *
     * @throws Exception
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "获取装备类型和统计值", notes = "获取装备类型和统计值")
    @GetMapping(value = "/getEquipmentTypeAndCount/tree")
    public Object getEquipmentTypeAndCount(@RequestParam(required = false) String bizOrgCode) throws Exception {
        return fireFightingSystemService.getEquipmentTypeAndCount(bizOrgCode);
    }

    /**
     * 获取车辆类型和统计值
     *
     * @throws Exception
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "获取车辆类型和统计值", notes = "获取车辆类型和统计值")
    @GetMapping(value = "/getCarTypeAndCount/tree")
    public Object getCarTypeAndCount(@RequestParam(required = false) String bizOrgCode) throws Exception {
        return fireFightingSystemService.getCarTypeAndCount(bizOrgCode);
    }

    /**
     * 获取物联设备类型和统计值
     *
     * @throws Exception
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "获取物联设备类型和统计值", notes = "获取物联设备类型和统计值")
    @GetMapping(value = "iot/getEquipmentTypeAndCount/tree")
    public Object iotgetEquipmentTypeAndCount(@RequestParam(required = false) String bizOrgCode) throws Exception {
        return fireFightingSystemService.iotgetEquipmentTypeAndCount(bizOrgCode);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "装备信息导出", notes = "装备信息导出")
    @PostMapping(value = "/downParameter")
    public void export(HttpServletResponse response, @RequestBody EquipTypeAmountPageDTO dto) {
        List<EquipmentExportVO> list = fireFightingSystemMapper.exportEquipmentList(dto);
        if (!CollectionUtils.isEmpty(list)) {
            for (EquipmentExportVO vo : list) {
                if (!ObjectUtils.isEmpty(vo.getProductionDate())) {
                    vo.setProductionDate(vo.getProductionDate().substring(0, 10));
                }
                if (!ObjectUtils.isEmpty(vo.getOperationTime())) {
                    vo.setOperationTime(vo.getOperationTime().substring(0, 10));
                }
            }
        }
        ExcelUtil.createTemplate(response, "装备信息", "装备信息", list, EquipmentExportVO.class, null, false);
    }

    /**
     * 获取消防系统状态信息
     *
     * @throws Exception
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "获取消防系统状态信息", notes = "获取消防系统状态信息")
    @GetMapping(value = "/state/info")
    public Object getSystemInfoList() throws Exception {
        return fireFightingSystemService.getSystemInfoList();
    }

    /**
     * 获取消防系统告警状态信息
     *
     * @throws Exception
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "获取消防系统告警状态信息", notes = "获取消防系统告警状态信息")
    @GetMapping(value = "/alarm/num")
    public Object getSystemAlarmInfoList(@RequestParam(required = false) String startDate, @RequestParam(required = false) String endDate) throws Exception {
        return fireFightingSystemService.getSystemAlarmInfoList(startDate, endDate);
    }

    /**
     * 重置画布数据
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "重置画布数据", notes = "重置画布数据")
    @GetMapping(value = "/reset/morphic")
    public void resetMorphic() {
        fireFightingSystemService.resetMorphic();
    }


}
