package com.lesingle.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.lesingle.common.enums.Visibility;
import com.lesingle.common.exception.BusinessException;
import com.lesingle.common.result.PageResult;
import com.lesingle.modules.ugc.entity.UgcWork;
import com.lesingle.modules.ugc.entity.UgcWorkPage;
import com.lesingle.modules.ugc.entity.UgcWorkTag;
import com.lesingle.modules.ugc.enums.WorkPublishStatus;
import com.lesingle.modules.ugc.mapper.UgcWorkMapper;
import com.lesingle.modules.ugc.mapper.UgcWorkPageCountRow;
import com.lesingle.modules.ugc.mapper.UgcWorkPageMapper;
import com.lesingle.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.*;
import java.util.stream.Collectors;

@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 : Visibility.PRIVATE.getValue());
        work.setStatus(WorkPublishStatus.DRAFT.getValue());
        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);
        fillPageCounts(result.getRecords());
        return PageResult.from(result);
    }

    /**
     * 为作品列表填充 _count.pages（供其它模块复用，如创作历史）
     */
    public void attachPageCounts(List<UgcWork> works) {
        fillPageCounts(works);
    }

    /** 为列表中的每条作品填充 _count.pages（来自 t_ugc_work_page 行数） */
    private void fillPageCounts(List<UgcWork> works) {
        if (works == null || works.isEmpty()) {
            return;
        }
        List<Long> ids = works.stream().map(UgcWork::getId).collect(Collectors.toList());
        List<UgcWorkPageCountRow> rows = ugcWorkPageMapper.countPagesGroupedByWorkIds(ids);
        Map<Long, Integer> idToPages = rows.stream()
                .collect(Collectors.toMap(
                        UgcWorkPageCountRow::getWorkId,
                        r -> r.getPageCount() != null ? r.getPageCount().intValue() : 0,
                        (a, b) -> a));
        for (UgcWork work : works) {
            UgcWork.WorkCountMeta meta = new UgcWork.WorkCountMeta();
            meta.setPages(idToPages.getOrDefault(work.getId(), 0));
            work.setCount(meta);
        }
    }

    /**
     * 获取作品详情
     */
    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, "作品不存在或无权操作");
        }
        String st = work.getStatus();
        if (WorkPublishStatus.PENDING_REVIEW.getValue().equals(st)
                || WorkPublishStatus.PUBLISHED.getValue().equals(st)) {
            throw new BusinessException(400, "审核中或已发布的作品不可删除，请先撤回审核或下架");
        }
        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, "作品不存在或无权操作");
        }
        String currentStatus = work.getStatus();
        if (!WorkPublishStatus.UNPUBLISHED.getValue().equals(currentStatus)
                && !WorkPublishStatus.REJECTED.getValue().equals(currentStatus)) {
            throw new BusinessException(400, "当前状态不可发布");
        }
        work.setStatus(WorkPublishStatus.PENDING_REVIEW.getValue());
        work.setModifyTime(LocalDateTime.now());
        ugcWorkMapper.updateById(work);
    }

    /**
     * 用户撤回审核：pending_review → unpublished（与超管
     * {@code POST /content-review/works/{id}/revoke} 不同：后者为 published/rejected → pending_review）
     */
    @Transactional
    public void withdrawReview(Long id, Long userId) {
        UgcWork work = ugcWorkMapper.selectById(id);
        if (work == null || work.getIsDeleted() == 1 || !work.getUserId().equals(userId)) {
            throw new BusinessException(404, "作品不存在或无权操作");
        }
        if (!WorkPublishStatus.PENDING_REVIEW.getValue().equals(work.getStatus())) {
            throw new BusinessException(400, "当前状态不可撤回审核");
        }
        LambdaUpdateWrapper<UgcWork> uw = new LambdaUpdateWrapper<>();
        uw.eq(UgcWork::getId, id)
                .set(UgcWork::getStatus, WorkPublishStatus.UNPUBLISHED.getValue())
                .set(UgcWork::getReviewTime, null)
                .set(UgcWork::getReviewerId, null)
                .set(UgcWork::getReviewNote, null)
                .set(UgcWork::getModifyTime, LocalDateTime.now());
        ugcWorkMapper.update(null, uw);
    }

    /**
     * 用户主动下架：published → unpublished（发现页不可见，可再次提交审核）
     */
    @Transactional
    public void unpublish(Long id, Long userId) {
        UgcWork work = ugcWorkMapper.selectById(id);
        if (work == null || work.getIsDeleted() == 1 || !work.getUserId().equals(userId)) {
            throw new BusinessException(404, "作品不存在或无权操作");
        }
        if (!WorkPublishStatus.PUBLISHED.getValue().equals(work.getStatus())) {
            throw new BusinessException(400, "当前状态不可下架");
        }
        LambdaUpdateWrapper<UgcWork> uw = new LambdaUpdateWrapper<>();
        uw.eq(UgcWork::getId, id)
                .set(UgcWork::getStatus, WorkPublishStatus.UNPUBLISHED.getValue())
                .set(UgcWork::getPublishTime, null)
                .set(UgcWork::getModifyTime, LocalDateTime.now());
        ugcWorkMapper.update(null, uw);
    }

    /**
     * 获取作品页面
     */
    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);

        // 与乐读派同步逻辑一致：首图作为作品库列表封面
        if (pages != null && !pages.isEmpty()) {
            Object img = pages.get(0).get("imageUrl");
            String firstCover = img != null ? img.toString().trim() : null;
            if (firstCover != null && !firstCover.isEmpty()) {
                LambdaUpdateWrapper<UgcWork> uw = new LambdaUpdateWrapper<>();
                uw.eq(UgcWork::getId, workId)
                        .set(UgcWork::getCoverUrl, firstCover)
                        .set(UgcWork::getModifyTime, LocalDateTime.now());
                ugcWorkMapper.update(null, uw);
            }
        }
    }

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