package com.backendsys.modules.cms.article.service.impl;

import cn.hutool.core.util.IdUtil;
import com.backendsys.exception.CustException;
import com.backendsys.modules.cms.article.dao.ArticleDao;
import com.backendsys.modules.cms.article.dao.ArticleI18nDao;
import com.backendsys.modules.cms.article.entity.Article;
import com.backendsys.modules.cms.article.entity.ArticleI18n;
import com.backendsys.modules.cms.article.service.ArticleService;
import com.backendsys.modules.common.config.security.utils.HttpRequestUtil;
import com.backendsys.modules.common.utils.ValidationUtil;
import com.backendsys.utils.MapUtil;
import com.backendsys.utils.response.PageEntity;
import com.backendsys.utils.response.PageInfoResult;
import com.backendsys.utils.v2.PageUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private HttpRequestUtil httpRequestUtil;

    @Autowired
    private ArticleDao articleDao;
    @Autowired
    private ArticleI18nDao articleI18nDao;

    /**
     * 获取资讯列表
     */
    @Override
    public PageEntity selectArticleList(Article article) {
        PageUtils.startPage();  // 分页

//        List<Article> list = articleDao.selectList(new LambdaQueryWrapper<>());
        List<Map<String, Object>> list = articleDao.selectArticleList(article);

        // 1) 完成分页实体渲染
        PageEntity pageEntity = new PageInfoResult(list).toEntity();
//
//        // 2) 分页列表格式化
//        list = list.stream().map(item -> {
//            item.put("create_time_shanghai", MapUtil.convertUtcToAsiaShanghai(item.get("create_time_utc")));
//            return item;
//        }).collect(Collectors.toList());
//
//        // 3) 分页实体重新赋值
//        List<Object> objectList = list.stream().map(item -> (Object) item).collect(Collectors.toList());
//        pageEntity.setList(objectList);

        return pageEntity;
    }

    /**
     * 获取资讯详情
     */
    @Override
    public Map<String, Object> selectArticleDetail(Article article) {
        Map<String, Object> detail = articleDao.selectArticleDetail(article);
        if (detail == null) throw new CustException("资讯不存在");
        return detail;
    }

    /**
     * 获取资讯详情 (公开)
     */
    @Override
    public Map<String, Object> selectArticleDetailPublic(Article article) {
        Map<String, Object> detail = articleDao.selectArticleDetailFull(article);
        if (detail == null) throw new CustException("资讯不存在");
        return detail;
    }

    /**
     * 获取资讯详情 (视图)
     */
    @Override
    public Article selectArticle(String lang, String uid) {

        // [Get] 详情
        Article detail = articleDao.selectOne(new LambdaQueryWrapper<Article>().eq(Article::getUid, uid).eq(Article::getStatus, 1));
        if (detail == null) return null;

        // [Get] 翻译
        LambdaQueryWrapper<ArticleI18n> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ArticleI18n::getLanguage, lang);
        wrapper.eq(ArticleI18n::getArticle_id, detail.getId());
        ArticleI18n i18nDetail = articleI18nDao.selectOne(wrapper);
        if (i18nDetail == null) return null;

        // [拼接] 详情 + 翻译
        detail.setTitle(i18nDetail.getTitle());
        detail.setDescription(i18nDetail.getDescription());
        detail.setContent(i18nDetail.getContent());
        detail.setMeta_keyword(i18nDetail.getMeta_keyword());
        detail.setMeta_description(i18nDetail.getMeta_description());

        return detail;
    }


    /**
     * 创建资讯
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> insertArticle(Article article) {

        // 生成随机UUID
        article.setUid(IdUtil.simpleUUID().substring(0, 10));

        // 插入
        article.setUser_id(httpRequestUtil.getUserId());
        articleDao.insert(article);

        // 批量插入 (翻译字段)
        Long article_id = article.getId();
        List<ArticleI18n> translations = article.getTranslations().stream()
            .peek(item -> { ValidationUtil.validateObject(item, ArticleI18n.Create.class); })
            .map(item -> { item.setArticle_id(article_id); return item; })
            .collect(Collectors.toList());
        articleI18nDao.insertBatch(translations);

        return Map.of("article_id", article_id);
    }

    /**
     * 编辑资讯
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> updateArticle(Article article) {

        Long article_id = article.getArticle_id();

        Article articleDetail = articleDao.selectById(article_id);
        if (articleDetail == null) throw new CustException("资讯不存在");

        // 更新
        article.setId(article_id);
        articleDao.updateById(article);

        // 批量更新 (翻译字段)
        List<ArticleI18n> translations = article.getTranslations().stream()
            .peek(item -> { ValidationUtil.validateObject(item, ArticleI18n.Update.class); })
            .map(t -> { t.setArticle_id(article_id); return t; })
            .collect(Collectors.toList());
        articleI18nDao.updateBatch(translations);

        return Map.of("article_id", article_id);
    }


    /**
     * 删除资讯
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> deleteArticle(Article article) {

        Long article_id = article.getArticle_id();

        Article detail = articleDao.selectById(article_id);
        if (detail == null) throw new CustException("资讯不存在");

        articleDao.deleteById(article_id);
        articleI18nDao.delete(new QueryWrapper<ArticleI18n>().eq("article_id", article_id));

        return Map.of("article_id", article_id);
    }

    /**
     * 删除资讯 (批量)
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> deleteArticleBatch(Article article) {

        List<Long> article_ids = article.getArticle_ids();

        articleDao.deleteBatchIds(article_ids);
        articleI18nDao.delete(new QueryWrapper<ArticleI18n>().in("article_id", article_ids));

        return Map.of("article_ids", article_ids);
    }


}
