package com.yeejoin.equipmanage.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.yeejoin.equipmanage.dto.EquipmentcountDto;
import com.yeejoin.equipmanage.fegin.JcsFeign;
import io.swagger.annotations.ApiParam;
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.util.StringUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.foundation.utils.Bean;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseModel;
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.extension.plugins.pagination.Page;
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.feign.morphic.model.ResourceDTO;
import com.yeejoin.equipmanage.common.entity.EquProperty;
import com.yeejoin.equipmanage.common.entity.Equipment;
import com.yeejoin.equipmanage.common.entity.EquipmentCategory;
import com.yeejoin.equipmanage.common.entity.EquipmentIndex;
import com.yeejoin.equipmanage.common.entity.EquipmentSpecific;
import com.yeejoin.equipmanage.common.entity.FireFightingSystemEntity;
import com.yeejoin.equipmanage.common.entity.ManufacturerInfo;
import com.yeejoin.equipmanage.common.entity.dto.EquipTypeAmountPageDTO;
import com.yeejoin.equipmanage.common.entity.dto.RequestBaseDto;
import com.yeejoin.equipmanage.common.entity.vo.EquipCountBySystemVO;
import com.yeejoin.equipmanage.common.entity.vo.EquipTypeImgAmountVO;
import com.yeejoin.equipmanage.common.entity.vo.EquiplistSpecificBySystemVO;
import com.yeejoin.equipmanage.common.entity.vo.EquipmentAlarmBySystemIdOrSourceIdVO;
import com.yeejoin.equipmanage.common.entity.vo.EquipmentExportVO;
import com.yeejoin.equipmanage.common.entity.vo.EquipmentIndexVO;
import com.yeejoin.equipmanage.common.entity.vo.PointTreeVo;
import com.yeejoin.equipmanage.common.utils.CommonResponseUtil;
import com.yeejoin.equipmanage.common.utils.StringUtil;
import com.yeejoin.equipmanage.common.vo.AlarmDataVO;
import com.yeejoin.equipmanage.common.vo.BuildingTreeVo;
import com.yeejoin.equipmanage.common.vo.EquipmentManageVo;
import com.yeejoin.equipmanage.common.vo.FireFightingSystemTreeVo;
import com.yeejoin.equipmanage.common.vo.FireFightingSystemTypeTreeVo;
import com.yeejoin.equipmanage.common.vo.FireFightingSystemVo;
import com.yeejoin.equipmanage.common.vo.SpeIndexVo;
import com.yeejoin.equipmanage.mapper.EquipmentSpecificIndexMapper;
import com.yeejoin.equipmanage.mapper.FireFightingSystemMapper;
import com.yeejoin.equipmanage.remote.RemoteSecurityService;
import com.yeejoin.equipmanage.service.IBuilldService;
import com.yeejoin.equipmanage.service.ICarService;
import com.yeejoin.equipmanage.service.IEquipmentCategoryService;
import com.yeejoin.equipmanage.service.IEquipmentIndexService;
import com.yeejoin.equipmanage.service.IEquipmentService;
import com.yeejoin.equipmanage.service.IEquipmentSpecificIndexSerivce;
import com.yeejoin.equipmanage.service.IEquipmentSpecificSerivce;
import com.yeejoin.equipmanage.service.IFireFightingSystemService;
import com.yeejoin.equipmanage.service.IManufacturerInfoService;
import com.yeejoin.equipmanage.service.IUploadFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;

import javax.servlet.http.HttpServletResponse;

/**
 * @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;

    @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;

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

    @RequestMapping(value = "/getEquipcountBySystemId", method = RequestMethod.GET)
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation("根据系统id查询分组设备数量")
    public List<EquipCountBySystemVO> getEquipCountBySystemId(Long systemId) {
        return fireFightingSystemService.getEquipCountBySystemId(systemId);
    }

    @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);
    }

    /**
     * 生产厂商列表（不分页）
     *
     * @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;
    }


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

    /**
     * 通过装备定义id查找性能指标
     *
     * @return
     */

    @Autowired
    IEquipmentSpecificIndexSerivce equipmentSpecificIndexSerivce;

    @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 -> {
            if(!"".equals(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);
        }

    }




    @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);
        }

    }



    @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());
            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.getColaCategoryAmountEquList(inhierarchy, equipTypeAmountPage.getEquipmentClassificationCode().substring(0, inhierarchy), 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);
        }

    }






    /**
     * 添加系统
     *
     * @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 = "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
    ) {
        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);
    }

    /**
     * 修改系统
     *
     * @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(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() {
        return fireFightingSystemService.list();
    }

    @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) {
        FireFightingSystemEntity fireFightingSystem = fireFightingSystemService.getById(id);
        List<AlarmDataVO> list1 = fireFightingSystemService.getSystemById(id);
        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);
        res.put("items", ite);
        res.put("title", "基本信息");
        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");
        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)
    @ApiOperation(value = "获取点位图，区域树数据", notes = "消防系统点位图使用")
    @GetMapping(value = "/point/tree")
    public List<PointTreeVo> getPointTree(@RequestParam(required = false) String systemId, @RequestParam(required = false) String bizOrgCode) {
        return fireFightingSystemService.getPointTree(systemId, bizOrgCode);
    }
    
    /**
     * 获取装备类型和统计值
     * @throws Exception 
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "获取装备类型和统计值", notes = "获取装备类型和统计值")
    @GetMapping(value = "/getEquipmentTypeAndCount/tree")
    public Object getEquipmentTypeAndCount( @RequestParam(required = false) String bizOrgCode,@RequestParam(required = false) String isiot) throws Exception {
        return fireFightingSystemService.getEquipmentTypeAndCount(bizOrgCode,isiot);
    }



    /**
     * 获取车辆类型和统计值
     * @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, 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);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "装备信息导出", notes = "装备信息导出")
    @PostMapping(value = "/downGetEquipmentcount")
    public void downGetEquipmentcount(HttpServletResponse response, @RequestParam(required = false) String name,@RequestParam(required = false)  String code) {

        if(code==null||code.equals("")){
            throw new RuntimeException("请选择单位");
        }else{
            List<EquipmentcountDto> list = iEquipmentService.getEquipmentcount(name,code);

            ExcelUtil.createTemplateHB(response, "装备信息", "装备信息", list, EquipmentcountDto.class, "bizOrgName");
        }
    }


}
