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.common.util.SecurityUtil;
import com.lesingle.modules.sys.entity.SysUser;
import com.lesingle.modules.sys.mapper.SysUserMapper;
import com.lesingle.modules.ugc.entity.UgcWork;
import com.lesingle.modules.ugc.entity.UgcWorkPage;
import com.lesingle.modules.ugc.enums.WorkPublishStatus;
import com.lesingle.modules.ugc.mapper.UgcWorkMapper;
import com.lesingle.modules.ugc.mapper.UgcWorkPageMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

@Slf4j
@Service
@RequiredArgsConstructor
public class PublicGalleryService {

    private final UgcWorkMapper ugcWorkMapper;
    private final UgcWorkPageMapper ugcWorkPageMapper;
    private final SysUserMapper sysUserMapper;

    /**
     * 获取广场作品列表
     *
     * @param tagId    可选，按 {@code t_ugc_work_tag} 关联筛选；与超管维护的标签 ID 一致
     * @param category 预留（按标签大类筛选），当前未接前端传参，忽略
     */
    public PageResult<Map<String, Object>> getGalleryList(int page, int pageSize, Long tagId,
                                                           String category, String sortBy, String keyword) {
        LambdaQueryWrapper<UgcWork> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UgcWork::getStatus, WorkPublishStatus.PUBLISHED.getValue())
                .eq(UgcWork::getVisibility, Visibility.PUBLIC.getValue())
                .eq(UgcWork::getIsDeleted, 0);
        if (tagId != null) {
            wrapper.apply("EXISTS (SELECT 1 FROM t_ugc_work_tag r WHERE r.work_id = t_ugc_work.id AND r.tag_id = {0})", tagId);
        }
        if (StringUtils.hasText(keyword)) {
            wrapper.like(UgcWork::getTitle, keyword);
        }

        // 排序
        if ("hot".equals(sortBy)) {
            wrapper.orderByDesc(UgcWork::getLikeCount);
        } else if ("views".equals(sortBy)) {
            wrapper.orderByDesc(UgcWork::getViewCount);
        } else {
            wrapper.orderByDesc(UgcWork::getPublishTime);
        }

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

        // 补充用户信息
        List<Map<String, Object>> voList = new ArrayList<>();
        for (UgcWork work : result.getRecords()) {
            Map<String, Object> vo = buildGalleryItem(work);
            voList.add(vo);
        }

        return PageResult.from(result, voList);
    }

    /**
     * 获取推荐作品
     */
    public List<Map<String, Object>> getRecommended() {
        LambdaQueryWrapper<UgcWork> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UgcWork::getIsRecommended, true)
                .eq(UgcWork::getStatus, WorkPublishStatus.PUBLISHED.getValue())
                .eq(UgcWork::getVisibility, Visibility.PUBLIC.getValue())
                .eq(UgcWork::getIsDeleted, 0)
                .orderByDesc(UgcWork::getPublishTime)
                .last("LIMIT 20");

        List<UgcWork> works = ugcWorkMapper.selectList(wrapper);
        List<Map<String, Object>> result = new ArrayList<>();
        for (UgcWork work : works) {
            result.add(buildGalleryItem(work));
        }
        return result;
    }

    /**
     * 获取广场作品详情
     */
    public Map<String, Object> getGalleryDetail(Long id) {
        UgcWork work = ugcWorkMapper.selectById(id);
        if (work == null || work.getIsDeleted() == 1) {
            throw new BusinessException(404, "作品不存在");
        }

        // 增加浏览量
        ugcWorkMapper.update(null, new LambdaUpdateWrapper<UgcWork>()
                .eq(UgcWork::getId, id)
                .setSql("view_count = view_count + 1"));

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

        // 获取作者信息
        Map<String, Object> userInfo = null;
        if (work.getUserId() != null) {
            SysUser user = sysUserMapper.selectById(work.getUserId());
            if (user != null) {
                userInfo = new LinkedHashMap<>();
                userInfo.put("id", user.getId());
                userInfo.put("username", user.getUsername());
                userInfo.put("nickname", user.getNickname());
                userInfo.put("avatar", user.getAvatar());
            }
        }

        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("viewCount", (work.getViewCount() != null ? work.getViewCount() : 0) + 1);
        result.put("likeCount", work.getLikeCount());
        result.put("favoriteCount", work.getFavoriteCount());
        result.put("commentCount", work.getCommentCount());
        result.put("isRecommended", work.getIsRecommended());
        result.put("publishTime", work.getPublishTime());
        result.put("pages", pages);
        result.put("user", userInfo);
        result.put("creator", userInfo);

        // 与 POST /content-review/works/{id}/reject 写入的 review_note 对齐；仅作者本人可见，避免公开泄露
        if (WorkPublishStatus.REJECTED.getValue().equals(work.getStatus())) {
            Long viewerId = SecurityUtil.getCurrentUserIdOrNull();
            boolean isOwner = viewerId != null && work.getUserId() != null && viewerId.equals(work.getUserId());
            result.put("reviewNote", isOwner ? work.getReviewNote() : null);
        }
        return result;
    }

    /**
     * 获取用户的公开作品
     */
    public PageResult<Map<String, Object>> getUserPublicWorks(Long userId, int page, int pageSize) {
        LambdaQueryWrapper<UgcWork> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UgcWork::getUserId, userId)
                .eq(UgcWork::getStatus, WorkPublishStatus.PUBLISHED.getValue())
                .eq(UgcWork::getVisibility, Visibility.PUBLIC.getValue())
                .eq(UgcWork::getIsDeleted, 0)
                .orderByDesc(UgcWork::getPublishTime);

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

        List<Map<String, Object>> voList = new ArrayList<>();
        for (UgcWork work : result.getRecords()) {
            voList.add(buildGalleryItem(work));
        }
        return PageResult.from(result, voList);
    }

    private Map<String, Object> buildGalleryItem(UgcWork work) {
        Map<String, Object> vo = new LinkedHashMap<>();
        vo.put("id", work.getId());
        vo.put("title", work.getTitle());
        vo.put("coverUrl", work.getCoverUrl());
        vo.put("description", work.getDescription());
        vo.put("viewCount", work.getViewCount());
        vo.put("likeCount", work.getLikeCount());
        vo.put("favoriteCount", work.getFavoriteCount());
        vo.put("isRecommended", work.getIsRecommended());
        vo.put("publishTime", work.getPublishTime());

        // 补充作者信息
        if (work.getUserId() != null) {
            SysUser user = sysUserMapper.selectById(work.getUserId());
            if (user != null) {
                Map<String, Object> userInfo = new LinkedHashMap<>();
                userInfo.put("id", user.getId());
                userInfo.put("username", user.getUsername());
                userInfo.put("nickname", user.getNickname());
                userInfo.put("avatar", user.getAvatar());
                vo.put("user", userInfo);
                vo.put("creator", userInfo);
            }
        }
        return vo;
    }
}
