package com.zksy.web.controller.WaterSupply.WaterPipeInfo;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zksy.WaterSupply.WaterPipeInfo.domain.WaterPipeInfo;
import com.zksy.WaterSupply.WaterPipeInfo.service.IWaterPipeInfoService;
import com.zksy.common.annotation.Anonymous;
import com.zksy.common.core.domain.AjaxResult;
import com.zksy.common.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 管网数据统计分析接口
 */
@RestController
@RequestMapping("/api/water/pipe")
@Api(tags = "供水管网-管网信息数据接口")
public class WaterPipeInfoController {

    private static final Logger log = LoggerFactory.getLogger(WaterPipeInfoController.class);

    @Autowired
    private IWaterPipeInfoService waterPipeInfoService;

    // -------------------------- 基础CRUD接口 --------------------------
    @GetMapping("/page")
    @ApiOperation(value = "分页查询管网数据", notes = "支持按管网编号、名称、材质、状态、时间范围模糊查询")
    @ApiResponses({
            @ApiResponse(code = 200, message = "查询成功", response = AjaxResult.class),
            @ApiResponse(code = 500, message = "服务器内部错误，查询失败", response = AjaxResult.class)
    })
    public AjaxResult queryPage(
            @ApiParam(value = "页码", defaultValue = "1") @RequestParam(defaultValue = "1") Integer pageNum,
            @ApiParam(value = "每页大小", defaultValue = "10") @RequestParam(defaultValue = "10") Integer pageSize,
            @ApiParam(value = "管网编号") @RequestParam(required = false) String pipeCode,
            @ApiParam(value = "管网名称") @RequestParam(required = false) String pipeName,
            @ApiParam(value = "管网材质") @RequestParam(required = false) String pipeMaterial,
            @ApiParam(value = "状态（0正常 1停用）") @RequestParam(required = false) String status,
            @ApiParam(value = "开始时间（格式：yyyy-MM-dd HH:mm:ss）", example = "2026-01-01 00:00:00") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @ApiParam(value = "结束时间（格式：yyyy-MM-dd HH:mm:ss）", example = "2026-12-31 23:59:59") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        try {
            Page<WaterPipeInfo> page = new Page<>(pageNum, pageSize);
            IPage<WaterPipeInfo> resultPage = waterPipeInfoService.queryPage(page, pipeCode, pipeName, pipeMaterial, status, startTime, endTime);
            return AjaxResult.success("查询成功", resultPage);
        } catch (Exception e) {
            log.error("分页查询管网数据异常", e);
            return AjaxResult.error("查询失败：" + e.getMessage());
        }
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "根据ID查询管网详情", notes = "传入管网ID获取完整信息")
    @ApiResponses({
            @ApiResponse(code = 200, message = "查询成功", response = AjaxResult.class),
            @ApiResponse(code = 404, message = "未找到指定ID的管网信息", response = AjaxResult.class),
            @ApiResponse(code = 500, message = "服务器内部错误，查询失败", response = AjaxResult.class)
    })
    public AjaxResult getById(
            @ApiParam(value = "管网ID", required = true, example = "1") @PathVariable Long id) {
        try {
            WaterPipeInfo data = waterPipeInfoService.getById(id);
            return data == null ? AjaxResult.warn("未找到该管网信息") : AjaxResult.success("查询成功", data);
        } catch (Exception e) {
            log.error("查询管网详情异常", e);
            return AjaxResult.error("查询失败：" + e.getMessage());
        }
    }

    @PostMapping
    @ApiOperation(value = "新增管网信息", notes = "传入管网实体对象进行新增")
    @ApiResponses({
            @ApiResponse(code = 200, message = "新增成功", response = AjaxResult.class),
            @ApiResponse(code = 400, message = "请求参数错误", response = AjaxResult.class),
            @ApiResponse(code = 500, message = "服务器内部错误，新增失败", response = AjaxResult.class)
    })
    public AjaxResult add(@RequestBody WaterPipeInfo waterPipeInfo) {
        try {
            waterPipeInfo.setDelFlag("0");
            try {
                waterPipeInfo.setCreateBy(SecurityUtils.getUsername());
            } catch (Exception e) {
                waterPipeInfo.setCreateBy("system");
            }
            waterPipeInfo.setCreateTime(LocalDateTime.now());
            boolean result = waterPipeInfoService.save(waterPipeInfo);
            return result ? AjaxResult.success("新增成功") : AjaxResult.error("新增失败");
        } catch (Exception e) {
            log.error("新增管网信息异常", e);
            return AjaxResult.error("新增失败：" + e.getMessage());
        }
    }

