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

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yfd.platform.annotation.Log;
import com.yfd.platform.component.nettyserver.NettyServerHandler;
import com.yfd.platform.config.ResponseResult;
import com.yfd.platform.modules.basedata.domain.*;
import com.yfd.platform.modules.basedata.service.*;
import com.yfd.platform.system.domain.SysUser;
import com.yfd.platform.system.service.ISysOrganizationService;
import com.yfd.platform.system.service.IUserService;
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.io.FileNotFoundException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * <p>
 * 变电站 前端控制器
 * </p>
 *
 *
 * @since 2023-03-28
 */
@RestController
@RequestMapping("/basedata/substation")
@Api(value = "SubstationController", tags = "变电站")
public class SubstationController {

    @Resource
    private ISubstationService substationService;

    @Resource
    private ISubstationAreaService substationAreaService;

    @Resource
    private ISubstationBayService substationBayService;

    @Resource
    private ISubstationPatroldeviceService substationPatroldeviceService;

    @Resource
    private ISubstationMaindeviceService substationMaindeviceService;

    @Resource
    private ISubstationDeviceService substationDeviceService;

    @Resource
    private ISysOrganizationService sysOrganizationService;

    @Resource
    private IUserService userService;

    @Resource
    NettyServerHandler nettyServerHandler;

    @ApiOperation("获取变电站树")
    @GetMapping("/getSubstationBayTree")
    @PreAuthorize("@el.check('select:substation')")
    public ResponseResult getSubstationBayTree(String name) {
        SysUser userInfo = userService.getUserInfo();
        Set<String> orgCodeByUser = sysOrganizationService.getOrgCodeByUser(userInfo.getId());
        List<Map<String, Object>> substationTree = substationService.getSubstationBayTree(name, orgCodeByUser);
        return ResponseResult.successData(substationTree);
    }

    @ApiOperation("获取变电站下拉列表")
    @GetMapping("/getSubstationList")
    public ResponseResult getSubstationList(String flag) {
        SysUser userInfo = userService.getUserInfo();
        Integer usertype = userInfo.getUsertype();
        LambdaQueryWrapper<Substation> queryWrapper = new LambdaQueryWrapper<>();
        if (usertype != 0) {
            Set<String> orgCodeByUser = sysOrganizationService.getOrgCodeByUser(userInfo.getId());
            if (orgCodeByUser == null || orgCodeByUser.size() == 0) {
                return ResponseResult.successData(null);
            } else {
                queryWrapper.in(Substation::getStationCode, orgCodeByUser);
            }
        }
        if (StrUtil.isNotBlank(flag)) {
            queryWrapper.eq(Substation::getIsStationFlag, flag);
        }
        queryWrapper.eq(Substation::getDatastatus, "1").select(Substation::getStationId, Substation::getStationCode,
                Substation::getStationName).orderByAsc(Substation::getCustom1);
        List<Map<String, Object>> listMaps = substationService.listMaps(queryWrapper);
        return ResponseResult.successData(listMaps);
    }

