package xiaoqu.home.open.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import xiaoqu.home.open.aop.AvoidRepeatSubmit;
import xiaoqu.home.open.controller.export.scenes.*;
import xiaoqu.home.open.controller.input.DistrictIdInput;
import xiaoqu.home.open.controller.input.sceneObject.Scene;
import xiaoqu.home.open.controller.input.sceneObject.SceneObjectInsert;
import xiaoqu.home.open.controller.input.sceneObject.SceneObjectPageInput;
import xiaoqu.home.open.model.db1.*;
import xiaoqu.home.open.model.db2.Object;
import xiaoqu.home.open.model.db2.SceneObject;
import xiaoqu.home.open.publicBean.BaseOutput;
import xiaoqu.home.open.publicBean.PageOutput;
import xiaoqu.home.open.service.db1.*;
import xiaoqu.home.open.service.db2.ObjectService;
import xiaoqu.home.open.service.db2.SceneObjectService;
import xiaoqu.home.open.utils.ResultResponseBeanUtil;
import xiaoqu.home.open.utils.StringUtil;
import xiaoqu.home.open.utils.UserUtils;
import xiaoqu.home.open.utils.WrapperUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;

/**
 *
 */
@Api(value = "场景对象相关")
@Controller
@RequestMapping("/sceneObject")
@Slf4j
public class SceneObjectController {
    @Autowired
    SceneObjectService sceneObjectService;
    @Autowired
    ToiletService toiletService;
    @Autowired
    PositionsService positionsService;
    @Autowired
    ObjectService objectService;
    @Autowired
    DistrictService districtService;
    @Autowired
    BuildingService buildingService;
    @Autowired
    FloorService floorService;
    @Autowired
    MultistageGridService multistageGridService;


//    @Autowired
//    RedisTemplate redisTemplate;

    @ApiOperation(value = "场景对象分页查询")
    @ResponseBody
    @RequestMapping(value = "/sceneObjectPageList", method = RequestMethod.POST)
    public BaseOutput<PageOutput<SceneObject>> sceneObjectPageList(HttpServletRequest request, @RequestBody SceneObjectPageInput input) {
        log.info("【sceneObjectPageList】input" + JSONObject.toJSONString(input));
        QueryWrapper<SceneObject> wrapper = WrapperUtils.getWrapper(false);
        PageOutput<SceneObject> output = new PageOutput<>();
        if (input.getTreeFlag() != null && input.getTreeFlag() == 1) {
            if (input.getIsscene() == 0) {
                switch (input.getLevel()) {
                    case 1:
                        wrapper.eq("building_id", input.getGridId());
                        break;
                    case 2:
                        wrapper.eq("floor_id", input.getGridId());

                        break;
                    default:
                        wrapper.eq("multistage_grid_id", input.getGridId());

                        break;
                }

            } else if (input.getIsscene() == 1) {
                if (input.getScenesId() != null) {
                    wrapper.eq("scenes_id", input.getScenesId());
                }
                if (input.getLevel() != null) {
                    wrapper.eq("scenes_level", input.getLevel());
                }
            }

        }
        if(input.getGridName()!=null){
            wrapper.like("superior_grid_name", input.getGridName());
            input.setGridName(null);

        }
        if (input.getObjectIds() != null && !input.getObjectIds().isEmpty()) {
            wrapper.in("object_id", input.getObjectIds());
            input.setObjectIds(null);

        }
        //树状字段排除
        input.setScenesId(null);
        input.setGridId(null);
        input.setLevel(null);
        input.setIsscene(null);
        input.setTreeFlag(null);


        WrapperUtils.beanToWrapper(wrapper, input);
        Page<SceneObject> pageList = new Page<>(input.getPage(), input.getRows());
        List<SceneObject> sceneObjectList = sceneObjectService.page(pageList, wrapper).getRecords();
        for (SceneObject sceneObject : sceneObjectList
        ) {
            if (sceneObject.getModifyId() == 0) {
                sceneObject.setModifyTime(null);
            }
        }
        output.setPage(pageList.getCurrent());
        output.setRecords(pageList.getTotal());
        output.setTotal(pageList.getPages());
        output.setRows(sceneObjectList);

        return ResultResponseBeanUtil.success(output);
    }


