package com.emotion.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.emotion.common.PageResult;
import com.emotion.dto.request.LifePathCreateRequest;
import com.emotion.dto.request.LifePathPageRequest;
import com.emotion.dto.request.LifePathUpdateRequest;
import com.emotion.dto.response.LifePathResponse;
import com.emotion.entity.LifePath;
import com.emotion.mapper.LifePathMapper;
import com.emotion.service.LifePathService;
import com.emotion.util.UserContextHolder;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 实现路径服务实现类
 *
 * @author huazhongmin
 * @date 2025-12-22
 */
@Service
public class LifePathServiceImpl extends ServiceImpl<LifePathMapper, LifePath> 
        implements LifePathService {

    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public PageResult<LifePathResponse> getPageByCurrentUser(LifePathPageRequest request) {
        String currentUserId = UserContextHolder.getCurrentUserId();
        if (currentUserId == null) {
            return new PageResult<>();
        }

        Page<LifePath> page = new Page<>(request.getCurrent(), request.getSize());
        LambdaQueryWrapper<LifePath> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LifePath::getUserId, currentUserId)
                .eq(LifePath::getIsDeleted, 0);

        // 剧本ID筛选
        if (StringUtils.hasText(request.getScriptId())) {
            wrapper.eq(LifePath::getScriptId, request.getScriptId());
        }

        // 状态筛选
        if (StringUtils.hasText(request.getStatus())) {
            wrapper.eq(LifePath::getStatus, request.getStatus());
        }

        // 按创建时间倒序排列
        wrapper.orderByDesc(LifePath::getCreateTime);

        Page<LifePath> resultPage = this.page(page, wrapper);
        List<LifePathResponse> responses = resultPage.getRecords().stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());

        PageResult<LifePathResponse> pageResult = new PageResult<>();
        pageResult.setCurrent(resultPage.getCurrent());
        pageResult.setSize(resultPage.getSize());
        pageResult.setTotal(resultPage.getTotal());
        pageResult.setPages(resultPage.getPages());
        pageResult.setRecords(responses);

        return pageResult;
    }

    @Override
    public List<LifePathResponse> getListByCurrentUser() {
        String currentUserId = UserContextHolder.getCurrentUserId();
        if (currentUserId == null) {
            return List.of();
        }

        LambdaQueryWrapper<LifePath> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LifePath::getUserId, currentUserId)
                .eq(LifePath::getIsDeleted, 0)
                .orderByDesc(LifePath::getCreateTime);

        return this.list(wrapper).stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
    }

    @Override
    public LifePathResponse getByScriptId(String scriptId) {
        String currentUserId = UserContextHolder.getCurrentUserId();
        if (currentUserId == null) {
            return null;
        }

        LambdaQueryWrapper<LifePath> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LifePath::getUserId, currentUserId)
                .eq(LifePath::getScriptId, scriptId)
                .eq(LifePath::getIsDeleted, 0);

        LifePath path = this.getOne(wrapper);
        return path != null ? convertToResponse(path) : null;
    }

    @Override
    public LifePathResponse getPathById(String id) {
        LifePath path = this.getById(id);
        if (path == null || path.getIsDeleted() == 1) {
            return null;
        }

        // 验证权限
        String currentUserId = UserContextHolder.getCurrentUserId();
        if (!path.getUserId().equals(currentUserId)) {
            return null;
        }

        return convertToResponse(path);
    }

    @Override
    public LifePathResponse createPath(LifePathCreateRequest request) {
        String currentUserId = UserContextHolder.getCurrentUserId();
        if (currentUserId == null) {
            return null;
        }

        LifePath path = new LifePath();
        path.setUserId(currentUserId);
        path.setScriptId(request.getScriptId());
        path.setTitle(request.getTitle());
        path.setDescription(request.getDescription());
        path.setSteps(request.getSteps());
        path.setStatus(StringUtils.hasText(request.getStatus()) ? request.getStatus() : "active");
        path.setProgress(request.getProgress() != null ? BigDecimal.valueOf(request.getProgress()) : BigDecimal.ZERO);

        this.save(path);
        return convertToResponse(path);
    }


    @Override
    public LifePathResponse updatePath(LifePathUpdateRequest request) {
        LifePath path = this.getById(request.getId());
        if (path == null || path.getIsDeleted() == 1) {
            return null;
        }

        // 验证权限
        String currentUserId = UserContextHolder.getCurrentUserId();
        if (!path.getUserId().equals(currentUserId)) {
            return null;
        }

        // 更新字段
        if (StringUtils.hasText(request.getTitle())) {
            path.setTitle(request.getTitle());
        }
        if (request.getDescription() != null) {
            path.setDescription(request.getDescription());
        }
        if (request.getSteps() != null) {
            path.setSteps(request.getSteps());
        }
        if (StringUtils.hasText(request.getStatus())) {
            path.setStatus(request.getStatus());
        }
        if (request.getProgress() != null) {
            path.setProgress(BigDecimal.valueOf(request.getProgress()));
        }

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

    @Override
    public boolean deletePath(String id) {
        LifePath path = this.getById(id);
        if (path == null) {
            return false;
        }

        // 验证权限
        String currentUserId = UserContextHolder.getCurrentUserId();
        if (!path.getUserId().equals(currentUserId)) {
            return false;
        }

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

    @Override
    public boolean deleteByScriptId(String scriptId) {
        String currentUserId = UserContextHolder.getCurrentUserId();
        if (currentUserId == null) {
            return false;
        }

        LambdaQueryWrapper<LifePath> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LifePath::getUserId, currentUserId)
                .eq(LifePath::getScriptId, scriptId);

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

    /**
     * 转换为响应对象
     */
    private LifePathResponse convertToResponse(LifePath path) {
        LifePathResponse response = new LifePathResponse();
        BeanUtils.copyProperties(path, response);
        response.setId(path.getId());
        if (path.getProgress() != null) {
            response.setProgress(path.getProgress().doubleValue());
        }
        if (path.getCreateTime() != null) {
            response.setCreateTime(path.getCreateTime().format(DATE_TIME_FORMATTER));
        }
        if (path.getUpdateTime() != null) {
            response.setUpdateTime(path.getUpdateTime().format(DATE_TIME_FORMATTER));
        }
        return response;
    }
}
