package com.yeejoin.amos.boot.module.common.biz.controller;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.util.StringUtil;
import com.yeejoin.amos.boot.biz.common.annotation.ResubmitCheck;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.interceptors.PermissionInterceptorContext;
import com.yeejoin.amos.boot.biz.common.utils.EnumsUtils;
import com.yeejoin.amos.boot.biz.common.utils.Menu;
import com.yeejoin.amos.boot.biz.common.utils.QRCodeUtil;
import com.yeejoin.amos.boot.module.common.api.core.framework.PersonIdentify;
import com.yeejoin.amos.boot.module.common.api.dto.*;
import com.yeejoin.amos.boot.module.common.api.entity.*;
import com.yeejoin.amos.boot.module.common.api.enums.OrgPersonEnum;
import com.yeejoin.amos.boot.module.common.api.enums.WaterResourceTypeEnum;
import com.yeejoin.amos.boot.module.common.api.feign.EquipFeignClient;
import com.yeejoin.amos.boot.module.common.biz.service.impl.*;
import com.yeejoin.amos.boot.module.common.biz.utils.CommonResponseUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
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 java.util.*;
import java.util.stream.Collectors;


/**
 * @author system_generator
 * @date 2021-06-29
 */
@RestController
@Api(tags = "stationApi")
@RequestMapping(value = "/water-resource")
public class WaterResourceController extends BaseController {

    @Autowired
    WaterResourceServiceImpl waterResourceServiceImpl;
    @Autowired
    WaterResourceCraneServiceImpl waterResourceCraneService;
    @Autowired
    WaterResourceHydrantServiceImpl waterResourceHydrantService;
    @Autowired
    WaterResourceNaturalServiceImpl waterResourceNaturalService;
    @Autowired
    WaterResourcePoolServiceImpl waterResourcePoolService;
    @Autowired
    WaterResourceIotServiceImpl waterResourceIotService;
    @Autowired
    SourceFileServiceImpl sourceFileService;
    @Autowired
    EquipFeignClient equipFeignClient;
    @Autowired
    WaterResourceIndexServiceImpl waterResourceIndexServiceImpl;
    @Autowired
    OrgUsrServiceImpl iOrgUsrService;

    @Value("${auth-key-fire-water:fire_water_info}")
    private String authKey;

