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

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

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

    @Autowired
    private IWaterPlantInfoService waterPlantInfoService;

    // -------------------------- 基础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 plantCode,
            @ApiParam(value = "水厂名称") @RequestParam(required = false) String plantName,
            @ApiParam(value = "运行状态（0正常 1停产）") @RequestParam(required = false) String status,
            @ApiParam(value = "负责人") @RequestParam(required = false) String principal,
            @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<WaterPlantInfo> page = new Page<>(pageNum, pageSize);
            IPage<WaterPlantInfo> resultPage = waterPlantInfoService.queryPage(page, plantCode, plantName, status, principal, 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 {
            WaterPlantInfo data = waterPlantInfoService.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 WaterPlantInfo waterPlantInfo) {
        try {
            waterPlantInfo.setDelFlag("0");
            try {
                waterPlantInfo.setCreateBy(SecurityUtils.getUsername());
            } catch (Exception e) {
                waterPlantInfo.setCreateBy("system");
            }
            waterPlantInfo.setCreateTime(LocalDateTime.now());
            boolean result = waterPlantInfoService.save(waterPlantInfo);
            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 WaterPlantInfo waterPlantInfo) {
        try {
            // 禁止修改关键字段
            waterPlantInfo.setDelFlag(null);
            waterPlantInfo.setCreateBy(null);
            waterPlantInfo.setCreateTime(null);

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

            boolean result = waterPlantInfoService.updateById(waterPlantInfo);
            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 = waterPlantInfoService.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 = "水厂编号") @RequestParam(required = false) String plantCode,
            @ApiParam(value = "水厂名称") @RequestParam(required = false) String plantName,
            @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<WaterPlantInfo> page = new Page<>(pageNum, pageSize);
            IPage<WaterPlantInfo> resultPage = waterPlantInfoService.queryDeletedPage(page, plantCode, plantName, 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 = waterPlantInfoService.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 = waterPlantInfoService.deleteByIdsPhysically(List.of(ids));
            return result
                    ? AjaxResult.success("彻底删除成功，共删除 " + ids.length + " 条数据")
                    : AjaxResult.error("彻底删除失败");
        } catch (Exception e) {
            log.error("彻底删除数据异常", e);
            return AjaxResult.error("彻底删除失败：" + e.getMessage());
        }
    }
}