package com.rj.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rj.entity.RedLineRecord;
import com.rj.service.IRedLineRecordService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 触及红线记录表前端控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/redLineRecord")
@Tag(name = "触及红线记录(red_line_record)", description = "增删改查与分页")
public class RedLineRecordController {

    @Autowired
    private IRedLineRecordService redLineRecordService;

    @PostMapping("/add")
    @Operation(summary = "新增")
    public ResponseEntity<Map<String, Object>> add(
            @Parameter(description = "实体", required = true) @RequestBody RedLineRecord entity) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (entity.getId() == null || entity.getId().trim().isEmpty()) {
                entity.setId(UUID.randomUUID().toString());
            }
            LocalDateTime now = LocalDateTime.now();
            if (entity.getCreateTime() == null) {
                entity.setCreateTime(now);
            }
            entity.setUpdateTime(now);
            boolean ok = redLineRecordService.save(entity);
            if (ok) {
                result.put("success", true);
                result.put("message", "添加成功");
                result.put("data", entity);
                return ResponseEntity.ok(result);
            }
            result.put("success", false);
            result.put("message", "添加失败");
            return ResponseEntity.badRequest().body(result);
        } catch (Exception e) {
            log.error("red_line_record add error", e);
            result.put("success", false);
            result.put("message", "添加异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    @GetMapping("/get/{id}")
    @Operation(summary = "按ID查询")
    public ResponseEntity<Map<String, Object>> getById(@PathVariable String id) {
        Map<String, Object> result = new HashMap<>();
        try {
            RedLineRecord one = redLineRecordService.getById(id);
            if (one != null) {
                result.put("success", true);
                result.put("message", "查询成功");
                result.put("data", one);
                return ResponseEntity.ok(result);
            }
            result.put("success", false);
            result.put("message", "记录不存在");
            return ResponseEntity.notFound().build();
        } catch (Exception e) {
            log.error("red_line_record get error, id={}", id, e);
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    @GetMapping("/list")
    @Operation(summary = "分页查询")
    public ResponseEntity<Map<String, Object>> list(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String audioManagementId,
            @RequestParam(required = false) String audioManagementSegmentsId,
            @RequestParam(required = false) String redLineType,
            @RequestParam(required = false) String redLineSubtype,
            @RequestParam(required = false) String salesId,
            @RequestParam(required = false) String reasonKeyword,
            @RequestParam(required = false) String createStartTime,
            @RequestParam(required = false) String createEndTime) {
        Map<String, Object> result = new HashMap<>();
        try {
            Page<RedLineRecord> page = new Page<>(current, size);
            LambdaQueryWrapper<RedLineRecord> q = new LambdaQueryWrapper<>();
            if (audioManagementId != null && !audioManagementId.trim().isEmpty()) {
                q.eq(RedLineRecord::getAudioManagementId, audioManagementId);
            }
            if (audioManagementSegmentsId != null && !audioManagementSegmentsId.trim().isEmpty()) {
                q.eq(RedLineRecord::getAudioManagementSegmentsId, audioManagementSegmentsId);
            }
            if (redLineType != null && !redLineType.trim().isEmpty()) {
                q.eq(RedLineRecord::getRedLineType, redLineType);
            }
            if (redLineSubtype != null && !redLineSubtype.trim().isEmpty()) {
                q.eq(RedLineRecord::getRedLineSubtype, redLineSubtype);
            }
            if (salesId != null && !salesId.trim().isEmpty()) {
                q.eq(RedLineRecord::getSalesId, salesId);
            }
            if (reasonKeyword != null && !reasonKeyword.trim().isEmpty()) {
                q.like(RedLineRecord::getReasonText, reasonKeyword);
            }
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            if (createStartTime != null && !createStartTime.trim().isEmpty()) {
                try {
                    q.ge(RedLineRecord::getCreateTime, LocalDateTime.parse(createStartTime, formatter));
                } catch (Exception ex) {
                    result.put("success", false);
                    result.put("message", "创建开始时间格式错误，请使用：yyyy-MM-dd HH:mm:ss");
                    return ResponseEntity.badRequest().body(result);
                }
            }
            if (createEndTime != null && !createEndTime.trim().isEmpty()) {
                try {
                    q.le(RedLineRecord::getCreateTime, LocalDateTime.parse(createEndTime, formatter));
                } catch (Exception ex) {
                    result.put("success", false);
                    result.put("message", "创建结束时间格式错误，请使用：yyyy-MM-dd HH:mm:ss");
                    return ResponseEntity.badRequest().body(result);
                }
            }
            q.orderByDesc(RedLineRecord::getCreateTime);
            Page<RedLineRecord> data = redLineRecordService.page(page, q);
            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", data.getRecords());
            result.put("total", data.getTotal());
            result.put("current", data.getCurrent());
            result.put("size", data.getSize());
            result.put("pages", data.getPages());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("red_line_record list error", e);
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    @PutMapping("/update")
    @Operation(summary = "更新")
    public ResponseEntity<Map<String, Object>> update(@RequestBody RedLineRecord entity) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (entity.getId() == null || entity.getId().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "ID不能为空");
                return ResponseEntity.badRequest().body(result);
            }
            entity.setUpdateTime(LocalDateTime.now());
            boolean ok = redLineRecordService.updateById(entity);
            if (ok) {
                result.put("success", true);
                result.put("message", "更新成功");
                result.put("data", redLineRecordService.getById(entity.getId()));
                return ResponseEntity.ok(result);
            }
            result.put("success", false);
            result.put("message", "更新失败");
            return ResponseEntity.badRequest().body(result);
        } catch (Exception e) {
            log.error("red_line_record update error", e);
            result.put("success", false);
            result.put("message", "更新异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除")
    public ResponseEntity<Map<String, Object>> delete(@PathVariable String id) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean ok = redLineRecordService.removeById(id);
            if (ok) {
                result.put("success", true);
                result.put("message", "删除成功");
                return ResponseEntity.ok(result);
            }
            result.put("success", false);
            result.put("message", "删除失败");
            return ResponseEntity.badRequest().body(result);
        } catch (Exception e) {
            log.error("red_line_record delete error", e);
            result.put("success", false);
            result.put("message", "删除异常：" + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }
}
