package shop.alien.lawyer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import shop.alien.entity.result.R;
import shop.alien.entity.store.LawyerUserSearchHistory;
import shop.alien.lawyer.service.LawyerUserSearchHistoryService;
import shop.alien.mapper.LawyerUserSearchHistoryMapper;

import shop.alien.util.myBaticsPlus.QueryBuilder;

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

/**
 * 用户搜索历史 服务实现类
 *
 * @author system
 * @since 2025-01-XX
 */
@Slf4j
@Transactional
@Service
@RequiredArgsConstructor
public class LawyerUserSearchHistoryServiceImpl extends ServiceImpl<LawyerUserSearchHistoryMapper, LawyerUserSearchHistory> implements LawyerUserSearchHistoryService {

    private final LawyerUserSearchHistoryMapper userSearchHistoryMapper;

    @Override
    public R<IPage<LawyerUserSearchHistory>> getUserSearchHistoryList(int pageNum, int pageSize, Integer clientUserId, Integer searchType) {
        log.info("LawyerUserSearchHistoryServiceImpl.getUserSearchHistoryList?pageNum={},pageSize={},clientUserId={},searchType={}",
                pageNum, pageSize, clientUserId, searchType);
        Page<LawyerUserSearchHistory> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<LawyerUserSearchHistory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LawyerUserSearchHistory::getDeleteFlag, 0);
        if (clientUserId != null) {
            queryWrapper.eq(LawyerUserSearchHistory::getClientUserId, clientUserId);
        }
        if (searchType != null) {
            queryWrapper.eq(LawyerUserSearchHistory::getSearchType, searchType);
        }
        queryWrapper.orderByDesc(LawyerUserSearchHistory::getSearchTime);
        IPage<LawyerUserSearchHistory> pageResult = this.page(page, queryWrapper);
        return R.data(pageResult);
    }

    @Override
    public List<LawyerUserSearchHistory> getListByUserId(Integer clientUserId) {
        log.info("LawyerUserSearchHistoryServiceImpl.getListByUserId?clientUserId={}", clientUserId);
        LambdaQueryWrapper<LawyerUserSearchHistory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LawyerUserSearchHistory::getClientUserId, clientUserId)
                .eq(LawyerUserSearchHistory::getDeleteFlag, 0)
                .orderByDesc(LawyerUserSearchHistory::getSearchTime)
                .last("LIMIT 20");
        return this.list(queryWrapper);
    }

    @Override
    public R<LawyerUserSearchHistory> addUserSearchHistory(LawyerUserSearchHistory userSearchHistory) {
        log.info("LawyerUserSearchHistoryServiceImpl.addUserSearchHistory?userSearchHistory={}", userSearchHistory);

        // 设置搜索时间
        if (userSearchHistory.getSearchTime() == null) {
            userSearchHistory.setSearchTime(new java.util.Date());
        }

        // 检查该用户的历史记录数量，如果超过10条则删除最老的记录
        if (userSearchHistory.getClientUserId() != null) {
            LambdaQueryWrapper<LawyerUserSearchHistory> countWrapper = new LambdaQueryWrapper<>();
            countWrapper.eq(LawyerUserSearchHistory::getClientUserId, userSearchHistory.getClientUserId())
                    .eq(LawyerUserSearchHistory::getDeleteFlag, 0);
            long count = this.count(countWrapper);

            // 如果已有10条或更多记录，删除最老的记录
            if (count >= 10) {
                // 查询需要删除的最老记录（保留9条，加上新的一条共10条）
                LambdaQueryWrapper<LawyerUserSearchHistory> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(LawyerUserSearchHistory::getClientUserId, userSearchHistory.getClientUserId())
                        .eq(LawyerUserSearchHistory::getDeleteFlag, 0)
                        .orderByAsc(LawyerUserSearchHistory::getSearchTime)  // 按搜索时间升序，最老的在前
                        .orderByAsc(LawyerUserSearchHistory::getCreatedTime)  // 如果搜索时间相同，按创建时间升序
                        .last("LIMIT " + (count - 9));  // 查询需要删除的记录数
                List<LawyerUserSearchHistory> toDeleteList = this.list(queryWrapper);

                // 批量删除最老的记录
                if (!toDeleteList.isEmpty()) {
                    List<Integer> idsToDelete = toDeleteList.stream()
                            .map(LawyerUserSearchHistory::getId)
                            .collect(Collectors.toList());
                    this.removeByIds(idsToDelete);
                    log.info("删除用户{}的最老搜索历史记录{}条，当前记录数：{}",
                            userSearchHistory.getClientUserId(), idsToDelete.size(), count);
                }
            }
        }

        // 保存新记录
        boolean result = this.save(userSearchHistory);
        if (result) {
            return R.data(userSearchHistory);
        }
        return R.fail("新增失败");
    }

    @Override
    public R<Boolean> deleteUserSearchHistory(Integer id) {
        log.info("LawyerUserSearchHistoryServiceImpl.deleteUserSearchHistory?id={}", id);
        boolean result = this.removeById(id);
        if (result) {
            return R.success("删除成功");
        }
        return R.fail("删除失败");
    }

    @Override
    public R<Boolean> clearUserSearchHistory(Integer clientUserId) {
        log.info("LawyerUserSearchHistoryServiceImpl.clearUserSearchHistory?clientUserId={}", clientUserId);
        LambdaQueryWrapper<LawyerUserSearchHistory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LawyerUserSearchHistory::getClientUserId, clientUserId)
                .eq(LawyerUserSearchHistory::getDeleteFlag, 0);
        boolean result = this.remove(queryWrapper);
        if (result) {
            return R.success("清空成功");
        }
        return R.fail("清空失败");
    }

    @Override
    public List<LawyerUserSearchHistory> getListWithOrder(LawyerUserSearchHistory userSearchHistory) {
        log.info("LawyerUserSearchHistoryServiceImpl.getListWithOrder?userSearchHistory={}", userSearchHistory);
        QueryWrapper<LawyerUserSearchHistory> queryWrapper = QueryBuilder.of(userSearchHistory)
                .build()
                .getWrapper();
        // 添加排序：按创建时间降序（新的在前，老的在后）
        queryWrapper.orderByDesc("created_time");
        return this.list(queryWrapper);
    }

    @Override
    public IPage<LawyerUserSearchHistory> getPageWithOrder(LawyerUserSearchHistory userSearchHistory, int pageNum, int pageSize) {
        log.info("LawyerUserSearchHistoryServiceImpl.getPageWithOrder?userSearchHistory={},pageNum={},pageSize={}",
                userSearchHistory, pageNum, pageSize);
        Page<LawyerUserSearchHistory> page = new Page<>(pageNum, pageSize);
        QueryWrapper<LawyerUserSearchHistory> queryWrapper = QueryBuilder.of(userSearchHistory)
                .build()
                .getWrapper();
        // 添加排序：按创建时间降序（新的在前，老的在后）
        queryWrapper.orderByDesc("created_time");
        return this.page(page, queryWrapper);
    }
}

