package com.yfd.platform.modules.basedata.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yfd.platform.annotation.Log;
import com.yfd.platform.config.ResponseResult;
import com.yfd.platform.modules.basedata.domain.SubstationComponent;
import com.yfd.platform.modules.basedata.domain.SubstationDevice;
import com.yfd.platform.modules.basedata.domain.SubstationMaindevice;
import com.yfd.platform.modules.basedata.domain.TreeNode;
import com.yfd.platform.modules.basedata.service.ISubstationComponentService;
import com.yfd.platform.modules.basedata.service.ISubstationDeviceService;
import com.yfd.platform.modules.basedata.service.ISubstationMaindeviceService;
import com.yfd.platform.system.domain.SysDictionaryItems;
import com.yfd.platform.system.service.ISysDictionaryItemsService;
import com.yfd.platform.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 变电站_主设备 前端控制器
 * </p>
 *
 *
 * @since 2023-03-28
 */
@RestController
@RequestMapping("/basedata/substation-maindevice")
@Api(value = "SubstationMaindeviceController", tags = "主设备及部件")
public class SubstationMaindeviceController {

    @Resource
    private ISubstationMaindeviceService substationMaindeviceService;

    @Resource
    private ISubstationComponentService substationComponentService;

    @Resource
    private ISysDictionaryItemsService sysDictionaryItemsService;

    @Resource
    private ISubstationDeviceService substationDeviceService;

    @GetMapping("/getMainDeviceTree")
    @ApiOperation("获取主设备及部件树")
    @PreAuthorize("@el.check('select:maindevice')")
    public ResponseResult getMainDeviceTree(String bayId, String name) {
        List<Map<String, Object>> mainDeviceTree = substationMaindeviceService.getMainDeviceTree(bayId, name);
        return ResponseResult.successData(mainDeviceTree);
    }

