package com.emotion.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.emotion.common.BasePageRequest;
import com.emotion.common.PageResult;
import com.emotion.dto.request.growth.GrowthTopicCreateRequest;
import com.emotion.dto.request.growth.GrowthTopicUpdateRequest;
import com.emotion.dto.response.growth.GrowthTopicResponse;
import com.emotion.entity.GrowthTopic;
import com.emotion.mapper.GrowthTopicMapper;
import com.emotion.service.GrowthTopicService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 成长话题服务实现类
 * 
 * @author huazhongmin
 * @date 2025-09-08
 */
@Service
public class GrowthTopicServiceImpl extends ServiceImpl<GrowthTopicMapper, GrowthTopic> implements GrowthTopicService {

    @Override
    public IPage<GrowthTopic> getPage(BasePageRequest request) {
        Page<GrowthTopic> page = new Page<>(request.getCurrent(), request.getSize());
        LambdaQueryWrapper<GrowthTopic> wrapper = new LambdaQueryWrapper<>();
        
        // 关键词搜索
        if (StringUtils.hasText(request.getKeyword())) {
            wrapper.and(w -> w.like(GrowthTopic::getTitle, request.getKeyword())
                    .or().like(GrowthTopic::getDescription, request.getKeyword()));
        }
        
        wrapper.eq(GrowthTopic::getIsDeleted, 0);
        
        // 排序
        if (StringUtils.hasText(request.getOrderBy())) {
            if ("asc".equalsIgnoreCase(request.getOrderDirection())) {
                wrapper.orderByAsc(GrowthTopic::getCreateTime);
            } else {
                wrapper.orderByDesc(GrowthTopic::getCreateTime);
            }
        } else {
            wrapper.orderByDesc(GrowthTopic::getCreateTime);
        }
        
        return this.page(page, wrapper);
    }

    @Override
    public PageResult<GrowthTopicResponse> getPageWithResponse(BasePageRequest request) {
        IPage<GrowthTopic> page = getPage(request);
        List<GrowthTopicResponse> responses = page.getRecords().stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
        PageResult<GrowthTopicResponse> pageResult = new PageResult<>();
        pageResult.setRecords(responses);
        pageResult.setCurrent(page.getCurrent());
        pageResult.setSize(page.getSize());
        pageResult.setTotal(page.getTotal());
        pageResult.setPages(page.getPages());
        return pageResult;
    }

    @Override
    public GrowthTopicResponse getGrowthTopicResponseById(String id) {
        GrowthTopic topic = this.getById(id);
        if (topic == null || topic.getIsDeleted() == 1) {
            return null;
        }
        return convertToResponse(topic);
    }

    @Override
    public GrowthTopic createGrowthTopic(String title, String description, String category,
            String difficultyLevel, String tags, LocalDateTime endTime) {
        GrowthTopic topic = new GrowthTopic();
        topic.setTitle(title);
        topic.setDescription(description);
        topic.setCategory(category);
        topic.setDifficulty(difficultyLevel);
        topic.setContent(description);
        topic.setDurationDays(30); // 默认30天
        topic.setIsUnlocked(1);
        topic.setProgress(BigDecimal.ZERO);
        topic.setRewards("成长积分");

        this.save(topic);
        return topic;
    }

    @Override
    public GrowthTopicResponse createGrowthTopicWithResponse(GrowthTopicCreateRequest request) {
        GrowthTopic topic = createGrowthTopic(
                request.getTitle(),
                request.getDescription(),
                request.getCategory(),
                request.getDifficultyLevel(),
                request.getTags(),
                request.getEndTime());
        return convertToResponse(topic);
    }

    @Override
    public GrowthTopicResponse updateGrowthTopicWithResponse(GrowthTopicUpdateRequest request) {
        GrowthTopic topic = this.getById(request.getId());
        if (topic == null || topic.getIsDeleted() == 1) {
            return null;
        }

        // 只更新非空字段
        if (StringUtils.hasText(request.getTitle())) {
            topic.setTitle(request.getTitle());
        }
        if (StringUtils.hasText(request.getDescription())) {
            topic.setDescription(request.getDescription());
            topic.setContent(request.getDescription());
        }
        if (StringUtils.hasText(request.getCategory())) {
            topic.setCategory(request.getCategory());
        }
        if (StringUtils.hasText(request.getDifficultyLevel())) {
            topic.setDifficulty(request.getDifficultyLevel());
        }
        if (StringUtils.hasText(request.getTags())) {
            // GrowthTopic实体中没有tags字段，暂时忽略
        }
        if (request.getEndTime() != null) {
            // GrowthTopic实体中没有endTime字段，暂时忽略
        }

        this.updateById(topic);
        return convertToResponse(topic);
    }

    @Override
    public boolean deleteGrowthTopic(String id) {
        GrowthTopic topic = this.getById(id);
        if (topic == null) {
            return false;
        }

        // 使用 MyBatis-Plus 的 removeById 方法，自动处理逻辑删除
        return this.removeById(id);
    }

    /**
     * 将实体转换为响应对象
     */
    private GrowthTopicResponse convertToResponse(GrowthTopic topic) {
        if (topic == null) {
            return null;
        }

        GrowthTopicResponse response = new GrowthTopicResponse();
        BeanUtils.copyProperties(topic, response);
        response.setId(topic.getId());
        if (topic.getCreateTime() != null) {
            response.setCreateTime(topic.getCreateTime().toString());
        }
        if (topic.getUpdateTime() != null) {
            response.setUpdateTime(topic.getUpdateTime().toString());
        }
        return response;
    }
}