package com.aircraft.modules.article.controller;

import com.aircraft.annotation.rest.AnonymousAccess;
import com.aircraft.annotation.rest.AnonymousGetMapping;
import com.aircraft.modules.article.domain.CpArticle;
import com.aircraft.modules.article.domain.CpText;
import com.aircraft.modules.article.mapper.CpLabelMapper;
import com.aircraft.modules.article.mapper.CpTextMapper;
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.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.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * <p>
 * 文本内容 前端控制器
 * </p>
 *
 * @author cli
 * @since 2025-07-11
 */
@Api(tags = "系统：文本内容管理")
@RestController
@RequestMapping("/cpText")
public class CpTextController {
    private static final Logger LOG = LoggerFactory.getLogger(CpTextController.class);

    @Autowired
    private CpTextService cpTextService;
    @Autowired
    private CpArticleService cpArticleService;
    @Autowired
    private CpTextMapper cpTextMapper;

    @AnonymousAccess
    @ApiOperation(value = "分页查询文本内容", notes = "分页查询文本内容")
    @RequestMapping(method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "size", value = "分页大小", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页面：从1开始", paramType = "query")
    })
    public ResponseEntity<IPage<CpText>> findByPage(final Page<CpText> page, @RequestParam(required = false) String keyWord) {
        try {
            IPage<CpText> records = cpTextService.findByPage(page, keyWord);
            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<Void> delete(@PathVariable final Integer id) {
        try {
            CpText cpText = cpTextService.getById(id);
            if (cpText == null) {
                return ResponseEntity.notFound().build();
            }

            // 检查是否有关联的文章
            List<CpArticle> articles = cpArticleService.lambdaQuery()
                    .eq(CpArticle::getTextid, id)
                    .list();

            if (articles != null && !articles.isEmpty()) {
                // 逻辑删除关联的文章
                articles.forEach(article -> {
                    article.setDelFlag(1);
                    cpArticleService.updateById(article);
                });
            }

            // 物理删除文本内容
            cpTextService.removeById(id);
            return ResponseEntity.noContent().build();
        } 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();
        }
    }

    @AnonymousAccess
    @ApiOperation(value = "查询单个文本内容")
    @GetMapping(value = "/{id}")
    @ApiImplicitParam(name = "id", value = "文本内容ID", required = true, paramType = "path")
    public ResponseEntity<CpText> one(@PathVariable final Integer id) {
        try {
            CpText entity = cpTextService.getById(id);
            if (entity == null) {
                return ResponseEntity.notFound().build();
            }
            cpTextMapper.updateViewCountById(id);
            entity.setViewCount(entity.getViewCount() + 1);
            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<CpText> add(@Valid @RequestBody final CpText cpText, final BindingResult result) {
        try {
            if (result.hasErrors()) {
                String errorMsg = Optional.ofNullable(result.getFieldErrors())
                        .flatMap(errors -> errors.stream().findFirst())
                        .map(FieldError::getDefaultMessage)
                        .orElse("参数验证失败");
                return ResponseEntity.badRequest().body(null);
            }

            // 保存文本内容
            cpTextService.save(cpText);

            // 返回201 Created状态和创建的资源
            return ResponseEntity
                    .created(URI.create("/cpText/" + cpText.getId()))
                    .body(cpText);
        } catch (Exception e) {
            LOG.error("添加文本内容失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

    @ApiOperation(value = "修改文本内容")
    @RequestMapping(method = {RequestMethod.PUT})
    public ResponseEntity<?> update(@Valid @RequestBody final CpText entity, final BindingResult result) {
        try {
            // 处理参数校验错误
            if (result.hasErrors()) {
                Map<String, Object> error = new HashMap<>();
                error.put("code", 400);
                error.put("msg", result.getFieldErrors().get(0).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);
            }

            // 校验文本内容是否存在
            CpText existingText = cpTextService.getById(entity.getId());
            if (existingText == null) {
                Map<String, Object> error = new HashMap<>();
                error.put("code", 404);
                error.put("msg", "文本内容不存在");
                return ResponseEntity.status(404).body(error);
            }

            // 更新文本内容
            boolean updated = cpTextService.lambdaUpdate()
                    .set(CpText::getText, entity.getText())
                    .eq(CpText::getId, entity.getId())
                    .update();

            if (!updated) {
                Map<String, Object> error = new HashMap<>();
                error.put("code", 500);
                error.put("msg", "文本内容更新失败");
                return ResponseEntity.status(500).body(error);
            }

            // 成功响应：返回更新后的文本内容数据
            return ResponseEntity.ok(cpTextService.getById(entity.getId()));

        } 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<CpText>> all(CpText example) {
        QueryWrapper<CpText> queryWrapper = new QueryWrapper<>(example);
        List<CpText> entitys = cpTextService.list(queryWrapper);
        if (entitys != null) {
            return ResponseEntity.ok(entitys);
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }

    @ApiOperation(value = "获取文本内容关联的文章")
    @RequestMapping(value = "{id}/articles", method = RequestMethod.GET)
    @ApiImplicitParam(name = "id", value = "文本内容ID", required = true, paramType = "path")
    public ResponseEntity<List<CpArticle>> getArticlesByTextId(@PathVariable final Integer id) {
        try {
            List<CpArticle> articles = cpArticleService.lambdaQuery()
                    .eq(CpArticle::getTextid, id)
                    .eq(CpArticle::getDelFlag, 0)
                    .list();
            return ResponseEntity.ok(articles);
        } catch (Exception e) {
            LOG.error("获取文本内容关联的文章失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}