package com.aircraft.modules.article.service.impl;

import com.aircraft.modules.article.controller.CpArticleController;
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.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 文章表 服务实现类
 * </p>
 *
 * @author cli
 * @since 2025-07-10
 */
@Service
public class CpArticleServiceImpl extends ServiceImpl<CpArticleMapper, CpArticle> implements CpArticleService {
    private static final Logger LOG = LoggerFactory.getLogger(CpArticleController.class);

    @Autowired
    private CpArticleMapper cpArticleMapper;
    @Autowired
    private CpLabelMapper cpLabelMapper;
    @Autowired
    private CpTextService cpTextService;

    @Override
    public IPage<CpArticleVo> findByPage(Page<CpArticleVo> page, CpArticleDTO cpArticleDTO) {
        // 执行分页查询
        IPage<CpArticleVo> cpArticleVoIPage = cpArticleMapper.selectVoPage(page, cpArticleDTO);
        return cpArticleVoIPage;
    }

    @Override
    public CpArticleVo getArticleById(Integer id) {
        CpArticleVo entity = cpArticleMapper.selectVoById(id);
        return entity;
    }

    @Override
    public ResponseEntity<?> updateById(CpArticleDTO entity, 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 cpLabelVo = cpLabelMapper.findById(entity.getLabelId());
            if (cpLabelVo == null) {
                Map<String, Object> error = new HashMap<>();
                error.put("code", 400);
                error.put("msg", "标签不存在");
                return ResponseEntity.badRequest().body(error);
            }
            //更新模块信息
            cpLabelMapper.updateModuleIdById(entity.getModuleId());

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

            // 更新文章内容
            if (existingArticle.getTextid() == null) {
                Map<String, Object> error = new HashMap<>();
                error.put("code", 400);
                error.put("msg", "文章内容ID不存在");
                return ResponseEntity.badRequest().body(error);
            }
            boolean textUpdated = cpTextService.lambdaUpdate()
                    .set(CpText::getText, entity.getText())
                    .eq(CpText::getId, existingArticle.getTextid())
                    .update();
            if (!textUpdated) {
                Map<String, Object> error = new HashMap<>();
                error.put("code", 500);
                error.put("msg", "文章内容更新失败");
                return ResponseEntity.status(500).body(error);
            }

            cpArticleMapper.updateById(entity);
            return ResponseEntity.ok().build();

        } 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);
        }
    }

    @Override
    public List<CpArticle> list(CpArticle example) {
        // 转换example为QueryWrapper条件
        QueryWrapper<CpArticle> wrapper = new QueryWrapper<>(example);
        // 添加逻辑删除过滤（如果需要）
        wrapper.eq("del_flag", 0);
        return baseMapper.selectList(wrapper);
    }

    @Override
    public void updateDelFlagById(Long id, Integer delFlag) {
        baseMapper.updateDelFlagById(id, delFlag);
    }

}