    @Log(module = "主设备及部件", value = "新增主设备",type = "1")
    @PostMapping("/addMainDevice")
    @ApiOperation("新增主设备")
    @PreAuthorize("@el.check('add:maindevice')")
    public ResponseResult addMainDevice(SubstationMaindevice substationMaindevice) {
        String mainDeviceName = substationMaindevice.getMainDeviceName();
        String bayId = substationMaindevice.getBayId();
        int count =
                substationMaindeviceService.count(new LambdaQueryWrapper<SubstationMaindevice>().eq(SubstationMaindevice::getBayId, bayId).eq(SubstationMaindevice::getMainDeviceName, mainDeviceName));
        if (count > 0) {
            return ResponseResult.error("当前间隔下已经存在该主设备");
        }
        int count1 =
                substationMaindeviceService.count(new LambdaQueryWrapper<SubstationMaindevice>().eq(SubstationMaindevice::getBayId, bayId)) + 1;
        substationMaindevice.setCustom1(count1);
        substationMaindevice.setDatastatus("1");
        substationMaindevice.setLastmodifier(SecurityUtils.getCurrentUsername());
        substationMaindevice.setLastmodifydate(LocalDateTime.now());
        boolean ok = substationMaindeviceService.save(substationMaindevice);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error();
        }
    }

    @GetMapping("/getMainDeviceById")
    @ApiOperation("根据Id获取主设备")
    public ResponseResult getMainDeviceById(String id) {
        if (StrUtil.isBlank(id)) {
            return ResponseResult.error("参数为空");
        }
        SubstationMaindevice substationMaindevice = substationMaindeviceService.getById(id);
        return ResponseResult.successData(substationMaindevice);
    }

    @GetMapping("/getMainDevice")
    @ApiOperation("根据条件获取主设备")
    public ResponseResult getMainDevice(String stationCode, String areaId, String bayId, String mainDeviceName,
                                        String deviceType) {
        LambdaQueryWrapper<SubstationMaindevice> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(stationCode)) {
            queryWrapper.like(SubstationMaindevice::getStationCode, stationCode);
        }
        if (StrUtil.isNotBlank(areaId)) {
            queryWrapper.eq(SubstationMaindevice::getAreaId, areaId);
        }
        if (StrUtil.isNotBlank(bayId)) {
            queryWrapper.like(SubstationMaindevice::getBayId, bayId);
        }
        // 主设备名称
        if (StrUtil.isNotBlank(mainDeviceName)) {
            queryWrapper.like(SubstationMaindevice::getMainDeviceName, mainDeviceName);
        }
        // 主设备类型
        if (StrUtil.isNotBlank(deviceType)) {
            queryWrapper.eq(SubstationMaindevice::getDeviceType, deviceType);
        }
        queryWrapper.eq(SubstationMaindevice::getDatastatus, "1").orderByAsc(SubstationMaindevice::getCustom1);
        List<Map<String, Object>> list = substationMaindeviceService.listMaps(queryWrapper);
        return ResponseResult.successData(list);
    }

    @PostMapping("/getMainDevicePage")
    @ApiOperation("根据条件获取主设备(分页)")
    public ResponseResult getMainDevicePage(@RequestBody String param) {
        JSONObject jsonObject = JSONUtil.parseObj(param);
        Page<Map<String, Object>> page = new Page<>();
        page.setCurrent(jsonObject.getInt("current"));
        page.setSize(jsonObject.getInt("size"));
        String stationCode = jsonObject.getStr("stationCode");
        String areaId = jsonObject.getStr("areaId");
        String bayId = jsonObject.getStr("bayId");
        String mainDeviceName = jsonObject.getStr("mainDeviceName");
        String deviceType = jsonObject.getStr("deviceType");
        String ids = jsonObject.getStr("ids");

        LambdaQueryWrapper<SubstationMaindevice> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(stationCode)) {
            queryWrapper.like(SubstationMaindevice::getStationCode, stationCode);
        }
        if (StrUtil.isNotBlank(areaId)) {
            queryWrapper.eq(SubstationMaindevice::getAreaId, areaId);
        }
        if (StrUtil.isNotBlank(ids)) {
            String[] split = ids.split(",");
            queryWrapper.notIn(SubstationMaindevice::getMainDeviceId, Arrays.asList(split));
        }
        if (StrUtil.isNotBlank(bayId)) {
            queryWrapper.like(SubstationMaindevice::getBayId, bayId);
        }
        // 主设备名称
        if (StrUtil.isNotBlank(mainDeviceName)) {
            queryWrapper.like(SubstationMaindevice::getMainDeviceName, mainDeviceName);
        }
        // 主设备类型
        if (StrUtil.isNotBlank(deviceType)) {
            queryWrapper.eq(SubstationMaindevice::getDeviceType, deviceType);
        }
        queryWrapper.eq(SubstationMaindevice::getDatastatus, "1");
        Page<Map<String, Object>> mapPage = substationMaindeviceService.pageMaps(page, queryWrapper);
        return ResponseResult.successData(mapPage);
    }

    @GetMapping("/getComponentByBay")
    @ApiOperation("根据条件获取部件")
    public ResponseResult getComponentByBay(String stationCode, String areaId, String bayId, String componentName,
                                            String mainDeviceId) {

        LambdaQueryWrapper<SubstationComponent> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(stationCode)) {
            queryWrapper.eq(SubstationComponent::getStationCode, stationCode);
        }
        if (StrUtil.isNotBlank(areaId)) {
            queryWrapper.eq(SubstationComponent::getAreaId, areaId);
        }
        if (StrUtil.isNotBlank(bayId)) {
            queryWrapper.eq(SubstationComponent::getBayId, bayId);
        }
        // 部件名称
        if (StrUtil.isNotBlank(componentName)) {
            queryWrapper.like(SubstationComponent::getComponentName, componentName);
        }
        // 主设备类型
        if (StrUtil.isNotBlank(mainDeviceId)) {
            queryWrapper.eq(SubstationComponent::getMainDeviceId, mainDeviceId);
        }
        queryWrapper.eq(SubstationComponent::getDatastatus, "1").orderByAsc(SubstationComponent::getCustom1);
        List<Map<String, Object>> list = substationComponentService.listMaps(queryWrapper);
        return ResponseResult.successData(list);
    }

    @PostMapping("/getComponentByBayPage")
    @ApiOperation("根据条件获取部件(分页)")
    public ResponseResult getComponentByBayPage(@RequestBody String param) {

        //        Page<Map<String, Object>> page, String stationCode, String areaId,
        //                String bayId, String componentName, String mainDeviceId, String ids
        JSONObject jsonObject = JSONUtil.parseObj(param);
        Page<Map<String, Object>> page = new Page<>();
        page.setCurrent(jsonObject.getInt("current"));
        page.setSize(jsonObject.getInt("size"));
        String stationCode = jsonObject.getStr("stationCode");
        String areaId = jsonObject.getStr("areaId");
        String bayId = jsonObject.getStr("bayId");
        String componentName = jsonObject.getStr("componentName");
        String mainDeviceId = jsonObject.getStr("mainDeviceId");
        String ids = jsonObject.getStr("ids");
        LambdaQueryWrapper<SubstationComponent> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(stationCode)) {
            queryWrapper.like(SubstationComponent::getStationCode, stationCode);
        }
        if (StrUtil.isNotBlank(areaId)) {
            queryWrapper.like(SubstationComponent::getAreaId, areaId);
        }
        if (StrUtil.isNotBlank(bayId)) {
            queryWrapper.like(SubstationComponent::getBayId, bayId);
        }
        // 部件名称
        if (StrUtil.isNotBlank(componentName)) {
            queryWrapper.like(SubstationComponent::getComponentName, componentName);
        }
        if (StrUtil.isNotBlank(ids)) {
            String[] split = ids.split(",");
            queryWrapper.notIn(SubstationComponent::getComponentId, Arrays.asList(split));
        }
        // 主设备类型
        if (StrUtil.isNotBlank(mainDeviceId)) {
            queryWrapper.eq(SubstationComponent::getMainDeviceId, mainDeviceId);
        }
        queryWrapper.eq(SubstationComponent::getDatastatus, "1");
        Page<Map<String, Object>> mapPage = substationComponentService.pageMaps(page, queryWrapper);
        return ResponseResult.successData(mapPage);
    }

    @PostMapping("/getComponentPage")
    @ApiOperation("获取没有绑定(分页)")
    public ResponseResult getComponentByBayPage(Page<Map<String, Object>> page, String algorithmId,
                                                String stationCode, String areaId,
                                                String bayId, String mainDeviceId, String componentName) {
        Page<Map<String, Object>> mapPage = substationComponentService.getComponentByBayPage(page, algorithmId,
                stationCode, areaId, bayId, mainDeviceId,
                componentName);
        return ResponseResult.successData(mapPage);
    }

    @GetMapping("/getMainDeviceType")
    @ApiOperation("获取当前主设备类型")
    public ResponseResult getMainDeviceType(String deviceType) {
        SysDictionaryItems sysDictionaryItems = substationMaindeviceService.getMainDeviceType(deviceType);
        return ResponseResult.successData(sysDictionaryItems);
    }

    @GetMapping("/getComponent")
    @ApiOperation("获取部件")
    public ResponseResult getComponent(String mainDeviceId,String bayId,String componentName) {
        List<Map<String, Object>> list = substationMaindeviceService.getComponent(mainDeviceId,bayId,componentName);
        return ResponseResult.successData(list);
    }

    @GetMapping("/getComponentByBayId")
    @ApiOperation("获取间隔下的部件")
    public ResponseResult getComponentByBayId(String bayId) {
        List<Map<String, Object>> list = substationMaindeviceService.getComponentByBay(bayId);
        return ResponseResult.successData(list);
    }

    @GetMapping("/getDeviceType")
    @ApiOperation("获取主设备类型集合")
    public ResponseResult getDeviceType() {
        List<Map<String, Object>> listItems = substationMaindeviceService.getDeviceType();
        return ResponseResult.successData(listItems);
    }

    @Log(module = "主设备及部件", value = "修改主设备",type = "1")
    @PostMapping("/updateMainDevice")
    @ApiOperation("修改主设备")
    @PreAuthorize("@el.check('update:maindevice')")
    public ResponseResult updateMainDevice(SubstationMaindevice substationMaindevice) {
        if (substationMaindevice == null) {
            return ResponseResult.error("参数为空");
        }
        String mainDeviceId = substationMaindevice.getMainDeviceId();
        String bayId = substationMaindevice.getBayId();
        String mainDeviceName = substationMaindevice.getMainDeviceName();
        LambdaQueryWrapper<SubstationMaindevice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SubstationMaindevice::getBayId, bayId).eq(SubstationMaindevice::getMainDeviceName,
                mainDeviceName).ne(SubstationMaindevice::getMainDeviceId, mainDeviceId);
        int count = substationMaindeviceService.count(queryWrapper);
        if (count > 0) {
            return ResponseResult.error("当前间隔下已经存在该主设备");
        }
        int count2 =
                substationDeviceService.count(new LambdaQueryWrapper<SubstationDevice>().eq(SubstationDevice::getMainDeviceId, mainDeviceId));
        if (count2 > 0) {
            return ResponseResult.error("当前主设备有点位关联不能修改");
        }
        substationMaindevice.setLastmodifier(SecurityUtils.getCurrentUsername());
        substationMaindevice.setLastmodifydate(LocalDateTime.now());
        boolean ok = substationMaindeviceService.updateById(substationMaindevice);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error();
        }
    }

    @Log(module = "主设备及部件", value = "修改主设备状态",type = "1")
    @PostMapping("/setMainDeviceStatus")
    @ApiOperation("修改主设备状态")
    public ResponseResult setMainDeviceStatus(String id, String dataStatus) {
        boolean ok = substationMaindeviceService.setMainDeviceStatus(id, dataStatus);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error("修改失败");
        }

    }

    @Log(module = "主设备及部件", value = "删除主设备",type = "1")
    @PostMapping("/deleteMainDevice")
    @ApiOperation("删除主设备")
    @PreAuthorize("@el.check('del:maindevice')")
    public ResponseResult deleteMainDevice(String id) {
        boolean ok = substationMaindeviceService.deleteMainDevice(id);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error("删除失败");
        }
    }

    @Log(module = "主设备及部件", value = "新增部件",type = "1")
    @PostMapping("/addComponent")
    @ApiOperation("新增部件")
    public ResponseResult addComponent(SubstationComponent substationComponent) {
        String mainDeviceId = substationComponent.getMainDeviceId();
        String componentName = substationComponent.getComponentName();
        int count =
                substationComponentService.count(new LambdaQueryWrapper<SubstationComponent>().eq(SubstationComponent::getMainDeviceId, mainDeviceId).eq(SubstationComponent::getComponentName, componentName));
        if (count > 0) {
            return ResponseResult.error("当前主设备下已经存在该部件");
        }
        int count1 =
                substationComponentService.count(new LambdaQueryWrapper<SubstationComponent>().eq(SubstationComponent::getBayId, mainDeviceId)) + 1;
        substationComponent.setCustom1(count1);
        boolean ok = substationMaindeviceService.addComponent(substationComponent);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error();
        }
    }

    @GetMapping("/getComponentById")
    @ApiOperation("根据Id获取部件")
    public ResponseResult getComponentById(String componentId) {
        SubstationComponent substationComponent = substationMaindeviceService.getComponentById(componentId);
        return ResponseResult.successData(substationComponent);
    }

    @Log(module = "主设备及部件", value = "修改部件",type = "1")
    @PostMapping("/updateComponent")
    @ApiOperation("修改部件")
    public ResponseResult updateComponent(SubstationComponent substationComponent) {
        String mainDeviceId = substationComponent.getMainDeviceId();
        String componentName = substationComponent.getComponentName();
        String componentId = substationComponent.getComponentId();
        int count =
                substationComponentService.count(new LambdaQueryWrapper<SubstationComponent>().eq(SubstationComponent::getMainDeviceId, mainDeviceId).eq(SubstationComponent::getComponentName, componentName).ne(SubstationComponent::getComponentId, componentId));
        if (count > 0) {
            return ResponseResult.error("当前主设备下已经存在该部件");
        }
        int count2 =
                substationDeviceService.count(new LambdaQueryWrapper<SubstationDevice>().eq(SubstationDevice::getComponentId, componentId));
        if (count2 > 0) {
            return ResponseResult.error("当前部件有点位关联不能修改");
        }
        boolean ok = substationMaindeviceService.updateComponent(substationComponent);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error("修改失败");
        }
    }

    @Log(module = "主设备及部件", value = "修改部件状态",type = "1")
    @PostMapping("/setComponentStatus")
    @ApiOperation("修改部件状态")
    public ResponseResult setComponentStatus(String componentId, String dataStatus) {
        boolean ok = substationMaindeviceService.setComponentStatus(componentId, dataStatus);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error("修改失败");
        }
    }

    @Log(module = "主设备及部件", value = "删除部件",type = "1")
    @PostMapping("/deleteComponent")
    @ApiOperation("删除部件")
    public ResponseResult deleteComponent(String componentId) {
        boolean ok = substationMaindeviceService.deleteComponent(componentId);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error("删除失败");
        }
    }

    @PostMapping("/uploadFile")
    @ApiOperation("导入文件")
    public ResponseResult uploadFile(MultipartFile file, String type) throws Exception {
        String str = substationMaindeviceService.uploadExcel(file, type);
        if (StrUtil.isBlank(str)) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error();
        }
    }

    @GetMapping("/getMainDeviceNumber")
    @ApiOperation("查询主设备个数")
    public ResponseResult getMainDeviceNumber(String stationCode) {
        LambdaQueryWrapper<SubstationMaindevice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SubstationMaindevice::getStationCode, stationCode).eq(SubstationMaindevice::getDatastatus, "1");
        List<SubstationMaindevice> list = substationMaindeviceService.list(queryWrapper);
        Map<String, List<SubstationMaindevice>> collect =
                list.stream().filter(s -> StrUtil.isNotBlank(s.getDeviceType())).collect(Collectors.groupingBy(SubstationMaindevice::getDeviceType));
        Map<String, Object> mainDevice = new HashMap<>();
        List<Map<String, Object>> equipmentType = sysDictionaryItemsService.getDeviceByType("EquipmentType");
        String[] mainArray = {"1", "2", "3", "4", "6", "7", "8", "9", "10"};
        List<String> mainList = Arrays.asList(mainArray);
        for (Map<String, Object> map : equipmentType) {
            String itemcode = map.get("itemcode").toString();
            if (!mainList.contains(itemcode)) {
                continue;
            }
            int count = 0;
            for (String type : collect.keySet()) {
                List<SubstationMaindevice> substationMaindevices = collect.get(type);
                if (type.equals(itemcode)) {
                    count = substationMaindevices.size();
                    break;
                }
            }
            String custom2 = map.get("custom2").toString();
            mainDevice.put(custom2, count);
        }
        return ResponseResult.successData(mainDevice);
    }

    @ApiOperation("获取主设备导航树")
    @GetMapping("/getSubstationMainDeviceTree")
    public ResponseResult getSubstationMainDeviceTree(String stationCode,String mainDeviceName) {
        List<Map<String, Object>> mainDeviceTree = substationMaindeviceService.getSubstationMainDeviceTree(stationCode,mainDeviceName);
        return ResponseResult.successData(mainDeviceTree);
    }

    @GetMapping("/getSubstationMainTree")
    @ApiOperation("获取主设备树（前台）")
    public ResponseResult getSubstationMainTree(String stationCode, String mainDeviceName) {
        TreeNode treeNode = substationMaindeviceService.getSubstationMainTree(stationCode, mainDeviceName);
        return ResponseResult.successData(treeNode);
    }

    @GetMapping("/getDeviceSignalTree")
    @ApiOperation("获取信号树（前台）")
    public ResponseResult getDeviceSignalTree(String stationCode,String signalName) {
        List<TreeNode> treeNodes = substationMaindeviceService.getDeviceSignalTree(stationCode,signalName);
        return ResponseResult.successData(treeNodes);
    }
    @GetMapping("/getComponentTree")
    @ApiOperation("获取部件树（前台）")
    public ResponseResult getComponentTree(String stationCode,String componentName) {
        List<TreeNode> treeNodes = substationMaindeviceService.getComponentTree(stationCode,componentName);
        return ResponseResult.successData(treeNodes);
    }
}
