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

import cn.hutool.core.date.DateUtil;
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.Substation;
import com.yfd.platform.modules.basedata.domain.SubstationDevice;
import com.yfd.platform.modules.basedata.domain.SubstationPatroldevice;
import com.yfd.platform.modules.basedata.service.ISubstationPatroldeviceService;
import com.yfd.platform.modules.basedata.service.ISubstationService;
import com.yfd.platform.modules.patroltask.domain.ExaminePlan;
import com.yfd.platform.modules.patroltask.service.IExaminePlanService;
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.web.bind.annotation.*;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 检修计划表 前端控制器
 * </p>
 *
 * @since 2023-04-08
 */
@RestController
@RequestMapping("/patroltasks/examine-plan")
@Api(value = "ExaminePlanController", tags = "任务检修")
public class ExaminePlanController {

    @Resource
    private IExaminePlanService examinePlanService;
    @Resource
    private ISubstationService substationService;
    @Resource
    private IStationRobotService stationRobotService;
    @Resource
    private ISubstationPatroldeviceService substationPatroldeviceService;
    @Resource
    private HttpServerConfig httpServerConfig;

    @GetMapping("/getExaminePlanPage")
    @ApiOperation("分页查询检修计划")
    public ResponseResult getExaminePlanPage(Page<Map<String, Object>> page, String stationId, String configName,
                                             String bindStatus) {
        Page<Map<String, Object>> mapPage = examinePlanService.getExaminePlanPage(page, stationId, configName, bindStatus);
        return ResponseResult.successData(mapPage);
    }

    @GetMapping("/getTaskById")
    @ApiOperation("根据Id查询检修计划")
    public ResponseResult getTaskById(String id) {
        ExaminePlan examinePlan = examinePlanService.getById(id);
        return ResponseResult.successData(examinePlan);
    }

    @GetMapping("/getBindInfoById")
    @ApiOperation("根据Id查询关联信息")
    public ResponseResult getBindInfoById(String id, String deviceLevel) {
        List<Map<String, Object>> mapList = examinePlanService.getBindInfoById(id, deviceLevel);
        return ResponseResult.successData(mapList);
    }