    @ApiOperation(value = "设置场景对象")
    @ResponseBody
    @AvoidRepeatSubmit
    @RequestMapping(value = "/setSceneObject", method = RequestMethod.POST)
    public BaseOutput<String> setSceneObject(HttpServletRequest request, @RequestBody SceneObjectInsert input) {
//        User user = UserUtils.getUser(request);
//        log.info("【addOrUpdateObject】User:" +user.getName()+",参数："+ JSONObject.toJSONString(input));
        List<Long> objectIds = input.getObjectIds();
        List<Scene> scenes = input.getScenes();
        if (input.getDistrictId() == null || input.getDistrictId() == 0) {
            return ResultResponseBeanUtil.fail("请选择站点");
        }
        if (objectIds == null || objectIds.size() == 0) {
            return ResultResponseBeanUtil.fail("请选择相关对象");
        }
        if (scenes == null || scenes.size() == 0) {
            return ResultResponseBeanUtil.fail("请选择相关场景");
        }
        List<Long> scenesIds = scenes.stream().map(p -> p.getId()).collect(Collectors.toList());

        List<Long> ids = new ArrayList<>();
        QueryWrapper<SceneObject> wrapper = WrapperUtils.getWrapper(false);
        wrapper.in("object_id", objectIds);
        wrapper.in("scenes_id", scenesIds);
        wrapper.eq("district_id", input.getDistrictId());
        int count = sceneObjectService.count(wrapper);
        if (count > 0) {
            return ResultResponseBeanUtil.fail(count + "条记录已存在，请修改后再提交");
        }

        try {

            for (Scene scene : scenes) {
                Toilet toilet = null;
                Positions positions = null;
                if (scene.getLevel() == 1) {
                    toilet = toiletService.getById(scene.getId());
                } else if (scene.getLevel() == 2) {
                    positions = positionsService.getById(scene.getId());
                }

                for (Long objectId : objectIds) {
                    Object object = objectService.getById(objectId);
                    if (object != null) {
                        SceneObject sceneObject = new SceneObject();
                        sceneObject.setObjectName(object.getName());
                        sceneObject.setObjectId(object.getId());
                        sceneObject.setObjectParentId(object.getParentId());
                        sceneObject.setObjectParentName(object.getParentName());
                        sceneObject.setLevel(object.getLevel());
                        sceneObject.setStatus(input.getStatus());
                        sceneObject.setMemo(input.getMemo() != null ? input.getMemo() : "");
                        sceneObject.setSort(object.getSort());

                        //从哪获取，scene||toilet/positions
                        sceneObject.setScenesLevel(scene.getLevel());

                        if (scene.getLevel() == 1) {

                            sceneObject.setDistrictId(toilet.getDistrictId());
                            sceneObject.setDistrictName(toilet.getDistrictName());
                            sceneObject.setPropertyId(toilet.getPropertyId());
                            sceneObject.setPropertyName(toilet.getPropertyName());
                            sceneObject.setAgentName(toilet.getAgentName());
                            sceneObject.setAgentId(toilet.getAgentId());
                            sceneObject.setSuperiorGridName(toilet.getSuperiorGridName());
                            sceneObject.setScenesId(toilet.getId());
                            sceneObject.setGridId(toilet.getMultistageGridId());
                            sceneObject.setGridLevel(toilet.getGridLevel());
                            sceneObject.setGridName(toilet.getMultistageGridName());
                            sceneObject.setSuperiorGridName(toilet.getSuperiorGridName());
                            sceneObject.setScenesName(toilet.getName());
                            sceneObject.setBuildingId(toilet.getBuildingId());
                            sceneObject.setFloorId(toilet.getFloorId());
                            sceneObject.setMultistageGridId(toilet.getMultistageGridId());
                            sceneObject.setSuperiorScenesName("");

                        } else if (scene.getLevel() == 2) {
                            sceneObject.setDistrictId(positions.getDistrictId());
                            sceneObject.setDistrictName(positions.getDistrictName());
                            sceneObject.setPropertyId(positions.getPropertyId());
                            sceneObject.setPropertyName(positions.getPropertyName());
                            sceneObject.setAgentName(positions.getAgentName());
                            sceneObject.setAgentId(positions.getAgentId());
//                            sceneObject.setSuperiorGridName(positions.getSuperiorGridName());
                            sceneObject.setScenesId(positions.getId());
                            sceneObject.setGridId(positions.getMultistageGridId());
                            sceneObject.setGridLevel(positions.getGridLevel());
                            sceneObject.setGridName(positions.getMultistageGridName());
                            sceneObject.setSuperiorGridName(positions.getSuperiorGridName());
                            sceneObject.setScenesName(positions.getName());
                            sceneObject.setBuildingId(positions.getBuildingId());
                            sceneObject.setFloorId(positions.getFloorId());
                            sceneObject.setMultistageGridId(positions.getMultistageGridId());
                            sceneObject.setSuperiorScenesName(positions.getSuperiorScenesName());

                        }
                        sceneObjectService.save(sceneObject);
                        ids.add(scene.getId());
                    }
                }


            }
        } catch (Exception e) {
            e.printStackTrace();
            sceneObjectService.removeByIds(ids);
            return ResultResponseBeanUtil.fail("设置失败");

        }
        return ResultResponseBeanUtil.success("场景对象设置成功");


    }

    @ApiOperation(value = "修改场景对象")
    @ResponseBody
    @AvoidRepeatSubmit
    @RequestMapping(value = "/updateSceneObject", method = RequestMethod.POST)
    public BaseOutput<String> updateSceneObject(HttpServletRequest request, @RequestBody SceneObjectInsert input) {
//        User user = UserUtils.getUser(request);
//        log.info("【addOrUpdateObject】User:" +user.getName()+",参数："+ JSONObject.toJSONString(input));
        if (input.getId() != null) {
            SceneObject sceneObject = sceneObjectService.getById(input.getId());
            if (sceneObject != null) {
                sceneObject.setStatus(input.getStatus());
                sceneObject.setMemo(input.getMemo() != null ? input.getMemo() : "");
                sceneObjectService.updateById(sceneObject);
                return ResultResponseBeanUtil.success("修改成功");

            } else {
                return ResultResponseBeanUtil.fail("当前修改场景对象未找到");
            }
        }
        return ResultResponseBeanUtil.fail("请要选择修改的记录");


    }

