package com.aircraft.modules.article.controller;


import com.aircraft.modules.article.domain.CpArticle;
import com.aircraft.modules.article.domain.CpLabel;
import com.aircraft.modules.article.domain.CpText;
import com.aircraft.modules.article.domain.dto.CpArticleDTO;
import com.aircraft.modules.article.domain.dto.CpArticleVo;
import com.aircraft.modules.article.mapper.CpArticleMapper;
import com.aircraft.modules.article.mapper.CpLabelMapper;
import com.aircraft.modules.article.service.CpArticleService;
import com.aircraft.modules.article.service.CpTextService;
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.*;

import static com.aircraft.utils.SecurityUtils.getCurrentUserId;

/**
 * <p>
 * 文章表 前端控制器
 * </p>
 *
 * @author cli
 * @since 2025-07-10
 */
@Api(tags = "系统：文章管理")
@RestController
@RequestMapping("/cpArticle")
public class CpArticleController {
    private static final Logger LOG = LoggerFactory.getLogger(CpArticleController.class);
    @Autowired
    private CpArticleService entityService;
    @Autowired
    private CpTextService cpTextService;
    @Autowired
    private CpLabelMapper cpLabelMapper;

    @ApiOperation(value = "分页查询文章（title模糊查询）", notes = "分页查询文章，仅根据文章标题进行模糊查询")
    @RequestMapping(method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "size", value = "分页大小", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页面：从1开始", paramType = "query")
    })
    public ResponseEntity<IPage<CpArticleVo>> findByPage(
            final Page<CpArticleVo> page, CpArticleDTO cpArticleDTO) {
        IPage<CpArticleVo> records = entityService.findByPage(page, cpArticleDTO);
        return new ResponseEntity<>(records, HttpStatus.OK);
    }

    @ApiOperation(value = "删除文章")
    @RequestMapping(value = "{id}", method = {RequestMethod.DELETE})
    @ApiImplicitParam(name = "id", value = "文章ID", required = true, paramType = "path")
    public ResponseEntity<?> delete(@PathVariable final Long id) {
        try {
            CpArticle cpArticle = entityService.getById(id);
            if (cpArticle == null) {
                return ResponseEntity.notFound().build();
            }
            cpArticle.setDelFlag(1);
            entityService.updateDelFlagById(id, cpArticle.getDelFlag());
            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<?> one(@PathVariable final Integer id) {
        try {
            CpArticleVo entity = entityService.getArticleById(id);
            if (entity == null || entity.getDelFlag() == 1) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("code", HttpStatus.NOT_FOUND.value());
                errorResponse.put("message", "不存在该文章");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(errorResponse);
            }
//            cpArticleMapper.updateViewCountById(id);
//            entity.setViewCount(entity.getViewCount()+1);
            return ResponseEntity.ok(entity);
        } catch (Exception e) {
            LOG.error("查询单个文章失败", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", HttpStatus.INTERNAL_SERVER_ERROR.value());
            errorResponse.put("message", "查询文章失败，请稍后重试");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    @ApiOperation(value = "添加文章")
    @RequestMapping(method = {RequestMethod.POST})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "title", value = "文章标题", required = true, paramType = "query"),
            @ApiImplicitParam(name = "text", value = "文章正文内容", required = true, paramType = "query"),
            @ApiImplicitParam(name = "labelId", value = "标签id", required = true, paramType = "query"),
            @ApiImplicitParam(name = "moduleId", value = "模块id", required = true, paramType = "query")
    })
    public ResponseEntity<?> add(@Valid @RequestBody final CpArticleDTO cpArticleDTO, final BindingResult result) {
        try {
            // 处理参数校验错误
            if (result.hasErrors()) {
                // 使用传统for循环提取第一个错误信息
                String errorMsg = null;
                for (FieldError error : result.getFieldErrors()) {
                    errorMsg = error.getField() + "：" + error.getDefaultMessage();
                    break;
                }
                if (errorMsg == null) {
                    errorMsg = "参数验证失败";
                }
                // 返回包含错误信息的响应体
                Map<String, Object> error = new HashMap<>();
                error.put("code", 400);
                error.put("msg", errorMsg);
                return ResponseEntity.badRequest().body(error);
            }

            // 查找标签信息
            CpLabel cpLabel = cpLabelMapper.findById(cpArticleDTO.getLabelId());
            if (cpLabel == null) {
                // 标签不存在时返回明确错误信息
                Map<String, Object> error = new HashMap<>();
                error.put("code", 400);
                error.put("msg", "标签不存在：标签名=" + cpArticleDTO.getLabelId());
                return ResponseEntity.badRequest().body(error);
            }

            // 关联标签与模块（关键步骤）
            cpLabel.setModuleId(cpArticleDTO.getModuleId());
            cpLabelMapper.updateById(cpLabel); // 更新标签的模块关联

            CpArticle cpArticle = new CpArticle();
            BeanUtils.copyProperties(cpArticleDTO, cpArticle);
            // 设置文章基础信息
            cpArticle.setCreateTime(LocalDateTime.now());
            cpArticle.setCheckState("t");// 默认已审核
            cpArticle.setDelFlag(0);
            cpArticle.setCplabelId(cpLabel.getId());// 关联标签ID

            Long authorId = getCurrentUserId();
            // 设置作者ID
            cpArticle.setAuthorId(authorId);
            entityService.save(cpArticle);

            // 保存文章内容
            CpText cpText = new CpText();
            cpText.setText(cpArticleDTO.getText());
            cpTextService.save(cpText);

            // 回填文章内容ID并更新
            cpArticle.setTextid(cpText.getId());
            entityService.updateById(cpArticle);

            // 返回创建成功的响应
            Map<String, Object> success = new HashMap<>();
            success.put("code", 201);
            success.put("msg", "文章创建成功");
            success.put("data", cpArticle);
            return ResponseEntity
                    .created(URI.create("/cpArticle/" + cpArticle.getId()))
                    .body(success);
        } catch (Exception e) {
            LOG.error("添加文章失败", e);
            // 服务器错误时返回错误信息
            Map<String, Object> error = new HashMap<>();
            error.put("code", 500);
            error.put("msg", "添加文章失败：" + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
        }
    }

    @ApiOperation(value = "修改文章")
    @RequestMapping(method = {RequestMethod.PUT})
    @ApiImplicitParam(name = "id", value = "文章id", required = true, paramType = "path")
    public ResponseEntity<?> update(@Valid @RequestBody final CpArticleDTO entity, final BindingResult result) {
        return entityService.updateById(entity, result);
    }

    @ApiOperation(value = "全部文章")
    @RequestMapping(value = "all", method = RequestMethod.GET)
    public ResponseEntity<List<CpArticle>> all(CpArticle example) {
        List<CpArticle> entitys = entityService.list(example);
        if (null != entitys) {
            // 即使列表为空（size=0），也返回200 OK和空列表，而非404
            return ResponseEntity.ok(entitys);
        }
        // 仅当查询结果为null时（通常是查询异常），返回500错误
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }
}

