package com.njcn.relational.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.njcn.relational.pojo.po.SyncTableLogs;
import com.njcn.relational.pojo.vo.HttpResult;
import com.njcn.relational.service.SyncTableLogsService;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

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

/**
 * 二三区数据转移日志 Controller
 *
 * @author cdf
 * @date 2026-06-28
 */
@RestController
@RequestMapping("/sync-logs")
@RequiredArgsConstructor
public class SyncTableLogsController {

    private final SyncTableLogsService syncTableLogsService;

    // ========== 查询 ==========

    /**
     * 分页查询日志
     * GET /api/sync-logs/page?pageNum=1&pageSize=10&timeId=2026-06-28&result=1
     */
    @GetMapping("/page")
    public HttpResult<IPage<SyncTableLogs>> page(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate timeId,
            @RequestParam(required = false) Integer result) {

        IPage<SyncTableLogs> page = syncTableLogsService.pageQuery(pageNum, pageSize, timeId, result);
        return HttpResult.success(page);
    }

    /**
     * 根据日期查询日志列表
     * GET /api/sync-logs/list?timeId=2026-06-28
     */
    @GetMapping("/list")
    public HttpResult<List<SyncTableLogs>> listByTimeId(
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate timeId) {

        List<SyncTableLogs> list = syncTableLogsService.listByTimeId(timeId);
        return HttpResult.success(list);
    }

    /**
     * 根据日期和结果查询
     * GET /api/sync-logs/list/condition?timeId=2026-06-28&result=1
     */
    @GetMapping("/list/condition")
    public HttpResult<List<SyncTableLogs>> listByTimeIdAndResult(
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate timeId,
            @RequestParam Integer result) {

        List<SyncTableLogs> list = syncTableLogsService.listByTimeIdAndResult(timeId, result);
        return HttpResult.success(list);
    }

    /**
     * 根据ID查询单条记录
     * GET /api/sync-logs/2026-06-28/1
     */
    @GetMapping("/{timeId}/{result}")
    public HttpResult<SyncTableLogs> getById(
            @PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate timeId,
            @PathVariable Integer result) {

        LambdaQueryWrapper<SyncTableLogs> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SyncTableLogs::getTimeId, timeId)
                .eq(SyncTableLogs::getResult, result);