    @ApiOperation(value = "删除对象信息")
    @ResponseBody
    @AvoidRepeatSubmit
    @RequestMapping(value = "/removeSceneObject", method = RequestMethod.POST)
    public BaseOutput<String> removeSceneObject(HttpServletRequest request, @RequestBody SceneObjectInsert input) {
//        User user = UserUtils.getUser(request);
//        log.info("【addOrUpdateObject】User:" +user.getName()+",参数："+ JSONObject.toJSONString(input));
        if (input.getId() != null) {
            SceneObject curObject = sceneObjectService.getById(input.getId());
            if (curObject != null) {
                curObject.setSoftDelete(1);
                sceneObjectService.updateById(curObject);
            } else {
                return ResultResponseBeanUtil.fail("当前场景对象未找到");
            }
        }
        return ResultResponseBeanUtil.success("删除成功");

    }
//
//
//    @ApiOperation(value = "场景对象导出(全站点)")
//    @PostMapping("/sceneObjectExport")
//    public void sceneObjectExport(HttpServletRequest request, HttpServletResponse response, @RequestBody DistrictIdInput input) throws IOException {
//        QueryWrapper<SceneObject> wrapper = WrapperUtils.getWrapper(false);
//        User user = UserUtils.getUser(request);
//        log.info("【sceneObjectExport】user:" + user.getName() + ",参数：" + JSONObject.toJSONString(input));
//
////        Boolean aBoolean = authorityService.checkAuthorityIsagent(user.getAuthorityId());
////        wrapper = WrapperUtils.getByIsAgent(aBoolean, user.getAgentId(), wrapper);
//
//        Long districtId = input.getDistrictId();
//        if (districtId == null || districtId == 0) {
//            return;
//        }
//        District district = districtService.getById(districtId);
//        if (district == null) {
//            return;
//        }
//
//
//        wrapper = WrapperUtils.beanToWrapper(wrapper, input);
//        List<SceneObject> querylist = sceneObjectService.list(wrapper);
//        wrapper.groupBy("object_id");
//        wrapper.orderByAsc("sort");
//        List<SceneObject> groupList = sceneObjectService.list(wrapper);
//        int colsize = groupList.size();
//        List<ObjectFlag> objectNameList = new ArrayList<>();
//        Map<Long, Integer> objectIdMap = new HashMap<>();
//        for (SceneObject sceneObject : groupList) {
//            objectIdMap.put(sceneObject.getId(), objectNameList.size());
//            ObjectFlag objectFlag = new ObjectFlag();
//            objectFlag.setObFlag(sceneObject.getObjectName());
//            objectNameList.add(objectFlag);
//        }
//        //映射用list
//        Map<String, List<ObjectFlag>> sceneIdMap = new HashMap<>();
//
//        List<DistrictUnionInfoOutput> list = new ArrayList<DistrictUnionInfoOutput>();
//        DistrictUnionInfoOutput districtUnionInfoOutput;
//        districtUnionInfoOutput = new DistrictUnionInfoOutput();
//        districtUnionInfoOutput.setId(district.getId());
//        districtUnionInfoOutput.setName(district.getDistrictName());
//        List<BuildingUnionInfoOutput> dropDownList = new ArrayList<BuildingUnionInfoOutput>();
//        QueryWrapper<Building> BuildingWrapper = WrapperUtils.getWrapper(false);
//        BuildingWrapper.eq("district_id", districtId);
//        BuildingWrapper.orderByAsc("id");
//        List<Building> buildingList = buildingService.list(BuildingWrapper);
//
//        if (buildingList != null && buildingList.size() > 0) {
//            // 查楼座
//            for (Building building : buildingList) {
//                BuildingUnionInfoOutput BuildingUnionInfoEntity = new BuildingUnionInfoOutput();
//                BuildingUnionInfoEntity.setId(building.getId());
//                BuildingUnionInfoEntity.setName(building.getName());
//                QueryWrapper<Floor> floorWrapper = WrapperUtils.getWrapper(false);
//                floorWrapper.eq("building_id", building.getId());
//                floorWrapper.orderByAsc("id");
//                List<Floor> floors = floorService.list(floorWrapper);
//                List<FloorUnionOutout> floorsOut = new ArrayList<FloorUnionOutout>();
//                for (Floor floor : floors) {// 查楼层
//                    FloorUnionOutout floorUnionOutout = new FloorUnionOutout();
//                    floorUnionOutout.setName(floor.getName());
//                    floorUnionOutout.setId(floor.getId());
//                    QueryWrapper<MultistageGrid> MultistageGridWrapper = WrapperUtils.getWrapper(false);
//                    MultistageGridWrapper.eq("floor_id", floor.getId());
//                    MultistageGridWrapper.orderByAsc("id");
//                    List<MultistageGrid> multistageGrids = multistageGridService.list(MultistageGridWrapper);
//                    List<MultistageGridOutput> multistageGridOutputs = new ArrayList<MultistageGridOutput>();
//                    if (multistageGrids != null && multistageGrids.size() > 0) {
//                        for (MultistageGrid multistageGrid : multistageGrids) {
//                            MultistageGridOutput multistageGridOutput = new MultistageGridOutput();
//                            multistageGridOutput.setId(multistageGrid.getId());
//                            multistageGridOutput.setName(multistageGrid.getName());
//                            QueryWrapper<Toilet> ToiletGridWrapper = WrapperUtils.getWrapper(false);
//                            ToiletGridWrapper.eq("multistage_grid_id", multistageGrid.getId());
//                            ToiletGridWrapper.orderByAsc("id");
//                            List<ScenesUnionOutput> toiletOuts = new ArrayList<ScenesUnionOutput>();
//                            List<Toilet> toilets = toiletService.list(ToiletGridWrapper);
//                            if (toilets != null && toilets.size() > 0) {
//                                for (Toilet toilet : toilets) {
//                                    ScenesUnionOutput toiletUnionOutput = GetScenesOutput(toilet, sceneIdMap, colsize);
//                                    toiletOuts.add(toiletUnionOutput);
//                                }
//                            }
//                            QueryWrapper<Positions> positionsWrapper = WrapperUtils.getWrapper(false);
//                            positionsWrapper.eq("multistage_grid_id", multistageGrid.getId());
//                            positionsWrapper.orderByAsc("id");
//                            List<Positions> positionss = positionsService.list(positionsWrapper);
//                            if (positionss != null && positionss.size() > 0) {
//                                for (Positions positions : positionss) {
//                                    ScenesUnionOutput toiletUnionOutput = GetScenesPosition(positions, sceneIdMap, colsize);
//                                    toiletOuts.add(toiletUnionOutput);
//                                }
//                            }
//                            if (toilets.size() > 0 || positionss.size() > 0) {
////                                multistageGridOutput.setScenes(toiletOuts);
//                                multistageGridOutputs.add(multistageGridOutput);
//                            }
//
//                        }
//                    } else {
//                        MultistageGridOutput multistageGridOutput = new MultistageGridOutput();
//                        QueryWrapper<Toilet> toiletWrapper = WrapperUtils.getWrapper(false);
//                        toiletWrapper.eq("district_id", districtId);
//                        toiletWrapper.eq("building_id", building.getId());
//                        toiletWrapper.eq("floor_id", floor.getId());
//                        toiletWrapper.eq("multistage_grid_id", 0);
//                        toiletWrapper.orderByAsc("id");
//                        List<ScenesUnionOutput> toiletOuts = new ArrayList<ScenesUnionOutput>();
//                        List<Toilet> toilets = toiletService.list(toiletWrapper);
//                        if (toilets != null && toilets.size() > 0) {
//                            for (Toilet toilet : toilets) {
//                                ScenesUnionOutput toiletUnionOutput = GetScenesOutput(toilet, sceneIdMap, colsize);
//                                toiletOuts.add(toiletUnionOutput);
//                            }
//                        }
//                        QueryWrapper<Positions> positionsWrapper = WrapperUtils.getWrapper(false);
//                        positionsWrapper.eq("district_id", districtId);
//                        positionsWrapper.eq("building_id", building.getId());
//                        positionsWrapper.eq("floor_id", floor.getId());
//                        positionsWrapper.eq("multistage_grid_id", 0);
//                        positionsWrapper.orderByAsc("id");
//                        List<Positions> positionss = positionsService.list(positionsWrapper);
//                        if (positionss != null && positionss.size() > 0) {
//                            for (Positions positions : positionss) {
//                                ScenesUnionOutput toiletUnionOutput = GetScenesPosition(positions, sceneIdMap, colsize);
//                                toiletOuts.add(toiletUnionOutput);
//                            }
//                        }
//
//                        if(toilets.size()>0||positionss.size()>0){
////                            multistageGridOutput.setScenes(toiletOuts);
//                            multistageGridOutputs.add(multistageGridOutput);
//                        }
//                    }
//                    QueryWrapper<Positions> positionsWrapper = WrapperUtils.getWrapper(false);
//                    positionsWrapper.eq("district_id", districtId);
//                    positionsWrapper.eq("building_id", building.getId());
//                    positionsWrapper.eq("floor_id", floor.getId());
//
//                    int count = positionsService.count(positionsWrapper);
//
//                    QueryWrapper<Toilet> toiletWrapper = WrapperUtils.getWrapper(false);
//                    toiletWrapper.eq("district_id", districtId);
//                    toiletWrapper.eq("building_id", building.getId());
//                    toiletWrapper.eq("floor_id", floor.getId());
//                    count += toiletService.count(toiletWrapper);
//                    if (count > 0) {
//                        floorUnionOutout.setMultistageGrid(multistageGridOutputs);
//                        floorsOut.add(floorUnionOutout);
//                    }
//
//                }
//                QueryWrapper<Positions> positionsWrapper = WrapperUtils.getWrapper(false);
//                positionsWrapper.eq("district_id", districtId);
//                positionsWrapper.eq("building_id", building.getId());
//                int count = positionsService.count(positionsWrapper);
//
//                QueryWrapper<Toilet> toiletWrapper = WrapperUtils.getWrapper(false);
//                toiletWrapper.eq("district_id", districtId);
//                toiletWrapper.eq("building_id", building.getId());
//                count += toiletService.count(toiletWrapper);
//                BuildingUnionInfoEntity.setFloor(floorsOut);
//                if (count > 0) {
//                    dropDownList.add(BuildingUnionInfoEntity);
//                }
//            }
//        }
//
//        for (SceneObject sceneObject : querylist) {
//            log.info("【sceneObjectExport】" + sceneObject.getScenesLevel() + "_" + sceneObject.getScenesId());
//            List<ObjectFlag> curObjectList = sceneIdMap.get(sceneObject.getScenesLevel() + "_" + sceneObject.getScenesId());
//            Integer integer = objectIdMap.get(sceneObject.getObjectId());
//            curObjectList.get(integer).setObFlag("●");
//        }
//        districtUnionInfoOutput.setBuilding(dropDownList);
//        list.add(districtUnionInfoOutput);
//        Map<String, java.lang.Object> map = new HashMap<String, java.lang.Object>();
//        String fileTemplate = "./temp/sceneObject.xlsx";
//        File fileOut = new File(fileTemplate);
//        //从jar里读取文件 然后建立临时文件模板  如果temp 目录已经有了就不读取了
//        if (!fileOut.exists()) {
//            File dirPath = new File("./temp");
//            if (!dirPath.exists()) {
//                dirPath.mkdir();
//            }
//            fileOut.createNewFile();//将模板文件放到临时目录
//            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/sceneObject.xlsx");
//            FileOutputStream fos = new FileOutputStream(fileTemplate);
//            byte[] b = new byte[1024];
//            while ((inputStream.read(b)) != -1) {
//                fos.write(b);// 写入数据
//            }
//            inputStream.close();
//            fos.close();// 保存数据
//        }
//        TemplateExportParams params = new TemplateExportParams(fileTemplate);
//        params.setColForEach(true);
//        log.info("场景对象分布记录=" + JSON.toJSONString(list));
//        map.put("list", list);
//        map.put("collist", objectNameList);
//        Workbook workbook = ExcelExportUtil.exportExcel(params, map);
//        String fileName = "场景对象分布记录" + DateUtil.format(new Date(), "yyyMMddHHmmss") + ".xlsx";
//        response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "iso8859-1"));
//        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
//        response.setHeader("Pragma", "no-cache");
//        response.setHeader("Cache-Control", "no-cache");
//        response.setDateHeader("Expires", 0);
//        BufferedOutputStream bufferedOutPut = new BufferedOutputStream(response.getOutputStream());
//        workbook.write(bufferedOutPut);
//        bufferedOutPut.flush();
//        bufferedOutPut.close();
//
//    }


