package com.competition.modules.pub.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
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.entity.UgcWorkTag;
import com.competition.modules.ugc.mapper.UgcWorkMapper;
import com.competition.modules.ugc.mapper.UgcWorkPageMapper;
import com.competition.modules.ugc.mapper.UgcWorkTagMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

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

@Slf4j
@Service
@RequiredArgsConstructor
public class PublicUserWorkService {

    private final UgcWorkMapper ugcWorkMapper;
    private final UgcWorkPageMapper ugcWorkPageMapper;
    private final UgcWorkTagMapper ugcWorkTagMapper;

    /**
     * 创建作品
     */
    @Transactional
    public UgcWork create(Long userId, String title, String coverUrl, String description,
                          String visibility, List<Map<String, Object>> pages, List<Long> tagIds) {
        UgcWork work = new UgcWork();
        work.setUserId(userId);
        work.setTitle(title);
        work.setCoverUrl(coverUrl);
        work.setDescription(description);
        work.setVisibility(visibility != null ? visibility : "private");
        work.setStatus(0); // 0=DRAFT
        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);

        // 保存页面
        if (pages != null && !pages.isEmpty()) {
            saveWorkPages(work.getId(), pages);
        }

        // 保存标签关联
        if (tagIds != null && !tagIds.isEmpty()) {
            for (Long tagId : tagIds) {
                UgcWorkTag wt = new UgcWorkTag();
                wt.setWorkId(work.getId());
                wt.setTagId(tagId);
                ugcWorkTagMapper.insert(wt);
            }
        }

        return work;
    }

    /**
     * 查询我的作品（分页）
     */
    public PageResult<UgcWork> findMyWorks(Long userId, int page, int pageSize, String status, String keyword) {
        LambdaQueryWrapper<UgcWork> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UgcWork::getUserId, userId)
                .eq(UgcWork::getIsDeleted, 0);
        if (StringUtils.hasText(status)) {
            wrapper.eq(UgcWork::getStatus, status);
        }
        if (StringUtils.hasText(keyword)) {
            wrapper.like(UgcWork::getTitle, keyword);
        }
        wrapper.orderByDesc(UgcWork::getCreateTime);

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

    /**
     * 获取作品详情
     */
    public Map<String, Object> findDetail(Long id, Long userId) {
        UgcWork work = ugcWorkMapper.selectById(id);
        if (work == null || work.getIsDeleted() == 1) {
            throw new BusinessException(404, "作品不存在");
        }
        if (!work.getUserId().equals(userId)) {
            throw new BusinessException(403, "无权访问该作品");
        }

        List<UgcWorkPage> pages = ugcWorkPageMapper.selectList(
                new LambdaQueryWrapper<UgcWorkPage>()
                        .eq(UgcWorkPage::getWorkId, id)
                        .orderByAsc(UgcWorkPage::getPageNo));

        Map<String, Object> result = new LinkedHashMap<>();
        result.put("work", work);
        result.put("pages", pages);
        return result;
    }

    /**
     * 更新作品
     */
    public void update(Long id, Long userId, Map<String, Object> dto) {
        UgcWork work = ugcWorkMapper.selectById(id);
        if (work == null || work.getIsDeleted() == 1 || !work.getUserId().equals(userId)) {
            throw new BusinessException(404, "作品不存在或无权操作");
        }

        LambdaUpdateWrapper<UgcWork> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(UgcWork::getId, id);
        if (dto.containsKey("title")) wrapper.set(UgcWork::getTitle, dto.get("title"));
        if (dto.containsKey("coverUrl")) wrapper.set(UgcWork::getCoverUrl, dto.get("coverUrl"));
        if (dto.containsKey("description")) wrapper.set(UgcWork::getDescription, dto.get("description"));
        if (dto.containsKey("visibility")) wrapper.set(UgcWork::getVisibility, dto.get("visibility"));
        wrapper.set(UgcWork::getModifyTime, LocalDateTime.now());
        ugcWorkMapper.update(null, wrapper);
    }

    /**
     * 删除作品（软删除）
     */
    public void delete(Long id, Long userId) {
        UgcWork work = ugcWorkMapper.selectById(id);
        if (work == null || work.getIsDeleted() == 1 || !work.getUserId().equals(userId)) {
            throw new BusinessException(404, "作品不存在或无权操作");
        }
        work.setIsDeleted(1);
        work.setModifyTime(LocalDateTime.now());
        ugcWorkMapper.updateById(work);
    }

    /**
     * 发布作品（提交审核）
     */
    public void publish(Long id, Long userId) {
        UgcWork work = ugcWorkMapper.selectById(id);
        if (work == null || work.getIsDeleted() == 1 || !work.getUserId().equals(userId)) {
            throw new BusinessException(404, "作品不存在或无权操作");
        }
        if (work.getStatus() != 0 && work.getStatus() != -1) {
            throw new BusinessException(400, "当前状态不可发布");
        }
        work.setStatus(1); // 1=PENDING
        work.setModifyTime(LocalDateTime.now());
        ugcWorkMapper.updateById(work);
    }

    /**
     * 获取作品页面
     */
    public List<UgcWorkPage> getPages(Long workId) {
        return ugcWorkPageMapper.selectList(
                new LambdaQueryWrapper<UgcWorkPage>()
                        .eq(UgcWorkPage::getWorkId, workId)
                        .orderByAsc(UgcWorkPage::getPageNo));
    }

    /**
     * 保存作品页面（覆盖式）
     */
    @Transactional
    public void savePages(Long workId, Long userId, List<Map<String, Object>> pages) {
        UgcWork work = ugcWorkMapper.selectById(workId);
        if (work == null || work.getIsDeleted() == 1 || !work.getUserId().equals(userId)) {
            throw new BusinessException(404, "作品不存在或无权操作");
        }

        // 删除旧页面
        ugcWorkPageMapper.delete(
                new LambdaQueryWrapper<UgcWorkPage>().eq(UgcWorkPage::getWorkId, workId));

        // 插入新页面
        saveWorkPages(workId, pages);
    }

    private void saveWorkPages(Long workId, List<Map<String, Object>> pages) {
        for (int i = 0; i < pages.size(); i++) {
            Map<String, Object> p = pages.get(i);
            UgcWorkPage page = new UgcWorkPage();
            page.setWorkId(workId);
            page.setPageNo(i + 1);
            page.setImageUrl((String) p.get("imageUrl"));
            page.setText((String) p.get("text"));
            page.setAudioUrl((String) p.get("audioUrl"));
            ugcWorkPageMapper.insert(page);
        }
    }
}
