package com.example.zxweb.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.zxweb.common.api.vo.Result;
import com.example.zxweb.entity.ZxCelue;
import com.example.zxweb.entity.ZxDevice;
import com.example.zxweb.service.IZxCelueService;
import com.example.zxweb.service.IZxDeviceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description 设备管理接口
 * @Author ZhouWenTao
 * @Date 2023/9/14 9:16
 */
@Api(tags = "设备管理")
@RequestMapping("/device")
@RestController
public class DeviceController {
    @Resource
    IZxDeviceService zxDeviceService;

    @ApiOperation(value = "设备列表")
    @GetMapping(value = "/listAll")
    public Result<?> listAll(){
        LambdaQueryWrapper<ZxDevice> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.isNotNull(ZxDevice::getSerial);
        queryWrapper.isNotNull(ZxDevice::getTerminalName);
        queryWrapper.in(ZxDevice::getType,"开关插座设备组","照明设备组");
        List<ZxDevice> list = zxDeviceService.list(queryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            return Result.OK(new ArrayList<>());
        }
        JSONArray allList=new JSONArray();
        Map<String,List<JSONObject>> map=new LinkedHashMap<>();
        for (ZxDevice zxDevice : list) {
            String type = zxDevice.getType();
            List<JSONObject> mapOrDefault = map.getOrDefault(type, new ArrayList<>());
            JSONObject jo=new JSONObject();
            jo.put("id",zxDevice.getSerial());
            jo.put("text",zxDevice.getTerminalName());
            mapOrDefault.add(jo);
            map.put(type,mapOrDefault);
        }
        for (String key : map.keySet()) {
            JSONObject jo=new JSONObject();
            jo.put("text",key);
            jo.put("children",map.get(key));
            allList.add(jo);
        }
        return Result.OK(allList);
    }


}