    @Log(module = "任务检修", value = "新增检修计划")
    @PostMapping("/addExaminePlan")
    @ApiOperation("新增检修计划")
    public ResponseResult addExaminePlan(@RequestBody ExaminePlan examinePlan) {
        if (examinePlan == null) {
            return ResponseResult.error("参数为空");
        }
        // 检修编码
        String configCode = examinePlan.getConfigCode();
        LambdaQueryWrapper<ExaminePlan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ExaminePlan::getConfigCode, configCode);
        int count = examinePlanService.count(queryWrapper);
        if (count > 0) {
            return ResponseResult.error("检修计划已经存在");
        }
        if (StrUtil.isBlank(examinePlan.getDeviceList())) {
            examinePlan.setDeviceLevel(0);
            examinePlan.setDatastatus("0");
        } else {
            examinePlan.setDatastatus("1");
        }
        examinePlan.setEnable(0);
        examinePlan.setCreateTime(DateUtil.now());
        examinePlan.setLastmodifier(SecurityUtils.getCurrentUsername());
        examinePlan.setLastmodifydate(new Timestamp(DateUtil.current()));
        boolean ok = examinePlanService.save(examinePlan);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error("新增失败");
        }
    }

    @Log(module = "任务检修", value = "修改检修计划")
    @PostMapping("/updateExaminePlan")
    @ApiOperation("修改检修计划")
    public ResponseResult updateExaminePlan(@RequestBody ExaminePlan examinePlan) {
        if (examinePlan == null) {
            return ResponseResult.error("参数为空");
        }
        // 检修编码
        String configCode = examinePlan.getConfigCode();
        String id = examinePlan.getId();
        LambdaQueryWrapper<ExaminePlan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ne(ExaminePlan::getId, id).eq(ExaminePlan::getConfigCode, configCode);
        int count = examinePlanService.count(queryWrapper);
        if (count > 0) {
            return ResponseResult.error("检修计划已经存在");
        }
        String deviceList = examinePlan.getDeviceList();
        if (StrUtil.isBlank(deviceList)) {
            examinePlan.setDeviceLevel(0);
            examinePlan.setDatastatus("0");
        } else {
            examinePlan.setDatastatus("1");
        }
        examinePlan.setLastmodifier(SecurityUtils.getCurrentUsername());
        examinePlan.setLastmodifydate(new Timestamp(DateUtil.current()));
        boolean ok = examinePlanService.updateById(examinePlan);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error("修改失败");
        }
    }

    @Log(module = "任务检修", value = "设置检修计划是否启用")
    @PostMapping("/setExaminePlanStatus")
    @ApiOperation("设置检修计划是否启用")
    public ResponseResult setExaminePlanStatus(String id, String enable) {
        ExaminePlan examinePlan = examinePlanService.getById(id);
        if (StrUtil.isBlank(examinePlan.getDeviceList())) {
            return ResponseResult.error("未关联启用状态不可操作");
        }
        examinePlan.setEnable(Integer.valueOf(enable));
        if (StrUtil.isNotBlank(examinePlan.getRobotCode())) {
            // 检修发送数据
            JSONObject jsonObject = new JSONObject();
            jsonObject.putOnce("config_code", examinePlan.getConfigCode());
            jsonObject.putOnce("enable", examinePlan.getEnable());
            jsonObject.putOnce("start_time", examinePlan.getStartTime());
            jsonObject.putOnce("end_time", examinePlan.getEndTime());
            jsonObject.putOnce("device_level", examinePlan.getDeviceLevel());
            jsonObject.putOnce("device_list", examinePlan.getDeviceList());
            jsonObject.putOnce("coordinate_pixel", examinePlan.getCoordinatePixel());
            String robotCode = examinePlan.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_EXAMINE_ISSUED_CODE.getCode(), SystemCode.COMMAND_EXAMINE_CONFIG_CODE.getCode(), examinePlan.getStationCode(), jsonObject.toString());
                }
            }
        }
        boolean ok = examinePlanService.updateById(examinePlan);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error("修改失败");
        }
    }

    @Log(module = "任务检修", value = "检修计划关联设备")
    @PostMapping("/bindExaminePlan")
    @ApiOperation("检修计划关联设备")
    public ResponseResult bindExaminePlan(@RequestBody ExaminePlan examinePlan) {
        if (examinePlan == null) {
            return ResponseResult.error("参数为空");
        }
        examinePlan.setLastmodifier(SecurityUtils.getCurrentUsername());
        examinePlan.setLastmodifydate(new Timestamp(DateUtil.current()));
        String deviceList = examinePlan.getDeviceList();
        if (StrUtil.isBlank(deviceList)) {
            examinePlan.setDeviceLevel(0);
        } else {
            examinePlan.setDatastatus("1");
        }
        boolean ok = examinePlanService.updateById(examinePlan);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error("关联失败");
        }
    }

    @Log(module = "任务检修", value = "删除检修计划")
    @PostMapping("/deleteExaminePlan")
    @ApiOperation("删除检修计划")
    public ResponseResult deleteExaminePlan(String id) {
        if (StrUtil.isBlank(id)) {
            return ResponseResult.error("参数为空");
        }
        String[] split = id.split(",");
        for (String s : split) {
            ExaminePlan examinePlan = examinePlanService.getById(s);
            if (examinePlan.getEnable() == 1) {
                continue;
            }
            examinePlanService.removeById(s);
        }
        return ResponseResult.success();
    }

    @GetMapping("/getBindExamineDevice")
    @ApiOperation("根据Id查询检修计划绑定点位")
    public ResponseResult getBindExamineDevice(String id) {
        List<SubstationDevice> deviceList = examinePlanService.getBindExamineDevice(id);
        return ResponseResult.successData(deviceList);
    }

}