    /**
     * 新增
     *
     * @return 返回结果
     */
    @ResubmitCheck
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/save")
    @ApiOperation(httpMethod = "POST", value = "新增", notes = "新增")
    public ResponseModel<WaterResourceDto> save(@RequestBody WaterResourceDto model) {
        String resourceType = model.getResourceType();
        Optional<WaterResourceTypeEnum> resourceTypeEnum = EnumsUtils.getEnumObject(WaterResourceTypeEnum.class,
                e -> e.getCode().equals(resourceType));
        /*bug 2913 更换保存方式 存储到公共附件表 chenzhao 2021-10-18 start*/
        // List<Object> realityImgList = model.getRealityImgList();

      /*
        if (realityImgList != null ){
        }
        realityImgList.forEach(i->{
            ((Map<String, Object>) i).put("name",QRCodeUtil.generateQRCode()+"."+i.toString().substring(i.toString().lastIndexOf(".") + 1).toLowerCase());
        });*/

        /* 更换保存方式 存储到公共附件表 chenzhao 2021-10-18 end*/


        model.setResourceTypeName(resourceTypeEnum.get().getName());
        model.setRealityImg(null);
        model.setOrientationImg(null);
        model.setIsDelete(true);
        /*2021-09-08 前端表示前端传递的address参数已经切割过，后端无需再切割获取 陈召 屏蔽代码 97-102行*/
       /* if(model.getAddress()!=null){
            JSONObject address = WaterResourceServiceImpl.getLongLatFromAddress(model.getAddress());
            model.setAddress(address.getString(BizConstant.ADDRESS));
            model.setLongitude(Double.valueOf(address.getString(BizConstant.LONGITUDE)));
            model.setLatitude(Double.valueOf(address.getString(BizConstant.LATITUDE)));
		 }*/
        if (!StringUtils.isEmpty(resourceType)) {
            switch (resourceType) {
                case "hydrant":
                    // 新增基础信息
                    model.setIsIot(true);
                    waterResourceServiceImpl.createWithModel(model);
                    // 新增属性信息
                    WaterResourceHydrantDto waterResourceHydrantDto = new WaterResourceHydrantDto();
                    BeanUtils.copyProperties(model, waterResourceHydrantDto);
                    waterResourceHydrantDto.setSequenceNbr(null);
                    waterResourceHydrantDto.setResourceId(model.getSequenceNbr());
                    waterResourceHydrantService.createWithModel(waterResourceHydrantDto);
                    break;
                case "crane":
                    // 新增基础信息
                    model.setIsIot(true);
                    waterResourceServiceImpl.createWithModel(model);
                    WaterResourceCraneDto waterResourceCraneDto = new WaterResourceCraneDto();
                    BeanUtils.copyProperties(model, waterResourceCraneDto);
                    waterResourceCraneDto.setSequenceNbr(null);
                    waterResourceCraneDto.setResourceId(model.getSequenceNbr());
                    waterResourceCraneService.createWithModel(waterResourceCraneDto);
                    break;
                case "natural":
                    // 新增基础信息
                    model.setIsIot(false);
                    waterResourceServiceImpl.createWithModel(model);
                    WaterResourceNaturalDto waterResourceNaturalDto = new WaterResourceNaturalDto();
                    BeanUtils.copyProperties(model, waterResourceNaturalDto);
                    waterResourceNaturalDto.setSequenceNbr(null);
                    waterResourceNaturalDto.setResourceId(model.getSequenceNbr());
                    waterResourceNaturalService.createWithModel(waterResourceNaturalDto);
                    break;
                case "pool":
                case "waterTank":
                case "industryPool":
                    // 新增基础信息
                    model.setIsIot(true);
                    waterResourceServiceImpl.createWithModel(model);
                    WaterResourcePoolDto waterResourcePoolDto = new WaterResourcePoolDto();
                    BeanUtils.copyProperties(model, waterResourcePoolDto);
//                    waterResourcePoolDto.setLevelDeviceId(String.join(",", model.getLevelDeviceId()));
                    waterResourcePoolDto.setSequenceNbr(null);
                    waterResourcePoolDto.setResourceId(model.getSequenceNbr());
                    waterResourcePoolService.createWithModel(waterResourcePoolDto);
                    break;
                default:
                    break;
            }
            // 新增物联信息
            if (null != model.getWaterResourceIotDto() && model.getWaterResourceIotDto().size() > 0) {
                Map<String, Object> map = model.getWaterResourceIotDto();
                List<WaterResourceIndex> list = new ArrayList<>();
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    WaterResourceIndex waterResourceIndex1 = new WaterResourceIndex();
                    waterResourceIndex1.setNameKey(entry.getKey());
                    waterResourceIndex1.setWaterId(model.getSequenceNbr());
                    waterResourceIndex1.setPerfValue(entry.getValue().toString());
                    list.add(waterResourceIndex1);
                }
                waterResourceIndexServiceImpl.saveBatch(list);
            }
        } else {
            waterResourceServiceImpl.createWithModel(model);
        }
        if (model.getAttachments() != null) {
            sourceFileService.saveAttachments(model.getSequenceNbr(), model.getAttachments());
        }
        if (model.getSequenceNbr() != null) {
            model.setResourceId(model.getSequenceNbr());
        }
        return ResponseHelper.buildResponse(model);
    }


    /**
     * 获取关联装备定义物联参数字段
     *
     * @param equipmentId 设备定义id
     * @return 返回结果
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getIotField")
    @ApiOperation(httpMethod = "GET", value = "获取关联装备定义物联参数字段", notes = "获取关联装备定义物联参数字段")
    public ResponseModel<Object> getIotField(Long equipmentId) {
        PerfQuotaIotDTO perfQuotaIotDTO = new PerfQuotaIotDTO();
        Page<EquipmentIndexDto> page = new Page<>();
        page.setCurrent(1);
        page.setSize(100);
        perfQuotaIotDTO.setEquipmentId(equipmentId);
        perfQuotaIotDTO.setGroupName("");
        perfQuotaIotDTO.setPage(page);
        ResponseModel<List<EquipmentIndexDto>> equipmentIndexDto = equipFeignClient.getEquipmentIndexDto(perfQuotaIotDTO);
        if (equipmentIndexDto.getResult().size() == 0) {
            return ResponseHelper.buildResponse(null);
        }

        List<EquipmentIndexDto> result = equipmentIndexDto.getResult();
        List<EquipmentIndexDto> list = result.stream().filter(e -> 1 == e.getIsIot()).collect(Collectors.toList());
        List<WaterResourceDyDto> listWater = new LinkedList<>();
        list.stream().forEach(e -> {
            WaterResourceDyDto dyDto = new WaterResourceDyDto();
            dyDto.setKey(e.getPerfQuotaDefinitionId());
            dyDto.setBlock(false);
            dyDto.setLabel(e.getPerfQuotaName());
            dyDto.setType("input");
            dyDto.setHide(false);
            listWater.add(dyDto);
        });

        return ResponseHelper.buildResponse(listWater);
    }


    /**
     * 根据sequenceNbr更新
     *
     * @param sequenceNbr 主键
     * @return 返回结果
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PutMapping(value = "/{sequenceNbr}")
    @ApiOperation(httpMethod = "PUT", value = "根据sequenceNbr更新", notes = "根据sequenceNbr更新")
    public ResponseModel<WaterResourceDto> updateBySequenceNbrWaterResource(@RequestBody WaterResourceDto model,
                                                                            @PathVariable(value = "sequenceNbr") Long sequenceNbr) {
        /*2021-09-08 前端表示前端传递的address参数已经切割过，后端无需再切割获取 陈召 屏蔽代码 173-178行*/
      /*  if (StringUtils.isNotEmpty(model.getAddress())) {
            JSONObject address = WaterResourceServiceImpl.getLongLatFromAddress(model.getAddress());
            model.setAddress(address.getString(BizConstant.ADDRESS));
            model.setLongitude(Double.valueOf(address.getString(BizConstant.LONGITUDE)));
            model.setLatitude(Double.valueOf(address.getString(BizConstant.LATITUDE)));
        }*/
        /*bug 2913 更换保存方式 存储到公共附件表 chenzhao 2021-10-18 start*/
        if (model.getAttachments() != null && !model.getAttachments().isEmpty()) {
            sourceFileService.saveAttachments(model.getSequenceNbr(), model.getAttachments());

        }
        /*bug 2913 更换保存方式 存储到公共附件表 chenzhao 2021-10-18 start*/
        // 更新基本信息
        model.setSequenceNbr(sequenceNbr);
        //model.setRealityImg(JSONArray.toJSONString(model.getRealityImgList()));
        //model.setOrientationImg(JSONArray.toJSONString(model.getOrientationImgList()));
        WaterResourceDto waterResourceDto = waterResourceServiceImpl.updateWithModel(model);
        // 更新属性信息
        String resourceType = model.getResourceType();
        if (!StringUtils.isEmpty(resourceType)) {
            switch (resourceType) {
                case "hydrant":
                    WaterResourceHydrantDto waterResourceHydrantDto = new WaterResourceHydrantDto();
                    WaterResourceHydrant waterResourceHydrant =
                            waterResourceHydrantService.getOne(new QueryWrapper<WaterResourceHydrant>().eq(
                                    "resource_id",
                                    sequenceNbr));
                    BeanUtils.copyProperties(model, waterResourceHydrantDto);
                    waterResourceHydrantDto.setSequenceNbr(waterResourceHydrant.getSequenceNbr());
                    waterResourceHydrantDto.setResourceId(sequenceNbr);
                    waterResourceHydrantService.updateWithModel(waterResourceHydrantDto);
                    break;
                case "crane":
                    WaterResourceCraneDto waterResourceCraneDto = new WaterResourceCraneDto();
                    WaterResourceCrane waterResourceCrane =
                            waterResourceCraneService.getOne(new QueryWrapper<WaterResourceCrane>().eq("resource_id",
                                    sequenceNbr));
                    BeanUtils.copyProperties(model, waterResourceCraneDto);
                    waterResourceCraneDto.setSequenceNbr(waterResourceCrane.getSequenceNbr());
                    waterResourceCraneDto.setResourceId(sequenceNbr);
                    waterResourceCraneService.updateWithModel(waterResourceCraneDto);
                    break;
                case "natural":
                    WaterResourceNaturalDto waterResourceNaturalDto = new WaterResourceNaturalDto();
                    WaterResourceNatural waterResourceNatural =
                            waterResourceNaturalService.getOne(new QueryWrapper<WaterResourceNatural>().eq(
                                    "resource_id",
                                    sequenceNbr));
                    BeanUtils.copyProperties(model, waterResourceNaturalDto);
                    waterResourceNaturalDto.setSequenceNbr(waterResourceNatural.getSequenceNbr());
                    waterResourceNaturalDto.setResourceId(sequenceNbr);
                    waterResourceNaturalService.updateWithModel(waterResourceNaturalDto);
                    break;
                case "industryPool":
                case "waterTank":
                case "pool":
                    WaterResourcePoolDto waterResourcePoolDto = new WaterResourcePoolDto();
                    WaterResourcePool waterResourcePool =
                            waterResourcePoolService.getOne(new QueryWrapper<WaterResourcePool>().eq("resource_id",
                                    sequenceNbr));
                    BeanUtils.copyProperties(model, waterResourcePoolDto);
                    waterResourcePoolDto.setSequenceNbr(waterResourcePool.getSequenceNbr());
                    waterResourcePoolDto.setResourceId(sequenceNbr);
                    waterResourcePoolService.updateWithModel(waterResourcePoolDto);
                    break;
                default:
                    break;
            }
        }
        // 更新物联信息
        if (null != model.getWaterResourceIotDto() && model.getWaterResourceIotDto().size() > 0) {
            Map<String, Object> map = model.getWaterResourceIotDto();
            List<WaterResourceIndex> list = new ArrayList<>();
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                LambdaQueryWrapper<WaterResourceIndex> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(WaterResourceIndex::getNameKey, entry.getKey());
                queryWrapper.eq(WaterResourceIndex::getWaterId, model.getSequenceNbr());
                WaterResourceIndex waterResourceIndex = waterResourceIndexServiceImpl.getOne(queryWrapper);
                if (waterResourceIndex != null) {
                    waterResourceIndex.setPerfValue(entry.getValue().toString());
                    list.add(waterResourceIndex);
                } else {
                    WaterResourceIndex waterResourceIndex1 = new WaterResourceIndex();
                    waterResourceIndex1.setNameKey(entry.getKey());
                    waterResourceIndex1.setWaterId(model.getSequenceNbr());
                    waterResourceIndex1.setPerfValue(entry.getValue().toString());
                    list.add(waterResourceIndex1);
                }
            }
            waterResourceIndexServiceImpl.saveOrUpdateBatch(list);
        }
        return ResponseHelper.buildResponse(waterResourceDto);
    }

    /**
     * 根据sequenceNbr删除
     *
     * @param sequenceNbr 主键
     * @return 返回结果
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @DeleteMapping(value = "/{sequenceNbr}")
    @ApiOperation(httpMethod = "DELETE", value = "根据sequenceNbr删除", notes = "根据sequenceNbr删除")
    public ResponseModel<Boolean> deleteBySequenceNbr(@PathVariable(value = "sequenceNbr") Long sequenceNbr) {
        WaterResource waterResource = waterResourceServiceImpl.getById(sequenceNbr);
        WaterResourceDto waterResourceDto = new WaterResourceDto();
        BeanUtils.copyProperties(waterResource, waterResourceDto);
        waterResourceDto.setIsDelete(false);
        waterResourceServiceImpl.updateWithModel(waterResourceDto);
        return ResponseHelper.buildResponse(true);
    }

    /**
     * 批量删除
     *
     * @param sequenceNbrList 主键
     * @return 返回结果
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @DeleteMapping(value = "/delete_batch")
    @ApiOperation(httpMethod = "DELETE", value = "批量删除", notes = "批量删除")
    public ResponseModel<Boolean> batchDeleteBySequenceNbrList(@RequestParam(value = "sequenceNbrList") List<Long> sequenceNbrList) {
        List<WaterResourceDto> waterResourceDtos = waterResourceServiceImpl.queryBatchSeq(sequenceNbrList);
        List<WaterResource> resourceList = waterResourceDtos.stream().map(item -> {
            WaterResource waterResource = new WaterResource();
            BeanUtils.copyProperties(item, waterResource);
            waterResource.setIsDelete(false);
            return waterResource;
        }).collect(Collectors.toList());
        boolean batchDelete = waterResourceServiceImpl.updateBatchById(resourceList);
        return ResponseHelper.buildResponse(batchDelete);
    }

    /**
     * 根据sequenceNbr查询
     *
     * @param sequenceNbr 主键
     * @return 返回结果
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/{sequenceNbr}")
    @ApiOperation(httpMethod = "GET", value = "根据sequenceNbr查询单个", notes = "根据sequenceNbr查询单个")
    public ResponseModel<WaterResourceDto> selectOne(@PathVariable Long sequenceNbr) {
        // 查询基本信息
        WaterResourceDto waterResourceDto = waterResourceServiceImpl.queryBySeq(sequenceNbr);

        /*bug 2913 更换保存方式 存储到公共附件表 chenzhao 2021-10-18 start*/
        Map<String, List<AttachmentDto>> attachments = sourceFileService.getAttachments(sequenceNbr);
        if (attachments != null) {
            waterResourceDto.setAttachments(attachments);
        }
        /*bug 2913 更换保存方式 存储到公共附件表 chenzhao 2021-10-18 end*/

        waterResourceDto.setRealityImgList(waterResourceDto.getRealityImg() != null ? JSONArray.parseArray(waterResourceDto.getRealityImg()) : null);
        waterResourceDto.setOrientationImgList(waterResourceDto.getOrientationImg() != null ? JSONArray.parseArray(waterResourceDto.getOrientationImg()) : null);
        Boolean isDelete = waterResourceDto.getIsDelete();
        // 查询属性信息
        String resourceType = waterResourceDto.getResourceType();
        if (!StringUtils.isEmpty(resourceType)) {
            switch (resourceType) {
                case "hydrant":
                    WaterResourceHydrant waterResourceHydrant =
                            waterResourceHydrantService.getOne(new QueryWrapper<WaterResourceHydrant>().eq(
                                    "resource_id",
                                    sequenceNbr));
                    BeanUtils.copyProperties(waterResourceHydrant, waterResourceDto);
                    break;
                case "crane":
                    WaterResourceCrane waterResourceCrane =
                            waterResourceCraneService.getOne(new QueryWrapper<WaterResourceCrane>().eq("resource_id",
                                    sequenceNbr));
                    BeanUtils.copyProperties(waterResourceCrane, waterResourceDto);
                    break;
                case "natural":
                    WaterResourceNatural waterResourceNatural =
                            waterResourceNaturalService.getOne(new QueryWrapper<WaterResourceNatural>().eq(
                                    "resource_id",
                                    sequenceNbr));
                    BeanUtils.copyProperties(waterResourceNatural, waterResourceDto);
                    break;
                case "industryPool":
                case "waterTank":
                case "pool":
                    WaterResourcePool waterResourcePool =
                            waterResourcePoolService.getOne(new QueryWrapper<WaterResourcePool>().eq("resource_id",
                                    sequenceNbr));
                    BeanUtils.copyProperties(waterResourcePool, waterResourceDto);
//                    waterResourceDto.setLevelDeviceId(Arrays.asList(waterResourcePool.getLevelDeviceId().split(",")));
                    break;
                default:
                    break;
            }
        }
        waterResourceDto.setSequenceNbr(sequenceNbr);
        waterResourceDto.setIsDelete(isDelete);
        // 查询物联参数
        LambdaQueryWrapper<WaterResourceIndex> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WaterResourceIndex::getWaterId, waterResourceDto.getSequenceNbr());
        List<WaterResourceIndex> list = waterResourceIndexServiceImpl.list(queryWrapper);
        if (list.size() > 0) {
            Map<String, Object> map = new HashMap<>();
            list.stream().forEach(e -> {
                map.put(e.getNameKey(), e.getPerfValue());
            });
            waterResourceDto.setWaterResourceIotDto(map);
        }
        return ResponseHelper.buildResponse(waterResourceDto);
    }

    /**
     * 列表分页查询
     *
     * @param current 当前页
     * @param size    每页大小
     * @return 返回结果
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/page")
    @ApiOperation(httpMethod = "GET", value = "分页查询", notes = "分页查询")
    public ResponseModel<Page<WaterResourceDto>> queryForPage(@RequestParam(value = "pageNum") int pageNum,
                                                              @RequestParam(value = "pageSize") int pageSize,
                                                              @RequestParam(value = "name", required = false) String name,
                                                              @RequestParam(value = "belongBuildingId", required = false) ArrayList<Long> belongBuildingId,
                                                              @RequestParam(value = "belongFightingSystemId", required = false) Long belongFightingSystemId,
                                                              @RequestParam(value = "sequenceNbr", required = false) Long sequenceNbr,
                                                              @RequestParam(value = "resourceType", required = false) String resourceType,
                                                              @RequestParam(value = "classifyId", required = false) String classifyId,
                                                              @RequestParam(value = "bizOrgCode", required = false) String bizOrgCode,
                                                              @RequestParam(value = "equipCateGoryCode", required = false) String equipCateGoryCode,
                                                              @RequestParam(value = "companyId", required = false) String companyId,
                                                              @RequestParam(value = "ids", required = false) List<String> ids) {
        Page<WaterResourceDto> page = new Page<>();
        page.setCurrent(pageNum);
        page.setSize(pageSize);

        //消防巡查 巡查对象用
        if (belongBuildingId != null && belongBuildingId.size() == 1  ){
            LinkedHashMap<String,Object> o = equipFeignClient.getTreeBuilding();
            if(o==null||!"200".equals(o.get("status").toString())) {
                throw new BadRequest("获取建筑树出错");
            }
            List<Map<String, Object>> buildingTree = (List<Map<String, Object>>) o.get("result");
            ArrayList<Long> finalBelongBuildingId = belongBuildingId;
            Map<String, Object> node = getAllNodes(buildingTree).stream().filter(map -> finalBelongBuildingId.get(0).toString().equals(map.get("id"))).findFirst().orElse(null);
            if (node != null) {
                belongBuildingId = findBuildChildrenIds(node);
            }
        }

        /*bug 2913 更换保存方式 存储到公共附件表 chenzhao 2021-10-18 start*/
        Page<WaterResourceDto> waterResourceDtoPage = waterResourceServiceImpl.queryForWaterResourcePage(page, name, resourceType,
                belongBuildingId, belongFightingSystemId, sequenceNbr, classifyId, bizOrgCode, equipCateGoryCode,ids,companyId);
        List<WaterResourceDto> records = waterResourceDtoPage.getRecords();
        records.forEach(i -> {
            Map<String, List<AttachmentDto>> attachments = sourceFileService.getAttachments(i.getSequenceNbr());
            if (attachments != null) {
                i.setAttachments(attachments);
            }
        });
        /*bug 2913 更换保存方式 存储到公共附件表 chenzhao 2021-10-18 end*/
        return ResponseHelper.buildResponse(waterResourceDtoPage);
    }

    private ArrayList<Long> findBuildChildrenIds(Map<String, Object> building) {
        List<Map<String, Object>> buildingTree = getAllNodes(Collections.singletonList(building));
        ArrayList<Long> objects = new ArrayList<>();
        List<Long> id = buildingTree.stream().map(building123 -> Long.valueOf(building123.get("id").toString())).collect(Collectors.toList());
       if (id.size()>0){
           objects.addAll(id);
       }
        return objects;

    }

    private List<Map<String, Object>> getAllNodes(List<Map<String, Object>> buildingTree) {
        List<Map<String, Object>> res = new LinkedList<>();
        if (buildingTree != null && !buildingTree.isEmpty()) {
            res.addAll(buildingTree);
            buildingTree.forEach(building -> {
                List<Map<String, Object>> childrenTree = (List<Map<String, Object>>) building.get("children");
                res.addAll(getAllNodes(childrenTree));
            });
        }
        return res;
    }

    /**
     * 列表分页查询缺陷模块用
     *
     * @param pageNum 当前页
     * @param pageSize    每页大小
     * @return 返回结果
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/pageByDefect")
    @ApiOperation(httpMethod = "GET", value = "列表分页查询缺陷模块用", notes = "列表分页查询缺陷模块用")
    public ResponseModel<Page<WaterResourceDto>> pageByDefect(@RequestParam(value = "pageNum") int pageNum,
                                                              @RequestParam(value = "pageSize") int pageSize,
                                                              @RequestParam(value = "nameOrCode", required = false) String nameOrCode,
                                                              @RequestParam(value = "bizOrgCode", required = false) String bizOrgCode,
                                                              @RequestParam(value = "systemName", required = false) String systemName) {
        ReginParams reginParams = getSelectedOrgInfo();
        if (StringUtils.isEmpty(bizOrgCode)) {
            if (ObjectUtils.isEmpty(reginParams) || ObjectUtils.isEmpty(reginParams.getPersonIdentity()) || StringUtils.isEmpty(reginParams.getPersonIdentity().getBizOrgCode())) {
                return ResponseHelper.buildResponse(null);
            }
            bizOrgCode = reginParams.getPersonIdentity().getBizOrgCode();
        }
        Page<WaterResourceDto> page = new Page<>();
        page.setCurrent(pageNum);
        page.setSize(pageSize);
        Page<WaterResourceDto> waterResourceDtoPage = waterResourceServiceImpl.pageByDefect(page, nameOrCode, bizOrgCode, systemName);
        return ResponseHelper.buildResponse(waterResourceDtoPage);
    }

    /**
     * 列表全部数据查询
     *
     * @return 返回结果
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "列表全部数据查询", notes = "列表全部数据查询")
    @GetMapping(value = "/list")
    public ResponseModel<List<WaterResourceDto>> selectForList() {
        return ResponseHelper.buildResponse(waterResourceServiceImpl.queryForWaterResourceList(true));
    }

    /**
     * 列表查询消防水资源
     *
     * @param name                   资源名称
     * @param sequenceNbr            资源编号
     * @param belongFightingSystemId 所属消防系统id
     * @param belongBuildingId       所在建筑id
     * @param belongBuilding         所在建筑
     * @param resourceType           资源类型（消火栓、消防水鹤、天然水源、消防水池）
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "根据条件查询列表", notes = "根据条件查询列表")
    @GetMapping(value = "/select_list")
    public ResponseModel<List<WaterResourceDto>> selectList(String name, Long sequenceNbr,
                                                            Long belongFightingSystemId, Long belongBuildingId,
                                                            String belongBuilding, String resourceType) {
        return ResponseHelper.buildResponse(waterResourceServiceImpl.queryWaterResourceList(true, name,
                sequenceNbr, belongFightingSystemId, belongBuildingId, belongBuilding, resourceType));
    }

    /**
     * 查询水资源类型列表
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "查询水资源类型列表", notes = "查询水资源类型列表")
    @GetMapping(value = "/resource_type_list")
    public ResponseModel<List<WaterResourceTypeDto>> selectResourceTypeList() {
        return ResponseHelper.buildResponse(waterResourceServiceImpl.getWaterResourceTypeList(true));
    }

    /**
     * 生成二维码code
     *
     * @return string
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "生成二维码code", notes = "生成二维码code")
    @GetMapping(value = "/qr/code")
    public ResponseModel<String> genQrCode() {
        return ResponseHelper.buildResponse(QRCodeUtil.generateQRCode());
    }

    @PersonIdentify
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/companyTreeByUserAndType", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据登录人及类型获取公司树", notes = "根据登录人及类型获取公司树")
    public ResponseModel<List<OrgMenuDto>> companyTreeByUserAndType() {
        // 获取登陆人角色
        ReginParams reginParams = getSelectedOrgInfo();
        // 权限赋值
        PermissionInterceptorContext.setDataAuthRule(authKey);
        List<OrgMenuDto> menus = iOrgUsrService.companyTreeByUserAndType(reginParams, null, null);
        return ResponseHelper.buildResponse(menus);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/typeTree/XFSYLX", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据bizOrgCode的值获取对应的消防水源树信息，含有队伍下统计数据", notes = "根据bizOrgCode的值获取对应的消防水源树信息，含有队伍下统计数据")
    public ResponseModel<List<Menu>> getwaterResourceTypeTree(@RequestParam(required = false) String bizOrgCode) throws Exception {
        List<Menu> list = waterResourceServiceImpl.getwaterResourceTypeTree(bizOrgCode);
        return ResponseHelper.buildResponse(list);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/type/XFSYLX", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "点击添加按钮显示的页签数据", notes = "点击添加按钮显示的页签数据")
    public ResponseModel<Object> getwaterResourceType() throws Exception {
        Object list = waterResourceServiceImpl.getwaterResourceType();
        return ResponseHelper.buildResponse(list);
    }

    @GetMapping("/equip/page")
    @ApiOperation(value = "消防水源信息分页列表")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    public ResponseModel getWaterInfoEquipListPage(@RequestParam(value = "pageNum") int pageNum,
                                                   @RequestParam(value = "pageSize") int pageSize,
                                                   @RequestParam(value = "bizOrgCode", required = false) String bizOrgCode,
                                                   @RequestParam(value = "id") String id) {
        Page<Map<String, Object>> page = new Page<>();
        page.setCurrent(pageNum);
        page.setSize(pageSize);
        if (StringUtils.isEmpty(bizOrgCode)) {
            ReginParams reginParams = getSelectedOrgInfo();
            bizOrgCode = !ValidationUtil.isEmpty(reginParams.getPersonIdentity()) && StringUtil.isNotEmpty(reginParams.getPersonIdentity().getBizOrgCode()) ? reginParams.getPersonIdentity().getBizOrgCode() : null;
        }
        return CommonResponseUtil.success(waterResourceServiceImpl.getWaterInfoEquipListPage(page, bizOrgCode, id));
    }

}
