package com.aircraft.modules.article.controller;

import com.aircraft.modules.article.domain.CpLabel;
import com.aircraft.modules.article.domain.dto.CpLabelDTO;
import com.aircraft.modules.article.domain.dto.CpLabelVo;
import com.aircraft.modules.article.mapper.CpLabelMapper;
import com.aircraft.modules.article.service.CpLabelService;
import com.aircraft.modules.article.service.CpModuleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.net.URI;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 标签表 前端控制器
 * </p>
 *
 * @author cli
 * @since 2025-07-10
 */
@Api(tags = "系统：标签管理")
@RestController
@RequestMapping("/cpLabel")
public class CpLabelController {
    private static final Logger LOG = LoggerFactory.getLogger(CpLabelController.class);

    @Autowired
    private CpLabelService entityService;

    @Autowired
    private CpLabelMapper cpLabelMapper;
    @Autowired
    private CpModuleService cpModuleService;

    @ApiOperation(value = "分页查询标签(name模糊查询)", notes = "分页查询标签")
    @RequestMapping(method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "size", value = "分页大小", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页面：从1开始", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "name进行模糊查询", paramType = "query")
    })
    public ResponseEntity<IPage<CpLabelVo>> findByPage(final Page<CpLabelVo> page, @RequestParam(required = false) String name) {
        try {
            IPage<CpLabelVo> records = entityService.findByPage(page, name);
            return new ResponseEntity<>(records, HttpStatus.OK);
        } catch (Exception e) {
            LOG.error("分页查询标签时出错", e);
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @ApiOperation(value = "删除标签")
    @RequestMapping(value = "{id}", method = {RequestMethod.DELETE})
    @ApiImplicitParam(name = "id", value = "标签ID", required = true, paramType = "path")
    public ResponseEntity<?> delete(@PathVariable final Integer id) {
        try {
            CpLabel cpLabel = entityService.getById(id);
            if (cpLabel == null) {
                return ResponseEntity.notFound().build();
            }
            cpLabel.setDelFlag(1); // 逻辑删除
            entityService.updateDelFlagById(id, cpLabel.getDelFlag());
            // 3. 删除成功，返回成功信息
            Map<String, Object> success = new HashMap<>();
            success.put("code", 200);
            success.put("msg", "删除成功");
            return ResponseEntity.ok(success);
        } catch (DataIntegrityViolationException e) {
            LOG.error("删除标签失败: 数据完整性冲突", e);
            return ResponseEntity.status(HttpStatus.CONFLICT).build();
        } catch (Exception e) {
            LOG.error("删除标签失败: 未知错误", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    @ApiOperation(value = "查询单个标签")
    @RequestMapping(value = "{id}", method = {RequestMethod.GET})
    @ApiImplicitParam(name = "id", value = "标签ID", required = true, paramType = "path")
    public ResponseEntity<CpLabel> one(@PathVariable final Integer id) {
        try {
            CpLabel entity = cpLabelMapper.selectById(id);
            if (entity == null || entity.getDelFlag() == 1) {
                return ResponseEntity.notFound().build();
            }
            return ResponseEntity.ok(entity);
        } catch (Exception e) {
            LOG.error("查询单个标签失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    @ApiOperation(value = "添加标签")
    @RequestMapping(method = {RequestMethod.POST})
    public ResponseEntity<?> add(@Valid @RequestBody final CpLabelDTO cpLabelDTO, final BindingResult result) {
        try {
            if (result.hasErrors()) {
                String errorMsg = result.getFieldErrors().stream()
                        .map(FieldError::getDefaultMessage)
                        .findFirst()
                        .orElse("参数验证失败");
                return ResponseEntity.badRequest().body(Map.of("message", errorMsg));
            }

            // 检查模块是否存在
            Integer moduleId = cpLabelDTO.getModuleId();
            if (moduleId == null || !cpModuleService.existsById(moduleId)) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(Map.of("message", "不存在该模块"));
            }

            CpLabel cpLabel = new CpLabel();
            BeanUtils.copyProperties(cpLabelDTO, cpLabel);
            // 设置默认值
            cpLabel.setCreateTime(LocalDateTime.now());
            cpLabel.setDelFlag(0);

            // 保存标签
            entityService.save(cpLabel);

            // 返回201 Created状态和创建的资源
            return ResponseEntity
                    .created(URI.create("/cpLabel/" + cpLabel.getId()))
                    .body(cpLabelDTO);
        } catch (Exception e) {
            LOG.error("添加标签失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("message", "添加标签失败，请稍后重试"));
        }
    }

    @ApiOperation(value = "修改标签")
    @RequestMapping(method = {RequestMethod.PUT})
    public ResponseEntity<?> update(@Valid @RequestBody final CpLabel entity, final BindingResult result) {
        try {
            // 处理参数校验错误
            if (result.hasErrors()) {
                Map<String, Object> error = new HashMap<>();
                error.put("code", 400);
                FieldError firstError = result.getFieldErrors().get(0);
                error.put("msg", firstError.getField() + "：" + firstError.getDefaultMessage());
                return ResponseEntity.badRequest().body(error);
            }

            // 校验ID是否存在
            if (entity.getId() == null) {
                Map<String, Object> error = new HashMap<>();
                error.put("code", 400);
                error.put("msg", "id不能为空");
                return ResponseEntity.badRequest().body(error);
            }

            // 校验标签是否存在
            CpLabel existingLabel = entityService.getById(entity.getId());
            if (existingLabel == null) {
                Map<String, Object> error = new HashMap<>();
                error.put("code", 404);
                error.put("msg", "标签不存在");
                return ResponseEntity.status(404).body(error);
            }

            // 更新标签
            entityService.updateById(entity);

            // 成功响应
            return ResponseEntity.ok(Map.of("code", 200, "msg", "修改标签成功"));
//            return ResponseEntity.ok(entity);

        } catch (Exception e) {
            LOG.error("修改标签失败", e);
            Map<String, Object> error = new HashMap<>();
            error.put("code", 500);
            error.put("msg", "修改标签失败：" + e.getMessage());
            return ResponseEntity.status(500).body(error);
        }
    }

    @ApiOperation(value = "全部标签")
    @RequestMapping(value = "all", method = RequestMethod.GET)
    public ResponseEntity<List<CpLabel>> all(CpLabel example) {
        try {
            List<CpLabel> entitys = entityService.list(new QueryWrapper<>(example));
            return ResponseEntity.ok(entitys);
        } catch (Exception e) {
            LOG.error("查询全部标签失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}