    @PutMapping
    @ApiOperation(value = "修改管网信息", notes = "传入管网实体对象进行修改，仅更新非空字段")
    @ApiResponses({
            @ApiResponse(code = 200, message = "修改成功", response = AjaxResult.class),
            @ApiResponse(code = 400, message = "请求参数错误", response = AjaxResult.class),
            @ApiResponse(code = 500, message = "服务器内部错误，修改失败", response = AjaxResult.class)
    })
    public AjaxResult update(@RequestBody WaterPipeInfo waterPipeInfo) {
        try {
            // 禁止修改关键字段
            waterPipeInfo.setDelFlag(null);
            waterPipeInfo.setCreateBy(null);
            waterPipeInfo.setCreateTime(null);

            try {
                waterPipeInfo.setUpdateBy(SecurityUtils.getUsername());
            } catch (Exception e) {
                waterPipeInfo.setUpdateBy("system");
            }
            waterPipeInfo.setUpdateTime(LocalDateTime.now());

            boolean result = waterPipeInfoService.updateById(waterPipeInfo);
            return result ? AjaxResult.success("修改成功") : AjaxResult.error("修改失败");
        } catch (Exception e) {
            log.error("修改管网信息异常", e);
            return AjaxResult.error("修改失败：" + e.getMessage());
        }
    }

    @DeleteMapping("/{ids}")
    @ApiOperation(value = "批量逻辑删除管网信息", notes = "多个ID用逗号分隔，逻辑删除（移入回收站）,不物理删除数据")
    @ApiResponses({
            @ApiResponse(code = 200, message = "修改成功", response = AjaxResult.class),
            @ApiResponse(code = 400, message = "请求参数错误", response = AjaxResult.class),
            @ApiResponse(code = 500, message = "服务器内部错误，修改失败", response = AjaxResult.class)
    })
    public AjaxResult remove(
            @ApiParam(value = "管网ID数组，多个用逗号分隔", required = true, example = "1,2,3") @PathVariable Long[] ids) {
        try {
            log.info("开始删除管网数据，ids: {}", (Object) ids);
            boolean result = waterPipeInfoService.removeByIds(List.of(ids));
            return result
                    ? AjaxResult.success("删除成功，已移入回收站，共删除 " + ids.length + " 条数据")
                    : AjaxResult.error("删除失败");
        } catch (Exception e) {
            log.error("删除管网数据异常", e);
            return AjaxResult.error("删除失败：" + e.getMessage());
        }
    }

    // -------------------------- 统计分析接口 --------------------------
    @GetMapping("/latest")
    @ApiOperation(value = "获取最新添加的管网信息", notes = "返回创建时间最晚的一条管网数据")
    @ApiResponses({
            @ApiResponse(code = 200, message = "查询成功", response = AjaxResult.class),
            @ApiResponse(code = 500, message = "服务器内部错误，查询失败", response = AjaxResult.class)
    })
    public AjaxResult getLatestPipe() {
        try {
            WaterPipeInfo data = waterPipeInfoService.getLatestPipe();
            return data == null ? AjaxResult.warn("未查询到管网数据") : AjaxResult.success("查询成功", data);
        } catch (Exception e) {
            log.error("查询最新管网异常", e);
            return AjaxResult.error("查询失败：" + e.getMessage());
        }
    }

    @GetMapping("/visualization/stat/status")
    @ApiOperation(value = "按状态统计管网数据", notes = "统计正常和停用状态的管网数量")
    @ApiResponses({
            @ApiResponse(code = 200, message = "统计成功", response = AjaxResult.class),
            @ApiResponse(code = 500, message = "服务器内部错误，统计失败", response = AjaxResult.class)
    })
    public AjaxResult statPipeByStatus() {
        try {
            return AjaxResult.success("统计成功", waterPipeInfoService.statPipeByStatus());
        } catch (Exception e) {
            log.error("按状态统计管网异常", e);
            return AjaxResult.error("统计失败：" + e.getMessage());
        }
    }

    @GetMapping("/visualization/stat/material")
    @ApiOperation(value = "按材质统计管网数据", notes = "统计不同材质管网的数量和总长度")
    @ApiResponses({
            @ApiResponse(code = 200, message = "统计成功", response = AjaxResult.class),
            @ApiResponse(code = 500, message = "服务器内部错误，统计失败", response = AjaxResult.class)
    })
    public AjaxResult statPipeByMaterial() {
        try {
            return AjaxResult.success("统计成功", waterPipeInfoService.statPipeByMaterial());
        } catch (Exception e) {
            log.error("按材质统计管网异常", e);
            return AjaxResult.error("统计失败：" + e.getMessage());
        }
    }

