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

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
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.HttpServerConfig;
import com.yfd.platform.config.ResponseResult;
import com.yfd.platform.constant.SystemCode;
import com.yfd.platform.modules.basedata.domain.LinkageSignal;
import com.yfd.platform.modules.basedata.domain.Substation;
import com.yfd.platform.modules.basedata.domain.SubstationDevice;
import com.yfd.platform.modules.basedata.domain.SubstationPatroldevice;
import com.yfd.platform.modules.basedata.service.ILinkageSignalService;
import com.yfd.platform.modules.basedata.service.ISubstationDeviceService;
import com.yfd.platform.modules.basedata.service.ISubstationPatroldeviceService;
import com.yfd.platform.modules.basedata.service.ISubstationService;
import com.yfd.platform.modules.patroltask.domain.Task;
import com.yfd.platform.modules.patroltask.service.ITaskService;
import com.yfd.platform.modules.robotapi.service.IStationRobotService;
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.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 联动信号关联表 前端控制器
 * </p>
 *
 * @since 2023-04-06
 */
@RestController
@RequestMapping("/basedata/linkage-signal")
@Api(value = "LinkageSignalController", tags = "联动信号配置")
public class LinkageSignalController {

    @Resource
    private ILinkageSignalService linkageSignalService;

    @Resource
    private ISubstationService substationService;

    @Resource
    private ISubstationDeviceService substationDeviceService;
    @Resource
    private IStationRobotService stationRobotService;
    @Resource
    private ITaskService taskService;
    @Resource
    private HttpServerConfig httpServerConfig;
    @Resource
    private ISubstationPatroldeviceService substationPatroldeviceService;

    @GetMapping("/getLinkageSignalList")
    @ApiOperation("分页查询联动信号配置")
    @PreAuthorize("@el.check('select:signal')")
    public ResponseResult getLinkageSignalList(Page<Map<String, Object>> page, String name, String dataStatus,
                                               String linkageType) {
        LambdaQueryWrapper<LinkageSignal> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(name)) {
            queryWrapper.and(i->i.eq(LinkageSignal::getControlNum,name).or().like(LinkageSignal::getLinkageDeviceName, name));
        }
        if (StrUtil.isNotBlank(dataStatus)) {
            queryWrapper.eq(LinkageSignal::getDatastatus, dataStatus);
        }