        SyncTableLogs log = syncTableLogsService.getOne(wrapper);
        return HttpResult.success(log);
    }

    /**
     * 检查某日期是否存在记录
     * GET /api/sync-logs/exists/2026-06-28
     */
    @GetMapping("/exists/{timeId}")
    public HttpResult<Boolean> existsByTimeId(
            @PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate timeId) {

        boolean exists = syncTableLogsService.existsByTimeId(timeId);
        return HttpResult.success(exists);
    }

    /**
     * 统计某日期的成功/失败数量
     * GET /api/sync-logs/count/2026-06-28/1
     */
    @GetMapping("/count/{timeId}/{result}")
    public HttpResult<Integer> countByTimeIdAndResult(
            @PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate timeId,
            @PathVariable Integer result) {

        int count = syncTableLogsService.countByTimeIdAndResult(timeId, result);
        return HttpResult.success(count);
    }

    /**
     * 查询所有日志
     * GET /api/sync-logs/all
     */
    @GetMapping("/all")
    public HttpResult<List<SyncTableLogs>> listAll() {
        List<SyncTableLogs> list = syncTableLogsService.list();
        return HttpResult.success(list);
    }

    // ========== 新增 ==========

    /**
     * 新增日志
     * POST /api/sync-logs
     */
    @PostMapping
    public HttpResult<Boolean> add(@RequestBody SyncTableLogs log) {
        // 设置创建时间
        if (log.getCreateTime() == null) {
            log.setCreateTime(LocalDateTime.now());
        }
        boolean success = syncTableLogsService.save(log);
        return success ? HttpResult.success(true) : HttpResult.error("新增日志失败");
    }

    /**
     * 批量新增日志
     * POST /api/sync-logs/batch
     */
    @PostMapping("/batch")
    public HttpResult<Boolean> batchAdd(@RequestBody List<SyncTableLogs> logs) {
        boolean success = syncTableLogsService.batchInsert(logs);
        return success ? HttpResult.success(true) : HttpResult.error("批量新增失败");
    }

    /**
     * 保存或更新（存在则更新，不存在则插入）
     * POST /api/sync-logs/saveOrUpdate
     */
    @PostMapping("/saveOrUpdate")
    public HttpResult<Boolean> saveOrUpdate(@RequestBody SyncTableLogs log) {
        boolean success = syncTableLogsService.saveOrUpdateLog(log);
        return success ? HttpResult.success(true) : HttpResult.error("保存或更新失败");
    }

    // ========== 更新 ==========

    /**
     * 更新日志
     * PUT /api/sync-logs
     * 注意：由于 timeId 和 result 是复合主键，更新时不能修改这两个字段
     */
    @PutMapping
    public HttpResult<Boolean> update(@RequestBody SyncTableLogs log) {
        // 使用条件更新
        LambdaQueryWrapper<SyncTableLogs> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SyncTableLogs::getTimeId, log.getTimeId())
                .eq(SyncTableLogs::getResult, log.getResult());

        // 只更新 localResult 字段（如果有其他字段需要更新，在这里设置）
        SyncTableLogs update = new SyncTableLogs();
        update.setLocalResult(log.getLocalResult());

        boolean success = syncTableLogsService.update(update, wrapper);
        return success ? HttpResult.success(true) : HttpResult.error("更新失败");
    }

    /**
     * 更新本地处理结果
     * PUT /api/sync-logs/localResult/2026-06-28/1?localResult=1
     */
    @PutMapping("/localResult/{timeId}/{result}")
    public HttpResult<Boolean> updateLocalResult(
            @PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate timeId,
            @PathVariable Integer result,
            @RequestParam Integer localResult) {

        LambdaQueryWrapper<SyncTableLogs> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SyncTableLogs::getTimeId, timeId)
                .eq(SyncTableLogs::getResult, result);

        SyncTableLogs update = new SyncTableLogs();
        update.setLocalResult(localResult);

        boolean success = syncTableLogsService.update(update, wrapper);
        return success ? HttpResult.success(true) : HttpResult.error("更新本地处理结果失败");
    }

    // ========== 删除 ==========

    /**
     * 根据日期和结果删除
     * DELETE /api/sync-logs/2026-06-28/1
     */
    @DeleteMapping("/{timeId}/{result}")
    public HttpResult<Boolean> delete(
            @PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate timeId,
            @PathVariable Integer result) {

        boolean success = syncTableLogsService.deleteByTimeIdAndResult(timeId, result);
        return success ? HttpResult.success(true) : HttpResult.error("删除失败");
    }

    /**
     * 根据日期删除所有日志
     * DELETE /api/sync-logs/timeId/2026-06-28
     */
    @DeleteMapping("/timeId/{timeId}")
    public HttpResult<Boolean> deleteByTimeId(
            @PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate timeId) {

        boolean success = syncTableLogsService.deleteByTimeId(timeId);
        return success ? HttpResult.success(true) : HttpResult.error("删除失败");
    }

    /**
     * 批量删除
     * DELETE /api/sync-logs/batch
     */
    @DeleteMapping("/batch")
    public HttpResult<Boolean> deleteBatch(@RequestBody List<SyncTableLogs> logs) {
        if (logs == null || logs.isEmpty()) {
            return HttpResult.error("请选择要删除的记录");
        }

        // 构建删除条件
        LambdaQueryWrapper<SyncTableLogs> wrapper = new LambdaQueryWrapper<>();
        for (SyncTableLogs log : logs) {
            wrapper.or(w -> w.eq(SyncTableLogs::getTimeId, log.getTimeId())
                    .eq(SyncTableLogs::getResult, log.getResult()));
        }

        boolean success = syncTableLogsService.remove(wrapper);
        return success ? HttpResult.success(true) : HttpResult.error("批量删除失败");
    }
}