    @GetMapping("/visualization/stat/overall")
    @ApiOperation(value = "获取管网整体统计数据", notes = "返回总管网数、总长度、运行中数量、停用数量")
    @ApiResponses({
            @ApiResponse(code = 200, message = "统计成功", response = AjaxResult.class),
            @ApiResponse(code = 500, message = "服务器内部错误，统计失败", response = AjaxResult.class)
    })
    public AjaxResult getOverallStatistics() {
        try {
            return AjaxResult.success("统计成功", waterPipeInfoService.getPipeOverallStatistics());
        } catch (Exception e) {
            log.error("获取整体统计异常", e);
            return AjaxResult.error("统计失败：" + e.getMessage());
        }
    }

    // -------------------------- 回收站接口 --------------------------
    @GetMapping("/recycle/list")
    @ApiOperation(value = "查询回收站数据", notes = "分页查询已删除的管网数据，支持筛选和时间范围")
    @ApiResponses({
            @ApiResponse(code = 200, message = "查询成功", response = AjaxResult.class),
            @ApiResponse(code = 500, message = "服务器内部错误，查询失败", response = AjaxResult.class)
    })
    public AjaxResult recycleList(
            @ApiParam(value = "页码", defaultValue = "1") @RequestParam(defaultValue = "1") Integer pageNum,
            @ApiParam(value = "每页大小", defaultValue = "10") @RequestParam(defaultValue = "10") Integer pageSize,
            @ApiParam(value = "管网编号") @RequestParam(required = false) String pipeCode,
            @ApiParam(value = "管网名称") @RequestParam(required = false) String pipeName,
            @ApiParam(value = "管网材质") @RequestParam(required = false) String pipeMaterial,
            @ApiParam(value = "开始时间（格式：yyyy-MM-dd HH:mm:ss）", example = "2026-01-01 00:00:00") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @ApiParam(value = "结束时间（格式：yyyy-MM-dd HH:mm:ss）", example = "2026-12-31 23:59:59") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        try {
            Page<WaterPipeInfo> page = new Page<>(pageNum, pageSize);
            IPage<WaterPipeInfo> resultPage = waterPipeInfoService.queryDeletedPage(page, pipeCode, pipeName, pipeMaterial, startTime, endTime);
            return AjaxResult.success("查询成功", resultPage);
        } catch (Exception e) {
            log.error("查询回收站数据异常", e);
            return AjaxResult.error("查询失败：" + e.getMessage());
        }
    }

    @PostMapping("/recycle/restore/{ids}")
    @ApiOperation(value = "批量恢复已删除数据", notes = "多个ID用逗号分隔，将数据从回收站恢复为正常状态")
    @ApiResponses({
            @ApiResponse(code = 200, message = "恢复成功", response = AjaxResult.class),
            @ApiResponse(code = 400, message = "请选择要恢复的数据", response = AjaxResult.class),
            @ApiResponse(code = 500, message = "服务器内部错误，恢复失败", response = AjaxResult.class)
    })
    public AjaxResult restore(
            @ApiParam(value = "管网ID数组，多个用逗号分隔", required = true, example = "3,4") @PathVariable Long[] ids) {
        try {
            log.info("开始恢复管网数据，ids: {}", (Object) ids);
            String updateBy = "system";
            try {
                updateBy = SecurityUtils.getUsername();
            } catch (Exception e) {
                log.warn("未获取到登录用户，使用默认值system");
            }

            boolean result = waterPipeInfoService.restoreByIds(List.of(ids), updateBy);
            return result
                    ? AjaxResult.success("恢复成功，共恢复 " + ids.length + " 条数据")
                    : AjaxResult.error("恢复失败");
        } catch (Exception e) {
            log.error("恢复数据异常", e);
            return AjaxResult.error("恢复失败：" + e.getMessage());
        }
    }

    @DeleteMapping("/recycle/delete/{ids}")
    @ApiOperation(value = "批量彻底删除数据（不可恢复）", notes = "多个ID用逗号分隔，物理删除数据库中的数据，谨慎使用")
    @ApiResponses({
            @ApiResponse(code = 200, message = "恢复成功", response = AjaxResult.class),
            @ApiResponse(code = 400, message = "请选择要恢复的数据", response = AjaxResult.class),
            @ApiResponse(code = 500, message = "服务器内部错误，恢复失败", response = AjaxResult.class)
    })
    public AjaxResult deletePhysically(
            @ApiParam(value = "管网ID数组，多个用逗号分隔", required = true, example = "5") @PathVariable Long[] ids) {
        try {
            log.info("开始彻底删除管网数据，ids: {}", (Object) ids);
            boolean result = waterPipeInfoService.deleteByIdsPhysically(List.of(ids));
            return result
                    ? AjaxResult.success("彻底删除成功，共删除 " + ids.length + " 条数据")
                    : AjaxResult.error("彻底删除失败");
        } catch (Exception e) {
            log.error("彻底删除数据异常", e);
            return AjaxResult.error("彻底删除失败：" + e.getMessage());
        }
    }
}