        if (StrUtil.isNotBlank(linkageType)) {
            queryWrapper.eq(LinkageSignal::getLinkageType, linkageType);
        }
        Page<Map<String, Object>> mapPage = linkageSignalService.pageMaps(page, queryWrapper);
        List<Map<String, Object>> records = mapPage.getRecords();
        records.forEach(r -> {
            if (!Objects.isNull(r.get("stationId"))) {
                String stationId = r.get("stationId").toString();
                Substation substation = substationService.getById(stationId);
                if (substation != null) {
                    r.put("isStationFlag", substation.getIsStationFlag());
                    r.put("online", substation.getOnline());
                }
            }
        });
        mapPage.setRecords(records);
        return ResponseResult.successData(mapPage);
    }

    @GetMapping("/getSubstationDeviceListById")
    @ApiOperation("根据联动信号Id查询绑定的巡视信息")
    public ResponseResult getSubstationDeviceListById(String id) {
        LinkageSignal linkageSignal = linkageSignalService.getById(id);
        String deviceIdList = linkageSignal.getDeviceIdList();
        //String videoPos = linkageSignal.getVideoPos();
        List<Map<String, Object>> mapList = new ArrayList<>();
        if (StrUtil.isNotBlank(deviceIdList)) {
            String[] split = deviceIdList.split(",");
            for (String s : split) {
                Map<String, Object> map = new HashMap<>();
                SubstationDevice substationDevice = substationDeviceService.getById(s);
                if (substationDevice == null) {
                    continue;
                }
                map.put("deviceId", substationDevice.getDeviceId());
                map.put("deviceName", substationDevice.getDeviceName());
                map.put("stationName", substationDevice.getStationName());
                map.put("stationCode", substationDevice.getStationCode());
                map.put("areaName", substationDevice.getAreaName());
                map.put("bayName", substationDevice.getBayName());
                map.put("areaId", substationDevice.getAreaId());
                map.put("bayId", substationDevice.getBayId());
                mapList.add(map);
            }
        } /*else if (StrUtil.isNotBlank(videoPos)) {
            List<Map> list = JSONUtil.toList(videoPos, Map.class);
            for (Map map : list) {
                mapList.add(map);
            }
        }*/
        return ResponseResult.successData(mapList);
    }

    @PostMapping("/deleteBindSubstationDevice")
    @ApiOperation("删除绑定的巡视点位(暂时不用)")
    public ResponseResult deleteBindSubstationDevice(String id, String deviceId) {
        LinkageSignal linkageSignal = linkageSignalService.getById(id);
        String deviceIdList = linkageSignal.getDeviceIdList();
        // 拆分巡视点位id
        String[] split = deviceIdList.split(",");
        List<String> ids = new ArrayList<>(split.length);
        ids.addAll(Arrays.asList(split));
        ids.remove(null);
        ids.remove("");
        // 删除指定的点位
        ids.remove(deviceId);
        // 将删除的点位id用逗号拼接
        String joinIds = String.join(",", ids);
        if (StrUtil.isBlank(joinIds)) {
            linkageSignal.setLinkageType("");
            linkageSignal.setDatastatus("0");
        }
        linkageSignal.setDeviceIdList(joinIds);
        boolean ok = linkageSignalService.updateById(linkageSignal);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error("删除失败");
        }
    }

    /*@GetMapping("/getLinkageSignalById")
    @ApiOperation("根据id查询联动信号配置")
    public ResponseResult getLinkageSignalById(String id) {
        return ResponseResult.successData(null);
    }
*/
    @Log(module = "联动信号配置", value = "绑定巡视点位或者巡视设备", type = "1")
    @PostMapping("/bindSubstationDevice")
    @ApiOperation("绑定巡视点位或者巡视设备")
    public ResponseResult bindSubstationDevice(@RequestBody LinkageSignal linkageSignal) {
        linkageSignal.setLastmodifier(SecurityUtils.getCurrentUsername());
        String deviceIdList = linkageSignal.getDeviceIdList();
    /*    String videoPos = linkageSignal.getVideoPos();
        if (StrUtil.isNotBlank(deviceIdList) || StrUtil.isNotBlank(videoPos)) {
            linkageSignal.setDatastatus("1");
        } else {
            linkageSignal.setLinkageType("");
            linkageSignal.setDatastatus("0");
        }*/
        if (StrUtil.isNotBlank(deviceIdList)) {
            linkageSignal.setDatastatus("1");
            String[] split = deviceIdList.split(",");
            String deviceId = split[0];
            SubstationDevice substationDevice = substationDeviceService.getById(deviceId);
            linkageSignal.setStationId(substationDevice.getStationId());
            linkageSignal.setStationCode(substationDevice.getStationCode());
            linkageSignal.setStationName(substationDevice.getStationName());
        } else {
            linkageSignal.setDatastatus("0");
        }
       /* String linkageType = linkageSignal.getLinkageType();
        // 如果类型是2，则传的参数为
        if ("2".equals(linkageType)) {
            JSONArray objects = JSONUtil.parseArray(videoPos);
            List<Map> list = JSONUtil.toList(objects, Map.class);
            List<Map<String, Object>> listMap = new ArrayList<>();
            for (Map map : list) {
                Map<String, Object> map1 = new HashMap<>();
                map1.put("patroldeviceCode", map.get("patroldeviceCode"));
                map1.put("patroldeviceName", map.get("patroldeviceName"));
                map1.put("typeName", map.get("typeName"));
                map1.put("preset", map.get("preset"));
                map1.put("stationCode", map.get("stationCode"));
                listMap.add(map1);
            }
            String jsonStr = JSONUtil.toJsonStr(listMap);
            linkageSignal.setVideoPos(jsonStr);
        }*/
        linkageSignal.setLastmodifydate(LocalDateTime.now());
        boolean ok = linkageSignalService.updateById(linkageSignal);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error("绑定失败");
        }
    }

    @Log(module = "联动信号配置", value = "新增联动信号", type = "1")
    @PostMapping("/addLinkageSignal")
    @ApiOperation("新增联动信号")
    @PreAuthorize("@el.check('add:signal')")
    public ResponseResult addLinkageSignal(@RequestBody LinkageSignal linkageSignal) {
        String controlNum = linkageSignal.getControlNum();
        int count = linkageSignalService.count(new LambdaQueryWrapper<LinkageSignal>().eq(LinkageSignal::getControlNum,
                controlNum));
        if (count > 0) {
            return ResponseResult.error("监控索引号重复");
        }
        String stationNum = linkageSignal.getStationCode();
        LambdaQueryWrapper<Substation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Substation::getStationCode, stationNum);
        List<Substation> list = substationService.list(queryWrapper);
        if (list == null) {
            return ResponseResult.error("新增失败");
        }
        Substation substation = list.get(0);
        linkageSignal.setStationNum(substation.getStationCode());
        linkageSignal.setStationId(substation.getStationId());
        linkageSignal.setStationCode(substation.getStationCode());
        linkageSignal.setStationName(substation.getStationName());
        linkageSignal.setDatastatus("0");
        linkageSignal.setIsenable("0");
        linkageSignal.setTime(LocalDateTime.now());
        linkageSignal.setLastmodifier(SecurityUtils.getCurrentUsername());
        linkageSignal.setLastmodifydate(LocalDateTime.now());
        boolean ok = linkageSignalService.save(linkageSignal);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error("新增失败");
        }

    }

    @Log(module = "联动信号配置", value = "修改联动信号", type = "1")
    @PostMapping("/updateLinkageSignalById")
    @ApiOperation("修改联动信号")
    @PreAuthorize("@el.check('update:signal')")
    public ResponseResult updateLinkageSignalById(@RequestBody LinkageSignal linkageSignal) {
        String id = linkageSignal.getId();
        String controlNum = linkageSignal.getControlNum();
        LambdaQueryWrapper<LinkageSignal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ne(LinkageSignal::getId, id).eq(LinkageSignal::getControlNum, controlNum);
        int count = linkageSignalService.count(queryWrapper);
        if (count > 0) {
            return ResponseResult.error("监控索引号重复");
        }
        LambdaQueryWrapper<Substation> queryWrapper1 = new LambdaQueryWrapper<>();
        List<Substation> list = substationService.list(queryWrapper1);
        if (list == null) {
            return ResponseResult.error("修改失败");
        }
        Substation substation = list.get(0);
        linkageSignal.setStationId(substation.getStationId());
        linkageSignal.setStationCode(substation.getStationCode());
        linkageSignal.setStationName(substation.getStationName());
        linkageSignal.setLastmodifier(SecurityUtils.getCurrentUsername());
        linkageSignal.setLastmodifydate(LocalDateTime.now());
        boolean ok = linkageSignalService.updateById(linkageSignal);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error("修改失败");
        }
    }

    @Log(module = "联动信号配置", value = "修改联动信号状态", type = "1")
    @PostMapping("/setLinkageSignalById")
    @ApiOperation("修改联动信号状态")
    public ResponseResult setLinkageSignalById(@RequestBody LinkageSignal linkageSignal) {
        linkageSignal.setLastmodifier(SecurityUtils.getCurrentUsername());
        linkageSignal.setLastmodifydate(LocalDateTime.now());
        boolean ok = linkageSignalService.updateById(linkageSignal);
        String id = linkageSignal.getId();
        LinkageSignal linkageSignal1 = linkageSignalService.getById(id);
        if ("1".equals(linkageSignal.getIsenable()) && StrUtil.isNotBlank(linkageSignal1.getRobotCode())) {
            createLinkageTask(linkageSignal1);
        }
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error("修改失败");
        }
    }

    /**********************************
     * 用途说明: 创建主辅联动任务
     * 参数说明 linkageSignal
     * 返回值说明: void
     ***********************************/
    private void createLinkageTask(LinkageSignal linkageSignal) {
        Task task = new Task();
        String uuid = IdUtil.fastSimpleUUID();
        task.setTaskId(uuid);
        task.setStationCode(linkageSignal.getStationCode());
        task.setStationName(linkageSignal.getStationName());
        String code = DateUtil.format(DateUtil.date(), "yyyyMMddHHmmss");
        task.setTaskCode(code);
        String taskName = "一件顺控任务-" + code;
        if ("2".equals(linkageSignal.getLinkageType())) {
            taskName = "智能联动任务-" + code;
        }
        task.setTaskName(taskName);
        //特殊巡视
        task.setType("2");
        // 主辅设备联动
        task.setTaskType("4");
        //1立即执行
        task.setTaskTodoType("1");
        //优先级最高(4级)
        task.setPriority("4");

        task.setDeviceLevel(3);
        task.setDeviceList(linkageSignal.getDeviceIdList());
        String currentUsername = "主辅联动";
        task.setLastmodifier(currentUsername);
        task.setCreator(currentUsername);
        Timestamp timestamp = new Timestamp(DateUtil.current());
        task.setLastmodifydate(timestamp);
        task.setCreateTime(DateUtil.now());
        task.setIsenable("1");
        task.setRobotCode(linkageSignal.getRobotCode());
        task.setIsReport("0");
        task.setDatastatus("2");
        // 修改为索引号
        //代用了一键顺控的属性值
        task.setControlNum(linkageSignal.getControlNum());
        taskService.save(task);
        // 联动信号
        JSONObject jsonObject = new JSONObject();
        jsonObject.putOnce("task_code", task.getTaskCode());
        jsonObject.putOnce("task_name", taskName);
        jsonObject.putOnce("priority", task.getPriority());
        jsonObject.putOnce("device_level", task.getDeviceLevel());
        jsonObject.putOnce("device_list", linkageSignal.getDeviceIdList());
        String robotCode = linkageSignal.getRobotCode();
        if (StrUtil.isNotBlank(robotCode)) {
            List<SubstationPatroldevice> list = substationPatroldeviceService.list(new LambdaQueryWrapper<SubstationPatroldevice>().eq(SubstationPatroldevice::getPatroldeviceCode, robotCode));
            if (list.size() > 0) {
                SubstationPatroldevice substationPatroldevice = list.get(0);
                stationRobotService.sendCommand(substationPatroldevice.getInternationalId(), httpServerConfig.getPatrolServerid(), substationPatroldevice.getInternationalId(),
                        SystemCode.TYPE_LINKAGE_TASK_ISSUED_CODE.getCode(), SystemCode.COMMAND_TASK_CONFIG_CODE.getCode(), code, jsonObject.toString());
            }
        }

    }

    @Log(module = "联动信号配置", value = "删除联动信号", type = "1")
    @PostMapping("/deleteLinkageSignalById")
    @ApiOperation("删除联动信号")
    @PreAuthorize("@el.check('del:signal')")
    public ResponseResult deleteLinkageSignalById(String ids) {
        if (StrUtil.isBlank(ids)) {
            return ResponseResult.error("参数为空");
        }
        String[] split = ids.split(",");
        for (String id : split) {
            LinkageSignal linkageSignal = linkageSignalService.getById(id);
            String datastatus = linkageSignal.getDatastatus();
            if ("1".equals(datastatus)) {
                continue;
            }
            linkageSignalService.removeById(id);
        }
        return ResponseResult.success();
    }

    @PostMapping("/receiveFile")
    @ApiOperation("接收文件")
    public ResponseResult receiveFile(MultipartFile file, String type) throws Exception {
        // 解析文件
        linkageSignalService.receiveFile(file, type);
        return ResponseResult.success();
    }


}
