package com.usky.cdi.controller.web;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.usky.cdi.domain.CdiDefenseProject;
import com.usky.cdi.service.CdiDefenseProjectService;
import com.usky.cdi.service.mqtt.MqttConnectionTool;
import com.usky.common.core.bean.ApiResult;
import com.usky.common.log.annotation.Log;
import com.usky.common.log.enums.BusinessType;
import com.usky.common.security.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * <p>
 * 人防_工程表（人防工程基础信息及MQTT连接配置） 前端控制器
 * </p>
 *
 * @author fu
 * @since 2026-02-02
 */
@Api(tags = "人防_工程表")
@Slf4j
@RestController
@RequestMapping("/cdiDefenseProject")
@RequiredArgsConstructor
public class CdiDefenseProjectController {

    private final MqttConnectionTool mqttConnectionTool;

    @Autowired
    private CdiDefenseProjectService cdiDefenseProjectService;

    @ApiOperation("查询人防工程配置")
    @GetMapping("config")
    public ApiResult<CdiDefenseProject> query() {
        Integer tenantId = SecurityUtils.getTenantId();
        if (tenantId == null) {
            return null;
        }
        return ApiResult.success(cdiDefenseProjectService.listByTenantId(tenantId));
    }

    /**
     * 新增人防工程
     */
    @ApiOperation("新增人防工程配置")
    @Log(title = "新增人防工程配置", businessType = BusinessType.INSERT)
    @PostMapping("config")
    public ApiResult<String> add(@RequestBody CdiDefenseProject cdiDefenseProject) {
        cdiDefenseProject.setCreateBy(SecurityUtils.getUsername());
        cdiDefenseProject.setCreateTime(LocalDateTime.now());
        cdiDefenseProject.setTenantId(SecurityUtils.getTenantId());
        cdiDefenseProject.setIsEnable(1);
        boolean save = cdiDefenseProjectService.save(cdiDefenseProject);

        if (save) {
            mqttConnectionTool.connectOrRefresh(cdiDefenseProject.getMqttUserName(), cdiDefenseProject.getMqttPassword());
            return ApiResult.success("新增成功！");
        } else {
            return ApiResult.error("新增失败！");
        }
    }

    /**
     * 修改人防工程
     */
    @ApiOperation("修改人防工程")
    @Log(title = "修改人防工程", businessType = BusinessType.UPDATE)
    @PutMapping("config")
    public ApiResult<String> edit(@RequestBody CdiDefenseProject cdiDefenseProject) {
        Long id = cdiDefenseProject.getId();
        if (id == null || id <= 0) {
            return ApiResult.error("参数错误，请检查ID");
        }
        CdiDefenseProject existCdiDefenseProject = cdiDefenseProjectService.getById(id);
        if (existCdiDefenseProject == null) {
            return ApiResult.error("工程配置不存在！");
        }

        cdiDefenseProject.setUpdateBy(SecurityUtils.getUsername());
        cdiDefenseProject.setUpdateTime(LocalDateTime.now());
        boolean b = cdiDefenseProjectService.updateById(cdiDefenseProject);
        if (b) {
            return ApiResult.success("修改成功！");
        } else {
            return ApiResult.error("修改失败！");
        }
    }

    /**
     * 更改人防工程状态
     */
    @ApiOperation("更改人防工程状态")
    @Log(title = "更改人防工程状态", businessType = BusinessType.UPDATE)
    @PutMapping("/configState")
    public ApiResult<String> changeStatus(@RequestBody CdiDefenseProject cdiDefenseProject) {
        Long id = cdiDefenseProject.getId();
        if (id == null || id <= 0) {
            return ApiResult.error("参数错误，请检查ID");
        }
        Integer isEnable = cdiDefenseProject.getIsEnable();
        CdiDefenseProject cdiDefenseProject1 = cdiDefenseProjectService.getById(id);
        if (cdiDefenseProject1 == null) {
            return ApiResult.error("工程配置不存在！");
        }
        if (isEnable < 0 || isEnable > 1) {
            return ApiResult.error("参数错误，请检查状态值！");
        }

        cdiDefenseProject1.setId(id);
        cdiDefenseProject1.setIsEnable(isEnable);
        cdiDefenseProject1.setUpdateBy(SecurityUtils.getUsername());
        cdiDefenseProject1.setUpdateTime(LocalDateTime.now());
        boolean b = cdiDefenseProjectService.updateById(cdiDefenseProject1);

        if (b && isEnable == 1) {
            return ApiResult.success("启用成功！");
        } else if (b) {
            return ApiResult.success("禁用成功！");
        } else {
            return ApiResult.error("操作失败！");
        }

    }

    /**
     * MQTT连通性测试
     */
    @ApiOperation("MQTT连通性测试")
    @GetMapping("configVerify")
    public ApiResult<String> testMqttConnection(@ApiParam("工程ID") @RequestParam Long id) {
        CdiDefenseProject cdiDefenseProject = cdiDefenseProjectService.getById(id);
        if (cdiDefenseProject == null) {
            return ApiResult.error("工程配置不存在！");
        }

        String broker = cdiDefenseProject.getPushAddress();
        String user = cdiDefenseProject.getMqttUserName();
        String pass = cdiDefenseProject.getMqttPassword();
        String clientId = cdiDefenseProject.getMqttClientId();
        boolean b = cdiDefenseProjectService.tryConnectAndPublish(broker, user, pass, "PING", clientId);

        if (b) {
            return ApiResult.success("MQTT 连通性测试成功！");
        } else {
            return ApiResult.error("MQTT 连通性测试失败，请检查网络、账号和密码！");
        }
    }
}