    private ScenesUnionOutput GetScenesOutput(Toilet toilet, Map<String, List<ObjectFlag>> sceneIdMap, Integer size) {
        ScenesUnionOutput toiletUnionOutput = new ScenesUnionOutput();
        toiletUnionOutput.setId(toilet.getId());
        toiletUnionOutput.setName(toilet.getName());
        toiletUnionOutput.setSuperiorScenesName("");
        ObjectFlag[] arr = new ObjectFlag[size];
        for (int i = 0; i < size; i++) {
            arr[i] = new ObjectFlag();
        }
        List<ObjectFlag> values = Arrays.asList(arr);
        toiletUnionOutput.setObjectList(values);
        sceneIdMap.put("1_" + toilet.getId(), values);
        return toiletUnionOutput;
    }


    private ScenesUnionOutput GetScenesPosition(Positions positions, Map<String, List<ObjectFlag>> sceneIdMap, Integer size) {
        ScenesUnionOutput toiletUnionOutput = new ScenesUnionOutput();
        toiletUnionOutput.setId(positions.getId());
        toiletUnionOutput.setName(positions.getName());
        toiletUnionOutput.setSuperiorScenesName(positions.getSuperiorScenesName());
        ObjectFlag[] arr = new ObjectFlag[size];
        for (int i = 0; i < size; i++) {
            arr[i] = new ObjectFlag();
        }
        List<ObjectFlag> values = Arrays.asList(arr);
        toiletUnionOutput.setObjectList(values);
        sceneIdMap.put("2_" + positions.getId(), values);
        return toiletUnionOutput;
    }

//
//    /**
//     * 测试用，每层计数
//     *
//     * @param request
//     * @param response
//     * @param input
//     * @throws IOException
//     */
//    @ApiOperation(value = "场景对象导出(全站点)")
//    @PostMapping("/sceneObjectExportTest")
//    public void sceneObjectExportTest(HttpServletRequest request, HttpServletResponse response, @RequestBody DistrictIdInput input) throws IOException {
//
//
//        User user = UserUtils.getUser(request);
//        log.info("【sceneObjectExport】user:" + user.getName() + ",参数：" + JSONObject.toJSONString(input));
//        Long districtId = input.getDistrictId();
//        District district = districtService.getById(districtId);
//        QueryWrapper<SceneObject> wrapper = WrapperUtils.getWrapper(false);
//        wrapper = WrapperUtils.beanToWrapper(wrapper, input);
//        List<SceneObject> querylist = sceneObjectService.list(wrapper);
//        wrapper.groupBy("object_id");
//        wrapper.orderByAsc("sort");
//        List<SceneObject> groupList = sceneObjectService.list(wrapper);
//        int colsize = groupList.size();
//        List<ObjectFlag> objectNameList = new ArrayList<>();
//        Map<Long, Integer> objectIdMap = new HashMap<>();
//        for (SceneObject sceneObject : groupList) {
//            objectIdMap.put(sceneObject.getObjectId(), objectNameList.size());
//            ObjectFlag objectFlag = new ObjectFlag();
//            objectFlag.setObFlag(sceneObject.getObjectName());
//            objectNameList.add(objectFlag);
//        }
//        //映射用list
//        Map<String, List<ObjectFlag>> sceneIdMap = new HashMap<>();
//
//
//        List<DistrictUnionInfoOutput> list = new ArrayList<DistrictUnionInfoOutput>();
//        DistrictUnionInfoOutput districtUnionInfoOutput;
//        districtUnionInfoOutput = new DistrictUnionInfoOutput();
//        districtUnionInfoOutput.setId(district.getId());
//        districtUnionInfoOutput.setName(district.getDistrictName());
//        List<BuildingUnionInfoOutput> dropDownList = new ArrayList<BuildingUnionInfoOutput>();
//        QueryWrapper<Building> BuildingWrapper = WrapperUtils.getWrapper(false);
//        BuildingWrapper.eq("district_id", districtId);
//        BuildingWrapper.orderByAsc("id");
//        List<Building> buildingList = buildingService.list(BuildingWrapper);
//
//        if (buildingList != null && buildingList.size() > 0) {
//            // 查楼座
//            for (Building building : buildingList) {
//                BuildingUnionInfoOutput BuildingUnionInfoEntity = new BuildingUnionInfoOutput();
//                BuildingUnionInfoEntity.setId(building.getId());
//                BuildingUnionInfoEntity.setName(building.getName());
//                QueryWrapper<Floor> floorWrapper = WrapperUtils.getWrapper(false);
//                floorWrapper.eq("building_id", building.getId());
//                floorWrapper.orderByAsc("id");
//                List<Floor> floors = floorService.list(floorWrapper);
//                List<FloorUnionOutout> floorsOut = new ArrayList<FloorUnionOutout>();
//                for (Floor floor : floors) {// 查楼层
//                    FloorUnionOutout floorUnionOutout = new FloorUnionOutout();
//                    floorUnionOutout.setName(floor.getName());
//                    floorUnionOutout.setId(floor.getId());
//                    QueryWrapper<MultistageGrid> MultistageGridWrapper = WrapperUtils.getWrapper(false);
//                    MultistageGridWrapper.eq("floor_id", floor.getId());
//                    MultistageGridWrapper.orderByAsc("id");
//                    List<MultistageGrid> multistageGrids = multistageGridService.list(MultistageGridWrapper);
//                    List<MultistageGridOutput> multistageGridOutputs = new ArrayList<MultistageGridOutput>();
//                    if (multistageGrids != null && multistageGrids.size() > 0) {
//                        for (MultistageGrid multistageGrid : multistageGrids) {
//                            MultistageGridOutput multistageGridOutput = new MultistageGridOutput();
//                            multistageGridOutput.setId(multistageGrid.getId());
//                            multistageGridOutput.setName(multistageGrid.getName());
//
//
//
//                            QueryWrapper<Toilet> ToiletGridWrapper = WrapperUtils.getWrapper(false);
//                            ToiletGridWrapper.eq("multistage_grid_id", multistageGrid.getId());
//                            ToiletGridWrapper.orderByAsc("id");
////                            List<ScenesUnionOutput> toiletOuts = new ArrayList<ScenesUnionOutput>();
//                            List<Toilet> Toilets = toiletService.list(ToiletGridWrapper);
//                            if (Toilets != null && Toilets.size() > 0) {
//                                List<SuperiorScenesUnionOutput> superiorScenes = new ArrayList<SuperiorScenesUnionOutput>();
//
//                                for (Toilet toilet : Toilets) {
//                                    SuperiorScenesUnionOutput superiorScenesUnionOutput = new SuperiorScenesUnionOutput();
//                                    superiorScenesUnionOutput.setId(0L);
//
//                                    ScenesUnionOutput toiletUnionOutput = GetScenesOutput(toilet, sceneIdMap, colsize);
//                                    toiletOuts.add(toiletUnionOutput);
//                                }
//                            }
//                            QueryWrapper<Positions> positionsWrapper = WrapperUtils.getWrapper(false);
//                            positionsWrapper.eq("multistage_grid_id", multistageGrid.getId());
//                            positionsWrapper.orderByAsc("id");
//                            List<Positions> positionss = positionsService.list(positionsWrapper);
//                            if (positionss != null && positionss.size() > 0) {
//                                for (Positions positions : positionss) {
//                                    ScenesUnionOutput toiletUnionOutput = GetScenesPosition(positions, sceneIdMap, colsize);
//                                    toiletOuts.add(toiletUnionOutput);
//                                }
//                            }
////                            multistageGridOutput.setScenes(toiletOuts);
//                            multistageGridOutputs.add(multistageGridOutput);
//                        }
//                    } else {
//                        MultistageGridOutput multistageGridOutput = new MultistageGridOutput();
//                        QueryWrapper<Toilet> toiletWrapper = WrapperUtils.getWrapper(false);
//                        toiletWrapper.eq("district_id", districtId);
//                        toiletWrapper.eq("building_id", building.getId());
//                        toiletWrapper.eq("floor_id", floor.getId());
//                        toiletWrapper.eq("multistage_grid_id", 0);
//                        toiletWrapper.orderByAsc("id");
//                        List<ScenesUnionOutput> toiletOuts = new ArrayList<ScenesUnionOutput>();
//                        List<Toilet> toilets = toiletService.list(toiletWrapper);
//                        if (toilets != null && toilets.size() > 0) {
//                            for (Toilet toilet : toilets) {
//                                ScenesUnionOutput toiletUnionOutput = GetScenesOutput(toilet, sceneIdMap, colsize);
//                                toiletOuts.add(toiletUnionOutput);
//                            }
//                        }
//                        QueryWrapper<Positions> positionsWrapper = WrapperUtils.getWrapper(false);
//                        positionsWrapper.eq("district_id", districtId);
//                        positionsWrapper.eq("building_id", building.getId());
//                        positionsWrapper.eq("floor_id", floor.getId());
//                        positionsWrapper.eq("multistage_grid_id", 0);
//                        positionsWrapper.orderByAsc("id");
//                        List<Positions> positionss = positionsService.list(positionsWrapper);
//                        if (positionss != null && positionss.size() > 0) {
//                            for (Positions positions : positionss) {
//                                ScenesUnionOutput toiletUnionOutput = GetScenesPosition(positions, sceneIdMap, colsize);
//                                toiletOuts.add(toiletUnionOutput);
//                            }
//                        }
//                        if(toilets.size()>0||positionss.size()>0){
////                            multistageGridOutput.setScenes(toiletOuts);
//                            multistageGridOutputs.add(multistageGridOutput);
//                        }
//
//                    }
//                    QueryWrapper<Positions> positionsWrapper = WrapperUtils.getWrapper(false);
//                    positionsWrapper.eq("district_id", districtId);
//                    positionsWrapper.eq("building_id", building.getId());
//                    positionsWrapper.eq("floor_id", floor.getId());
//
//                    int count = positionsService.count(positionsWrapper);
//
//                    QueryWrapper<Toilet> toiletWrapper = WrapperUtils.getWrapper(false);
//                    toiletWrapper.eq("district_id", districtId);
//                    toiletWrapper.eq("building_id", building.getId());
//                    toiletWrapper.eq("floor_id", floor.getId());
//                    count += toiletService.count(toiletWrapper);
//                    if (count > 0) {
//                        floorUnionOutout.setMultistageGrid(multistageGridOutputs);
//                        floorsOut.add(floorUnionOutout);
//                    }
//                }
//                QueryWrapper<Positions> positionsWrapper = WrapperUtils.getWrapper(false);
//                positionsWrapper.eq("district_id", districtId);
//                positionsWrapper.eq("building_id", building.getId());
//                int count = positionsService.count(positionsWrapper);
//
//                QueryWrapper<Toilet> toiletWrapper = WrapperUtils.getWrapper(false);
//                toiletWrapper.eq("district_id", districtId);
//                toiletWrapper.eq("building_id", building.getId());
//                count += toiletService.count(toiletWrapper);
//                BuildingUnionInfoEntity.setFloor(floorsOut);
//                if (count > 0) {
//                    dropDownList.add(BuildingUnionInfoEntity);
//                }
//            }
//        }
//
//        for (SceneObject sceneObject : querylist) {
//            log.info(sceneObject.getScenesLevel() + "_" + sceneObject.getScenesId());
//            List<ObjectFlag> curObjectList = sceneIdMap.get(sceneObject.getScenesLevel() + "_" + sceneObject.getScenesId());
//            Integer integer = objectIdMap.get(sceneObject.getObjectId());
//            curObjectList.get(integer).setObFlag("●");
//        }
//        districtUnionInfoOutput.setBuilding(dropDownList);
//        list.add(districtUnionInfoOutput);
//        Map<String, java.lang.Object> map = new HashMap<String, java.lang.Object>();
//
//        String fileTemplate = "D:\\ququ_git\\xiaoqu-intellectual-web\\src\\main\\resources\\template\\sceneObject.xlsx";
//        File fileOut = new File(fileTemplate);
//        //从jar里读取文件 然后建立临时文件模板  如果temp 目录已经有了就不读取了
//        if (!fileOut.exists()) {
//
//            File dirPath = new File("./temp");
//            if (!dirPath.exists()) {
//                dirPath.mkdir();
//            }
//            fileOut.createNewFile();//将模板文件放到临时目录
//            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/sceneObject.xlsx");
//            FileOutputStream fos = new FileOutputStream(fileTemplate);
//            byte[] b = new byte[1024];
//            while ((inputStream.read(b)) != -1) {
//                fos.write(b);// 写入数据
//            }
//            inputStream.close();
//            fos.close();// 保存数据
//        }
//        TemplateExportParams params = new TemplateExportParams(fileTemplate);
//        params.setColForEach(true);
//        log.info("场景对象分布记录=" + JSON.toJSONString(list));
//        map.put("list", list);
//        map.put("collist", objectNameList);
//        Workbook workbook = ExcelExportUtil.exportExcel(params, map);
////        String fileName = "场景对象分布记录" + DateUtil.format(new Date(), "yyyMMddHHmmss") + ".xlsx";
//        FileOutputStream fos;
//        try {
//            fos = new FileOutputStream("d:/excel/template1.xlsx");
//            workbook.write(fos);
//            fos.close();
//        } catch (Exception e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
////        return ResultResponseBeanUtil.success("导出完成");
//
//    }
//
//
//
//    @ApiOperation(value = "导出")
//    @PostMapping("/export")
//    public void export(HttpServletRequest request, HttpServletResponse response, @RequestBody DistrictIdInput input) throws IOException {
//        Long districtId = input.getDistrictId();
//        if (districtId == null || districtId == 0) {
//            return;
//        }
//        District district = districtService.getById(districtId);
//        if (district == null) {
//            return;
//        }
//
//        List<DistrictUnionInfoOutput> list = new ArrayList<DistrictUnionInfoOutput>();
//        DistrictUnionInfoOutput districtUnionInfoOutput = new DistrictUnionInfoOutput();
//        districtUnionInfoOutput.setId(district.getId());
//        districtUnionInfoOutput.setName(district.getDistrictName());
//        List<BuildingUnionInfoOutput> dropDownList = new ArrayList<BuildingUnionInfoOutput>();
//        QueryWrapper<Building> BuildingWrapper = WrapperUtils.getWrapper(false);
//        BuildingWrapper.eq("district_id", districtId);
//        BuildingWrapper.orderByAsc("id");
//        List<Building> buildingList = buildingService.list(BuildingWrapper);
//
//        if (buildingList != null && buildingList.size() > 0) {
//            // 查楼座
//            for (Building building : buildingList) {
//                BuildingUnionInfoOutput BuildingUnionInfoEntity = new BuildingUnionInfoOutput();
//                BuildingUnionInfoEntity.setId(building.getId());
//                BuildingUnionInfoEntity.setName(building.getName());
//                QueryWrapper<Floor> floorWrapper = WrapperUtils.getWrapper(false);
//                floorWrapper.eq("building_id", building.getId());
//                floorWrapper.orderByAsc("id");
//                List<Floor> floors = floorService.list(floorWrapper);
//                List<FloorUnionOutout> floorsOut = new ArrayList<FloorUnionOutout>();
//                for (Floor floor : floors) {// 查楼层
//                    FloorUnionOutout floorUnionOutout = new FloorUnionOutout();
//                    floorUnionOutout.setName(floor.getName());
//                    floorUnionOutout.setId(floor.getId());
//                    QueryWrapper<MultistageGrid> MultistageGridWrapper = WrapperUtils.getWrapper(false);
//                    MultistageGridWrapper.eq("floor_id", floor.getId());
//                    MultistageGridWrapper.orderByAsc("id");
//                    List<MultistageGrid> multistageGrids = multistageGridService.list(MultistageGridWrapper);
//                    List<MultistageGridOutput> multistageGridOutputs = new ArrayList<MultistageGridOutput>();
//                    if (multistageGrids != null && multistageGrids.size() > 0) {
//                        for (MultistageGrid multistageGrid : multistageGrids) {
//                            MultistageGridOutput multistageGridOutput = new MultistageGridOutput();
//                            multistageGridOutput.setId(multistageGrid.getId());
//                            multistageGridOutput.setName(multistageGrid.getName());
//                            QueryWrapper<Toilet> ToiletGridWrapper = WrapperUtils.getWrapper(false);
//                            ToiletGridWrapper.eq("multistage_grid_id", multistageGrid.getId());
//                            ToiletGridWrapper.orderByAsc("id");
//                            List<SuperiorScenesUnionOutput> superiorScenes = new ArrayList<SuperiorScenesUnionOutput>();
//                            List<Toilet> Toilets = toiletService.list(ToiletGridWrapper);
//                            if (StringUtil.isNotEmpty(Toilets)) {
//                                SuperiorScenesUnionOutput superiorScenesUnionOutput = new SuperiorScenesUnionOutput();
//                                for (Toilet toilet : Toilets) {
//                                    superiorScenesUnionOutput.setId(0L);
//                                    List<ScenesUnionOutput> toiletScenes = new ArrayList<ScenesUnionOutput>();
//                                    ScenesUnionOutput toiletUnionOutput = GetScenesOutput(toilet);
//                                    toiletScenes.add(toiletUnionOutput);
//                                    superiorScenesUnionOutput.setScenes(toiletScenes);
//                                    superiorScenes.add(superiorScenesUnionOutput);
//                                    //查2级场景
//                                    QueryWrapper<Positions> positionsWrapper = WrapperUtils.getWrapper(false);
//                                    positionsWrapper.eq("district_id", districtId);
//                                    positionsWrapper.eq("building_id", building.getId());
//                                    positionsWrapper.eq("floor_id", floor.getId());
//                                    positionsWrapper.eq("toilet_id", toilet.getId());
//                                    positionsWrapper.orderByAsc("id");
//                                    List<Positions> positionss = positionsService.list(positionsWrapper);
//                                    if (StringUtil.isNotEmpty(positionss)) {
//                                        SuperiorScenesUnionOutput toiletScenesUnionOutput = new SuperiorScenesUnionOutput();
//                                        toiletScenesUnionOutput.setId(toilet.getId());
//                                        toiletScenesUnionOutput.setName(toilet.getName());
//                                        List<ScenesUnionOutput> positionsScenes = new ArrayList<ScenesUnionOutput>();
//                                        for (Positions positions : positionss) {
//                                            ScenesUnionOutput positionsUnionOutput = GetScenesPosition(positions);
//                                            positionsScenes.add(positionsUnionOutput);
//                                        }
//                                        toiletScenesUnionOutput.setScenes(positionsScenes);
//                                        superiorScenes.add(toiletScenesUnionOutput);
//                                    }
//                                }
//                            }
//                            multistageGridOutput.setSuperiorScenes(superiorScenes);
//                            multistageGridOutputs.add(multistageGridOutput);
//                        }
//                    }
//
//                    MultistageGridOutput multistageGridOutput = new MultistageGridOutput();
//                    QueryWrapper<Toilet> toiletWrapper = WrapperUtils.getWrapper(false);
//                    toiletWrapper.eq("district_id", districtId);
//                    toiletWrapper.eq("building_id", building.getId());
//                    toiletWrapper.eq("floor_id", floor.getId());
//                    toiletWrapper.eq("multistage_grid_id", 0);
//                    toiletWrapper.orderByAsc("id");
//                    List<SuperiorScenesUnionOutput> superiorScenes = new ArrayList<SuperiorScenesUnionOutput>();
//                    List<Toilet> Toilets = toiletService.list(toiletWrapper);
//                    if (StringUtil.isNotEmpty(Toilets)) {
//                        for (Toilet toilet : Toilets) {
//                            SuperiorScenesUnionOutput superiorScenesUnionOutput = new SuperiorScenesUnionOutput();
//                            //装一遍自身
//                            superiorScenesUnionOutput.setId(0L);
//                            List<ScenesUnionOutput> toiletScenes = new ArrayList<ScenesUnionOutput>();
//                            ScenesUnionOutput toiletUnionOutput = GetScenesOutput(toilet);
//                            toiletScenes.add(toiletUnionOutput);
//                            superiorScenesUnionOutput.setScenes(toiletScenes);
//                            superiorScenes.add(superiorScenesUnionOutput);
//                            //查一级场景下的2级场景
//                            QueryWrapper<Positions> positionsWrapper = WrapperUtils.getWrapper(false);
//                            positionsWrapper.eq("district_id", districtId);
//                            positionsWrapper.eq("building_id", building.getId());
//                            positionsWrapper.eq("floor_id", floor.getId());
//                            positionsWrapper.eq("toilet_id", toilet.getId());
//                            positionsWrapper.eq("multistage_grid_id", 0);
//                            positionsWrapper.orderByAsc("id");
//                            List<Positions> positionss = positionsService.list(positionsWrapper);
//                            if (StringUtil.isNotEmpty(positionss)) {
//                                SuperiorScenesUnionOutput toiletScenesUnionOutput = new SuperiorScenesUnionOutput();
//                                toiletScenesUnionOutput.setId(toilet.getId());
//                                toiletScenesUnionOutput.setName(toilet.getName());
//                                List<ScenesUnionOutput> positionsScenes = new ArrayList<ScenesUnionOutput>();
//                                for (Positions positions : positionss) {
//                                    ScenesUnionOutput positionsUnionOutput = GetScenesPosition(positions);
//                                    positionsScenes.add(positionsUnionOutput);
//                                }
//                                toiletScenesUnionOutput.setScenes(positionsScenes);
//                                superiorScenes.add(toiletScenesUnionOutput);
//                            }
//                        }
//                        multistageGridOutput.setSuperiorScenes(superiorScenes);
//                        multistageGridOutputs.add(multistageGridOutput);
//                    }
//                    floorUnionOutout.setMultistageGrid(multistageGridOutputs);
//                    floorsOut.add(floorUnionOutout);
//                }
//                BuildingUnionInfoEntity.setFloor(floorsOut);
//                dropDownList.add(BuildingUnionInfoEntity);
//            }
//        }
//        districtUnionInfoOutput.setBuilding(dropDownList);
//        list.add(districtUnionInfoOutput);
//        Map<String, java.lang.Object> map = new HashMap<String, java.lang.Object>();
//        String fileTemplate = "./temp/sceneTemplate.xlsx";
//        File fileOut = new File(fileTemplate);
//        // 从jar里读取文件 然后建立临时文件模板 如果temp 目录已经有了就不读取了
//        if (!fileOut.exists()) {
//            File dirPath = new File("./temp");
//            if (!dirPath.exists()) {
//                dirPath.mkdir();
//            }
//            fileOut.createNewFile();// 将模板文件放到临时目录
//            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/sceneTemplate.xlsx");
//            FileOutputStream fos = new FileOutputStream(fileTemplate);
//            byte[] b = new byte[1024];
//            while ((inputStream.read(b)) != -1) {
//                fos.write(b);// 写入数据
//            }
//            inputStream.close();
//            fos.close();// 保存数据
//        }
//        TemplateExportParams params = new TemplateExportParams(fileTemplate);
//        params.setColForEach(true);
//        log.info("场景导出对象=" + JSON.toJSONString(list));
//        map.put("list", list);
//
//        Workbook workbook = ExcelExportUtil.exportExcel(params, map);
//        String fileName = "场景导出" + DateUtil.format(new Date(), "yyyMMddHHmmss") + ".xlsx";
//        response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "iso8859-1"));
//        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
//        response.setHeader("Pragma", "no-cache");
//        response.setHeader("Cache-Control", "no-cache");
//        response.setDateHeader("Expires", 0);
//        BufferedOutputStream bufferedOutPut = new BufferedOutputStream(response.getOutputStream());
//        workbook.write(bufferedOutPut);
//        bufferedOutPut.flush();
//        bufferedOutPut.close();
//    }
//
//




}
