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

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zksy.WaterSupply.WaterSourceInfo.domain.WaterSourceInfo;
import com.zksy.WaterSupply.WaterSourceInfo.service.IWaterSourceInfoService;
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/sourceInfo")
@Api(tags = "供水管网-水源地信息数据接口")
public class WaterSourceInfoController {

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

    @Autowired
    private IWaterSourceInfoService waterSourceInfoService;

    // -------------------------- 基础CRUD接口 --------------------------
    @GetMapping("/page")
    @ApiOperation(value = "分页查询水源地数据", notes = "支持按水源地ID、名称、状态、所属单位、时间范围模糊查询")
    @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 = "水源地ID") @RequestParam(required = false) String sourceId,
            @ApiParam(value = "水源地名称") @RequestParam(required = false) String sourceName,
            @ApiParam(value = "状态（0正常 1异常）") @RequestParam(required = false) String status,
            @ApiParam(value = "所属单位") @RequestParam(required = false) String unit,
            @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<WaterSourceInfo> page = new Page<>(pageNum, pageSize);
            IPage<WaterSourceInfo> resultPage = waterSourceInfoService.queryPage(page, sourceId, sourceName, status, unit, 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 = "0") @PathVariable Long id) {
        try {
            WaterSourceInfo data = waterSourceInfoService.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 WaterSourceInfo waterSourceInfo) {
        try {
            waterSourceInfo.setDelFlag("0");
            try {
                waterSourceInfo.setCreateBy(SecurityUtils.getUsername());
            } catch (Exception e) {
                waterSourceInfo.setCreateBy("system");
            }
            waterSourceInfo.setCreateTime(LocalDateTime.now());
            boolean result = waterSourceInfoService.save(waterSourceInfo);
            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 WaterSourceInfo waterSourceInfo) {
        try {
            waterSourceInfo.setDelFlag(null);
            waterSourceInfo.setCreateBy(null);
            waterSourceInfo.setCreateTime(null);

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

            boolean result = waterSourceInfoService.updateById(waterSourceInfo);
            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 = waterSourceInfoService.removeByIds(List.of(ids));
            return result
                    ? AjaxResult.success("删除成功，已移入回收站，共删除 " + ids.length + " 条数据")
                    : AjaxResult.error("删除失败");
        } 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 = "水源地ID") @RequestParam(required = false) String sourceId,
            @ApiParam(value = "水源地名称") @RequestParam(required = false) String sourceName,
            @ApiParam(value = "状态（0正常 1异常）") @RequestParam(required = false) String status,
            @ApiParam(value = "开始时间（格式：yyyy-MM-dd HH:mm:ss）", example = "2025-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 = "2025-12-31 23:59:59") @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        try {
            Page<WaterSourceInfo> page = new Page<>(pageNum, pageSize);
            IPage<WaterSourceInfo> resultPage = waterSourceInfoService.queryDeletedPage(page, sourceId, sourceName, status, 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 = waterSourceInfoService.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 = waterSourceInfoService.deleteByIdsPhysically(List.of(ids));
            return result
                    ? AjaxResult.success("彻底删除成功，共删除 " + ids.length + " 条数据")
                    : AjaxResult.error("彻底删除失败");
        } catch (Exception e) {
            log.error("彻底删除数据异常", e);
            return AjaxResult.error("彻底删除失败：" + e.getMessage());
        }
    }
}