    @ApiOperation("获取所有变电站")
    @GetMapping("/getAllSubstationList")
    public ResponseResult getAllSubstationList(String flag) {
        LambdaQueryWrapper<Substation> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(flag)) {
            queryWrapper.eq(Substation::getIsStationFlag, flag);
        }
        queryWrapper.eq(Substation::getDatastatus, "1").select(Substation::getStationId, Substation::getStationCode,
                Substation::getStationName,Substation::getCoordinate).orderByAsc(Substation::getCustom1);
        List<Map<String, Object>> listMaps = substationService.listMaps(queryWrapper);
        return ResponseResult.successData(listMaps);
    }


    @ApiOperation("获取变电站下的区域")
    @GetMapping("/getSubstationAreaByCode")
    public ResponseResult getSubstationAreaByCode(String stationCode) {
        if (StrUtil.isBlank(stationCode)) {
            return ResponseResult.error("参数为空");
        }
        LambdaQueryWrapper<SubstationArea> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SubstationArea::getStationCode, stationCode).eq(SubstationArea::getDatastatus, "1").select(SubstationArea::getStationCode,SubstationArea::getStationName,SubstationArea::getAreaId,SubstationArea::getAreaName);
        List<Map<String, Object>> list = substationAreaService.listMaps(queryWrapper);
        return ResponseResult.successData(list);
    }

    @ApiOperation("获取变电站区域间隔导航树")
    @GetMapping("/getSubstationTree")
    public ResponseResult getSubstationTree(String stationId) {
        List<Map<String, Object>> substationTree = substationService.getSubstationTree(stationId);
        return ResponseResult.successData(substationTree);
    }

    @ApiOperation("获取变电站区域导航树")
    @GetMapping("/getSubstationAreaTree")
    public ResponseResult getSubstationAreaTree(String stationId) {
        List<Map<String, Object>> substationTree = substationService.getSubstationAreaTree(stationId);
        return ResponseResult.successData(substationTree);
    }

    @ApiOperation("获取区域下所有间隔")
    @GetMapping("/getSubstationBayByArea")
    public ResponseResult getSubstationBayByArea(String stationCode, String areaId, String bayName) {
        List<Map<String, Object>> substationBayList = substationService.getSubstationBayByArea(stationCode,areaId, bayName);
        return ResponseResult.successData(substationBayList);
    }

    @Log(module = "变电站区域间隔", value = "修改变电站",type = "1")
    @ApiOperation("修改变电站")
    @PostMapping("/updateSubstation")
    public ResponseResult updateSubstation(@RequestBody Substation substation) {
        if (substation == null) {
            return ResponseResult.error("参数为空");
        }
        boolean ok = substationService.updateSubstation(substation);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error("修改失败");
        }
    }

    @Log(module = "变电站区域间隔", value = "修改变电站状态",type = "1")
    @ApiOperation("修改变电站状态")
    @PostMapping("/setSubstationStatus")
    public ResponseResult setSubstationStatus(String stationId, String dataStatus) {
        boolean ok = substationService.setSubstationStatus(stationId, dataStatus);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error("修改失败");
        }
    }

    @Log(module = "变电站区域间隔", value = "修改区域状态",type = "1")
    @ApiOperation("修改区域状态")
    @PostMapping("/setSubstationAreaStatus")
    public ResponseResult setSubstationAreaStatus(String areaId, String dataStatus) {
        boolean ok = substationService.setSubstationAreaStatus(areaId, dataStatus);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error("修改失败");
        }
    }

    @Log(module = "变电站区域间隔", value = "修改间隔状态",type = "1")
    @ApiOperation("修改间隔状态")
    @PostMapping("/setSubstationBayStatus")
    public ResponseResult setSubstationBayStatus(String bayId, String dataStatus) {
        boolean ok = substationService.setSubstationBayStatus(bayId, dataStatus);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error("修改失败");
        }
    }

    @Log(module = "变电站区域间隔", value = "删除变电站",type = "1")
    @ApiOperation("删除变电站")
    @PostMapping("/deleteSubstation")
    public ResponseResult deleteSubstation(@RequestParam String stationId) {

        if (StrUtil.isBlank(stationId)) {
            return ResponseResult.error("参数为空");
        }
        boolean ok = substationService.deleteSubstation(stationId);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error("删除失败");
        }
    }

    @Log(module = "变电站区域间隔", value = "删除区域",type = "1")
    @ApiOperation("删除区域")
    @PostMapping("/deleteSubstationArea")
    public ResponseResult deleteSubstationArea(@RequestParam String areaId) {

        if (StrUtil.isBlank(areaId)) {
            return ResponseResult.error("参数为空");
        }
        boolean ok = substationService.deleteSubstationArea(areaId);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error("删除失败");
        }
    }

    @Log(module = "变电站区域间隔", value = "删除间隔",type = "1")
    @ApiOperation("删除间隔")
    @PostMapping("/deleteSubstationBay")
    public ResponseResult deleteSubstationBay(@RequestParam String bayId) {

        if (StrUtil.isBlank(bayId)) {
            return ResponseResult.error("参数为空");
        }
        boolean ok = substationService.deleteSubstationBay(bayId);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error("删除失败");
        }
    }

    @Log(module = "变电站区域间隔", value = "修改变电站",type = "1")
    @ApiOperation("修改变电站(暂时)")
    @PostMapping("/updateSubstation_bak")
    public ResponseResult updateSubstation_bak(@RequestBody Substation substation) {
        if (substation == null) {
            return ResponseResult.error("参数为空");
        }
        String username = userService.getUsername();
        substation.setLastmodifier(username);
        substation.setLastmodifydate(LocalDateTime.now());
        boolean ok = substationService.updateById(substation);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error("修改失败");
        }
    }

    @Log(module = "变电站区域间隔", value = "修改变电站",type = "1")
    @ApiOperation("根据id查询变电站(暂时)")
    @PostMapping("/getSubstationById")
    public ResponseResult getSubstationById(String stationId) {
        if (StrUtil.isBlank(stationId)) {
            return ResponseResult.error("参数为空");
        }
        Substation substation = substationService.getById(stationId);
        return ResponseResult.successData(substation);
    }

    @Log(module = "变电站区域间隔", value = "修改区域",type = "1")
    @ApiOperation("修改区域")
    @PostMapping("/updateSubstationArea")
    public ResponseResult updateSubstationArea(@RequestBody SubstationArea substationArea) {
        if (substationArea == null) {
            return ResponseResult.error("参数为空");
        }
        String areaName = substationArea.getAreaName();
        String areaId = substationArea.getAreaId();
        String stationCode = substationArea.getStationCode();
        LambdaQueryWrapper<SubstationArea> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SubstationArea::getStationCode, stationCode).eq(SubstationArea::getAreaName, areaName).ne(SubstationArea::getAreaId, areaId);
        int count = substationAreaService.count(queryWrapper);
        if (count > 0) {
            return ResponseResult.error("变电站下已经存在该区域");
        }
        LambdaQueryWrapper<SubstationBay> bayQueryWrapper = new LambdaQueryWrapper<>();
        bayQueryWrapper.eq(SubstationBay::getAreaId, areaId);
        int count1 = substationBayService.count(bayQueryWrapper);
        if (count1 > 0) {
            return ResponseResult.error("当前区域有间隔关联不能修改");
        }
        int count2 =
                substationPatroldeviceService.count(new LambdaQueryWrapper<SubstationPatroldevice>().eq(SubstationPatroldevice::getAreaId, areaId));
        if (count2 > 0) {
            return ResponseResult.error("当前区域有巡视设备关联不能修改");
        }
        substationArea.setLastmodifier(SecurityUtils.getCurrentUsername());
        substationArea.setLastmodifydate(LocalDateTime.now());
        boolean ok = substationAreaService.updateById(substationArea);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error("修改失败");
        }
    }

    @Log(module = "变电站区域间隔", value = "修改间隔",type = "1")
    @ApiOperation("修改间隔")
    @PostMapping("/updateSubstationBay")
    public ResponseResult updateSubstationBay(@RequestBody SubstationBay substationBay) {
        if (substationBay == null) {
            return ResponseResult.error("参数为空");
        }
        String bayName = substationBay.getBayName();
        String areaId = substationBay.getAreaId();
        String bayId = substationBay.getBayId();
        LambdaQueryWrapper<SubstationBay> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SubstationBay::getAreaId, areaId).eq(SubstationBay::getBayName, bayName).ne(SubstationBay::getBayId, bayId);
        int count = substationBayService.count(queryWrapper);
        if (count > 0) {
            return ResponseResult.error("区域下已经存在该间隔");
        }
        LambdaQueryWrapper<SubstationMaindevice> mainQueryWrapper = new LambdaQueryWrapper<>();
        mainQueryWrapper.eq(SubstationMaindevice::getBayId, bayId);
        int count1 = substationMaindeviceService.count(mainQueryWrapper);
        if (count1 > 0) {
            return ResponseResult.error("当前间隔有主设备关联不能修改");
        }
        int count2 =
                substationDeviceService.count(new LambdaQueryWrapper<SubstationDevice>().eq(SubstationDevice::getBayId, bayId));
        if (count2 > 0) {
            return ResponseResult.error("当前间隔有点位关联不能修改");
        }
        substationBay.setLastmodifier(SecurityUtils.getCurrentUsername());
        substationBay.setLastmodifydate(LocalDateTime.now());
        boolean ok = substationBayService.updateById(substationBay);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error("修改失败");
        }
    }

    @Log(module = "变电站区域间隔", value = "新增变电站",type = "1")
    @ApiOperation("新增变电站")
    @PostMapping("/addSubstation")
    public ResponseResult addSubstation(@RequestBody Substation substation) {
        if (substation == null) {
            return ResponseResult.error("参数为空");
        }
        String isStationFlag = substation.getIsStationFlag();
        if (StrUtil.isBlank(isStationFlag)) {
            substation.setIsStationFlag("0");
        }
        String stationCode = substation.getStationCode();
        LambdaQueryWrapper<Substation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Substation::getStationCode, stationCode).or().eq(Substation::getNodeId, substation.getNodeId());
        int count = substationService.count(queryWrapper);
        if (count > 0) {
            return ResponseResult.error("当前变电站编号或节点已经存在");
        }
        int count1 = substationService.count() + 1;
        substation.setCustom1(count1);
        substation.setLastmodifier(SecurityUtils.getCurrentUsername());
        substation.setLastmodifydate(LocalDateTime.now());
        substation.setDatastatus("1");
        boolean ok = substationService.save(substation);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error("新增失败");
        }
    }

    @Log(module = "变电站区域间隔", value = "新增区域",type = "1")
    @ApiOperation("新增区域")
    @PostMapping("/addSubstationArea")
    public ResponseResult addSubstationArea(@RequestBody SubstationArea substationArea) {
        if (substationArea == null) {
            return ResponseResult.error("参数为空");
        }
        String stationCode = substationArea.getStationCode();
        String areaName = substationArea.getAreaName();
        LambdaQueryWrapper<SubstationArea> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SubstationArea::getStationCode, stationCode).eq(SubstationArea::getAreaName, areaName);
        int count = substationAreaService.count(queryWrapper);
        if (count > 0) {
            return ResponseResult.error("当前区域已经存在");
        }
        int count1 =
                substationAreaService.count(new LambdaQueryWrapper<SubstationArea>().eq(SubstationArea::getStationCode, stationCode).orderByAsc(SubstationArea::getCustom1)) + 1;
        substationArea.setCustom1(count1);
        substationArea.setLastmodifier(SecurityUtils.getCurrentUsername());
        substationArea.setLastmodifydate(LocalDateTime.now());
        substationArea.setDatastatus("1");
        boolean ok = substationAreaService.save(substationArea);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error("新增失败");
        }
    }

    @Log(module = "变电站区域间隔", value = "新增间隔",type = "1")
    @ApiOperation("新增间隔")
    @PostMapping("/addSubstationBay")
    public ResponseResult addSubstationBay(@RequestBody SubstationBay substationBay) {
        if (substationBay == null) {
            return ResponseResult.error("参数为空");
        }
        String bayAreaName = substationBay.getAreaName();
        String bayName = substationBay.getBayName();
        String areaId = substationBay.getAreaId();
        LambdaQueryWrapper<SubstationBay> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SubstationBay::getAreaName, bayAreaName).eq(SubstationBay::getBayName, bayName);
        int count = substationBayService.count(queryWrapper);
        if (count > 0) {
            return ResponseResult.error("当前间隔已经存在");
        }
        int count1 =
                substationBayService.count(new LambdaQueryWrapper<SubstationBay>().eq(SubstationBay::getAreaId,
                        areaId).orderByAsc(SubstationBay::getCustom1)) + 1;
        substationBay.setCustom1(count1);
        substationBay.setLastmodifier(SecurityUtils.getCurrentUsername());
        substationBay.setLastmodifydate(LocalDateTime.now());
        substationBay.setDatastatus("1");
        boolean ok = substationBayService.save(substationBay);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error("新增失败");
        }
    }

    @Log(module = "变电站区域间隔", value = "上传图片",type = "1")
    @PostMapping("/uploadImage")
    @ApiOperation("上传图片")
    @ResponseBody
    public ResponseResult uploadImage(MultipartFile image) throws FileNotFoundException {
        if (image.isEmpty()) {
           return ResponseResult.error("文件是空的");
        }
        String filename = image.getOriginalFilename();
        String suffix = StrUtil.subAfter(filename, ".", true).toLowerCase();
        if (!"png".equals(suffix) && !"jpg".equals(suffix) && !"gif".equals(suffix)) {
            return ResponseResult.error("非法文件类型");
        }
        String contentType = image.getContentType();
        if (!"image/jpeg".equals(contentType) && !"image/png".equals(contentType)&& !"image/gif".equals(contentType)) {
            return ResponseResult.error("非法文件内容");
        }
        String fileName = substationService.uploadIcon(image);
        return ResponseResult.successData(fileName);
    }

    @Log(module = "变电站区域间隔", value = "删除图片",type = "1")
    @PostMapping("/deleteImage")
    @ApiOperation("删除图片")
    @ResponseBody
    public ResponseResult deleteImage(String id, String filename) throws FileNotFoundException {

        boolean ok = substationService.deleteImage(id, filename);
        if (ok) {
            return ResponseResult.successData(true);
        } else {
            return ResponseResult.error();
        }

    }

    @PostMapping("/cancelImage")
    @ApiOperation("取消修改")
    @ResponseBody
    public ResponseResult cancelImage(String id, String images) throws FileNotFoundException {
        boolean ok = substationService.cancelImage(id, images);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error();
        }

    }

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

    @GetMapping("/getStationOnline")
    @ApiOperation("获取边缘节点在线状态")
    public int getStationOnline(String stationcode) throws Exception {
        return substationService.getStationOnline(stationcode);
    }

    @PostMapping("/testSendMsg")
    @ApiOperation("测试向客户端发送数据")
    public ResponseResult testSendMsg() throws Exception {
        return ResponseResult.success();
    }


    @GetMapping("/getSubstationMaindeviceList")
    @ApiOperation("获取间隔下的主设备")
    public ResponseResult getSubstationMaindeviceList(String bayId) {
        LambdaQueryWrapper<SubstationMaindevice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SubstationMaindevice::getDatastatus, "1").eq(SubstationMaindevice::getBayId, bayId).select(SubstationMaindevice::getAreaId, SubstationMaindevice::getAreaName, SubstationMaindevice::getBayId, SubstationMaindevice::getBayName, SubstationMaindevice::getStationCode, SubstationMaindevice::getMainDeviceName, SubstationMaindevice::getMainDeviceId);
        List<Map<String, Object>> mapList = substationMaindeviceService.listMaps(queryWrapper);
        return ResponseResult.successData(mapList);
    }
}
