package com.jeesharp.business.modules.ai.application;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.jeesharp.business.modules.ai.convert.AiFaqConvert;
import com.jeesharp.business.modules.ai.dto.AiFaqSaveDTO;
import com.jeesharp.business.modules.ai.entity.AiFaq;
import com.jeesharp.business.modules.ai.entity.AiFaqCategory;
import com.jeesharp.business.modules.ai.service.AiFaqCategoryService;
import com.jeesharp.business.modules.ai.service.AiFaqService;
import com.jeesharp.business.modules.ai.vo.AiFaqInfoVO;
import com.jeesharp.business.modules.ai.vo.AiFaqListVO;
import com.jeesharp.business.modules.ai.vo.AiFaqQueryVO;
import com.jeesharp.framework.pojo.Page;
import com.jeesharp.framework.pojo.query.PageRespVO;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
@Transactional(readOnly = true)
public class AiFaqApplicationService {

    private final AiFaqService aiFaqService;
    private final AiFaqCategoryService aiFaqCategoryService;

    public AiFaqInfoVO get(String id) {
        return AiFaqConvert.INSTANCE.toInfoVO(aiFaqService.get(id));
    }

    public PageRespVO<AiFaqListVO> findPage(Page<AiFaq> page, AiFaqQueryVO query) {
        AiFaqQueryVO prepared = prepareQuery(query);
        if (prepared == null) {
            return emptyPage(page);
        }
        Page<AiFaq> result = aiFaqService.findPage(page, prepared);
        PageRespVO<AiFaqListVO> pageVo = AiFaqConvert.INSTANCE.toPageRespVO(result);
        enrichCategoryDisplay(pageVo.getRecords());
        return pageVo;
    }

    @Transactional(readOnly = false)
    public void save(AiFaqSaveDTO dto) {
        AiFaq entity = AiFaqConvert.INSTANCE.toEntity(dto);
        if (StrUtil.isBlank(dto.getId())) {
            aiFaqService.createFaq(entity);
            return;
        }
        aiFaqService.updateFaq(entity);
    }

    @Transactional(readOnly = false)
    public void delete(String ids) {
        aiFaqService.batchDelete(StrUtil.splitTrim(ids, ','));
    }

    public List<AiFaqListVO> listForMobile(String categoryId, String keyword) {
        AiFaqQueryVO query = new AiFaqQueryVO();
        query.setStatus(1);
        List<AiFaqListVO> list = AiFaqConvert.INSTANCE.toListVO(aiFaqService.findList(query));
        enrichCategoryDisplay(list);
        list.forEach(item -> item.setHot(item.getSortNo() != null && item.getSortNo() <= 10));
        if (StrUtil.isNotBlank(categoryId)) {
            list = list.stream()
                    .filter(item -> StrUtil.equals(categoryId, item.getCategoryId())
                            || StrUtil.equals(categoryId, item.getCategory()))
                    .toList();
        }
        if (StrUtil.isBlank(keyword)) {
            return list;
        }
        return list.stream()
                .filter(item -> StrUtil.containsIgnoreCase(item.getQuestion(), keyword)
                        || StrUtil.containsIgnoreCase(StrUtil.nullToEmpty(item.getKeywords()), keyword))
                .toList();
    }

    /**
     * 管理端分类名称筛选：categoryKeyword → categoryIdIn。
     */
    private AiFaqQueryVO prepareQuery(AiFaqQueryVO query) {
        AiFaqQueryVO q = query != null ? query : new AiFaqQueryVO();
        if (StrUtil.isNotBlank(q.getCategoryKeyword())) {
            List<String> categoryIds = aiFaqCategoryService.findIdsByCategoryName(q.getCategoryKeyword().trim());
            q.setCategoryKeyword(null);
            if (CollUtil.isEmpty(categoryIds)) {
                return null;
            }
            q.setCategoryId(null);
            q.setCategoryIdIn(categoryIds);
        }
        return q;
    }

    private static PageRespVO<AiFaqListVO> emptyPage(Page<AiFaq> page) {
        PageRespVO<AiFaqListVO> empty = new PageRespVO<>();
        empty.setRecords(Collections.emptyList());
        empty.setTotal(0L);
        empty.setPageNo(page != null ? page.getPageNo() : 1L);
        empty.setPageSize(page != null ? page.getPageSize() : 10L);
        return empty;
    }

    private void enrichCategoryDisplay(List<AiFaqListVO> rows) {
        if (rows == null || rows.isEmpty()) {
            return;
        }
        List<String> categoryIds = rows.stream()
                .map(AiFaqListVO::getCategoryId)
                .filter(StrUtil::isNotBlank)
                .map(String::trim)
                .distinct()
                .toList();
        if (categoryIds.isEmpty()) {
            return;
        }
        Map<String, String> categoryNameMap = aiFaqCategoryService.listByIds(categoryIds).stream()
                .filter(category -> category != null && StrUtil.isNotBlank(category.getId()))
                .collect(Collectors.toMap(AiFaqCategory::getId, AiFaqCategory::getCategoryName, (a, b) -> a));
        rows.forEach(item -> {
            String categoryId = StrUtil.trim(item.getCategoryId());
            String categoryName = categoryNameMap.get(categoryId);
            item.setCategory(StrUtil.isNotBlank(categoryName) ? categoryName : categoryId);
        });
    }
}
