package com.competition.modules.pub.service;

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.competition.common.exception.BusinessException;
import com.competition.common.result.PageResult;
import com.competition.modules.ugc.entity.UgcWork;
import com.competition.modules.ugc.entity.UgcWorkPage;
import com.competition.modules.ugc.mapper.UgcWorkMapper;
import com.competition.modules.ugc.mapper.UgcWorkPageMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

@Slf4j
@Service
@RequiredArgsConstructor
public class PublicCreationService {

    private final UgcWorkMapper ugcWorkMapper;
    private final UgcWorkPageMapper ugcWorkPageMapper;

    /**
     * 提交 AI 创作（保留但降级为辅助接口）
     */
    public UgcWork submit(Long userId, String originalImageUrl, String voiceInputUrl, String textInput) {
        UgcWork work = new UgcWork();
        work.setUserId(userId);
        work.setTitle("未命名作品");
        work.setStatus(0); // DRAFT
        work.setOriginalImageUrl(originalImageUrl);
        work.setVoiceInputUrl(voiceInputUrl);
        work.setTextInput(textInput);
        work.setVisibility("private");
        work.setViewCount(0);
        work.setLikeCount(0);
        work.setFavoriteCount(0);
        work.setCommentCount(0);
        work.setShareCount(0);
        work.setIsRecommended(false);
        work.setIsDeleted(0);
        work.setCreateTime(LocalDateTime.now());
        work.setModifyTime(LocalDateTime.now());
        ugcWorkMapper.insert(work);
        return work;
    }

    /**
     * 获取创作状态
     * 返回 INT 类型的 status + progress + progressMessage
     */
    public Map<String, Object> getStatus(Long id, Long userId) {
        UgcWork work = ugcWorkMapper.selectById(id);
        if (work == null || !work.getUserId().equals(userId)) {
            throw new BusinessException(404, "创作记录不存在");
        }
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("id", work.getId());
        result.put("status", work.getStatus());
        result.put("progress", work.getProgress());
        result.put("progressMessage", work.getProgressMessage());
        result.put("remoteWorkId", work.getRemoteWorkId());
        result.put("title", work.getTitle());
        result.put("coverUrl", work.getCoverUrl());
        return result;
    }

    /**
     * 获取创作结果（包含 pageList 的完整数据）
     */
    public Map<String, Object> getResult(Long id, Long userId) {
        UgcWork work = ugcWorkMapper.selectById(id);
        if (work == null || !work.getUserId().equals(userId)) {
            throw new BusinessException(404, "创作记录不存在");
        }

        Map<String, Object> result = new LinkedHashMap<>();
        result.put("id", work.getId());
        result.put("title", work.getTitle());
        result.put("coverUrl", work.getCoverUrl());
        result.put("description", work.getDescription());
        result.put("status", work.getStatus());
        result.put("progress", work.getProgress());
        result.put("progressMessage", work.getProgressMessage());
        result.put("originalImageUrl", work.getOriginalImageUrl());
        result.put("voiceInputUrl", work.getVoiceInputUrl());
        result.put("textInput", work.getTextInput());
        result.put("aiMeta", work.getAiMeta());
        result.put("style", work.getStyle());
        result.put("authorName", work.getAuthorName());
        result.put("failReason", work.getFailReason());
        result.put("remoteWorkId", work.getRemoteWorkId());
        result.put("createTime", work.getCreateTime());

        // 查询页面列表
        LambdaQueryWrapper<UgcWorkPage> pageWrapper = new LambdaQueryWrapper<>();
        pageWrapper.eq(UgcWorkPage::getWorkId, id)
                   .orderByAsc(UgcWorkPage::getPageNo);
        List<UgcWorkPage> pages = ugcWorkPageMapper.selectList(pageWrapper);
        result.put("pages", pages);

        return result;
    }

    /**
     * 获取创作历史
     */
    public PageResult<UgcWork> getHistory(Long userId, int page, int pageSize) {
        LambdaQueryWrapper<UgcWork> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UgcWork::getUserId, userId)
                .eq(UgcWork::getIsDeleted, 0)
                .isNotNull(UgcWork::getOriginalImageUrl)
                .orderByDesc(UgcWork::getCreateTime);

        IPage<UgcWork> result = ugcWorkMapper.selectPage(new Page<>(page, pageSize), wrapper);
        return PageResult.from(result);
    }
}
