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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.jeesharp.business.modules.mall.convert.MallSearchLogConvert;
import com.jeesharp.business.modules.mall.dto.MallSearchLogSaveDTO;
import com.jeesharp.business.modules.mall.entity.MallSearchLog;
import com.jeesharp.business.modules.mall.service.MallSearchLogService;
import com.jeesharp.business.modules.mall.vo.MallSearchLogInfoVO;
import com.jeesharp.business.modules.mall.vo.MallSearchLogListVO;
import com.jeesharp.business.modules.mall.vo.MallSearchLogQueryVO;
import com.jeesharp.business.modules.member.service.MemberService;
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;

/**
 * 搜索历史 Application Service
 */
@Service
@AllArgsConstructor
@Transactional(readOnly = true)
public class MallSearchLogApplicationService {

    private final MallSearchLogService mallSearchLogService;
    private final MemberService memberService;

    public MallSearchLogInfoVO get(String id) {
        return MallSearchLogConvert.INSTANCE.toInfoVO(mallSearchLogService.get(id));
    }

    public PageRespVO<MallSearchLogListVO> findPage(Page<MallSearchLog> page, MallSearchLogQueryVO query) {
        MallSearchLogQueryVO prepared = prepareQuery(query);
        if (prepared == null) {
            return emptyPage(page);
        }
        Page<MallSearchLog> result = mallSearchLogService.findPage(page, prepared);
        return MallSearchLogConvert.INSTANCE.toPageRespVO(result);
    }

    @Transactional(readOnly = false)
    public void save(MallSearchLogSaveDTO dto) {
        MallSearchLog entity = MallSearchLogConvert.INSTANCE.toEntity(dto);
        if (StrUtil.isBlank(dto.getId())) {
            mallSearchLogService.createSearchLog(entity);
            return;
        }
        mallSearchLogService.updateSearchLog(entity);
    }

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

    /**
     * 记录用户搜索历史
     */
    @Transactional(readOnly = false)
    public void recordSearchHistory(String memberId, String keyword) {
        mallSearchLogService.recordSearchHistory(memberId, keyword);
    }

    /**
     * 获取用户搜索历史（最近20条）
     */
    public List<String> getUserSearchHistory(String memberId) {
        return mallSearchLogService.getUserSearchHistory(memberId);
    }

    /**
     * 获取热门搜索词（最近7天，按搜索次数倒序）
     */
    public List<Map<String, Object>> getHotSearchWords() {
        return mallSearchLogService.getHotSearchWords();
    }

    /**
     * 删除用户的搜索历史
     */
    @Transactional(readOnly = false)
    public void clearUserSearchHistory(String memberId) {
        mallSearchLogService.clearUserSearchHistory(memberId);
    }

    /**
     * 会员手机号 → memberIdIn 筛选条件。
     */
    private MallSearchLogQueryVO prepareQuery(MallSearchLogQueryVO query) {
        MallSearchLogQueryVO q = query != null ? query : new MallSearchLogQueryVO();
        if (StrUtil.isBlank(q.getMemberMobile())) {
            return q;
        }
        List<String> memberIds = memberService.findIdsByKeyword(q.getMemberMobile().trim());
        q.setMemberMobile(null);
        if (CollUtil.isEmpty(memberIds)) {
            return null;
        }
        q.setMemberIdIn(memberIds);
        return q;
    }

    private PageRespVO<MallSearchLogListVO> emptyPage(Page<MallSearchLog> page) {
        PageRespVO<MallSearchLogListVO> empty = new PageRespVO<>();
        empty.setRecords(Collections.emptyList());
        empty.setTotal(0L);
        empty.setPageNo(page.getPageNo());
        empty.setPageSize(page.getPageSize());
        empty.setPages(0L);
        return empty;
    }
}
