package shop.alien.store.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import shop.alien.entity.store.AiIntelligentAssistant;
import shop.alien.entity.store.StoreCustomerService;
import shop.alien.mapper.AiIntelligentAssistantMapper;
import shop.alien.mapper.StoreCustomerServiceMapper;
import shop.alien.store.service.StoreCustomerServiceService;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 门店客服 服务实现类
 * </p>
 *
 * @author ssk
 * @since 2024-12-30
 */
@Service
@RequiredArgsConstructor
public class StoreCustomerServiceServiceImpl extends ServiceImpl<StoreCustomerServiceMapper, StoreCustomerService> implements StoreCustomerServiceService {

    private final StoreCustomerServiceMapper storeCustomerServiceMapper;

    private final AiIntelligentAssistantMapper aiIntelligentAssistantMapper;

    @Override
    public StoreCustomerService getByQuestion(String question) {
        if (StringUtils.isEmpty(question)) {
            return null;
        }
        LambdaQueryWrapper<StoreCustomerService> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(StoreCustomerService::getQuestion, question)
                .eq(StoreCustomerService::getDeleteFlag, 0)
                .orderByDesc(StoreCustomerService::getCreatedTime)
                .last("limit 1");
        return storeCustomerServiceMapper.selectOne(lambdaQueryWrapper);
    }

    @Override
    public StoreCustomerService saveStoreCustomerService(StoreCustomerService storeCustomerService) {
        storeCustomerService.setUpdatedTime(new Date());
        if (ObjectUtils.isNotEmpty(storeCustomerService.getId())) {
            storeCustomerServiceMapper.updateById(storeCustomerService);
        } else {
            storeCustomerService.setCreatedTime(new Date());
            storeCustomerServiceMapper.insert(storeCustomerService);
        }
        return storeCustomerService;
    }

    @Override
    public void delStoreCustomerService(String id) {
        storeCustomerServiceMapper.deleteById(id);
    }

    @Override
    public IPage<StoreCustomerService> getStoreCustomerServicePage(int page, int size, String question, String type) {
        LambdaQueryWrapper<StoreCustomerService> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(question), StoreCustomerService::getQuestion, question)
                .eq(StringUtils.isNotEmpty(type), StoreCustomerService::getType, type)
                .eq(StoreCustomerService::getDeleteFlag, 0)
                .orderByDesc(StoreCustomerService::getCreatedTime);
        IPage<StoreCustomerService> storeCustomerServiceIPage = new Page<>(page, size);
        IPage<StoreCustomerService> selectPage = storeCustomerServiceMapper.selectPage(storeCustomerServiceIPage, lambdaQueryWrapper);
        return selectPage;
    }

    @Override
    public StoreCustomerService getById(String id) {
        return storeCustomerServiceMapper.selectById(id);
    }

    @Override
    public List<StoreCustomerService> getRandList(String type, Integer limit) {
        if (StringUtils.isEmpty(type) || limit == null || limit <= 0) {
            return new ArrayList<>();
        }
        // 限制最大查询数量，防止SQL注入和性能问题
        if (limit > 100) {
            limit = 100;
        }
        LambdaQueryWrapper<StoreCustomerService> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(StoreCustomerService::getType, type)
                .eq(StoreCustomerService::getDeleteFlag, 0)
                .last("order by rand() LIMIT " + limit);
        return storeCustomerServiceMapper.selectList(lambdaQueryWrapper);
    }

    @Override
    public List<AiIntelligentAssistant> saveAiIntelligentAssistant(List<AiIntelligentAssistant> aiIntelligentAssistants) {
        if (aiIntelligentAssistants == null || aiIntelligentAssistants.isEmpty()) {
            return new ArrayList<>();
        }
        Date now = new Date();
        for (AiIntelligentAssistant aiIntelligentAssistant : aiIntelligentAssistants) {
            if (aiIntelligentAssistant == null) {
                continue;
            }
            aiIntelligentAssistant.setDeleteFlag(0);
            if (aiIntelligentAssistant.getType() != null && aiIntelligentAssistant.getType() != 0) {
                aiIntelligentAssistant.setCreatedTime(now);
                aiIntelligentAssistant.setUpdatedTime(now);
            }
        }
        // 过滤掉null值
        List<AiIntelligentAssistant> validList = aiIntelligentAssistants.stream()
                .filter(item -> item != null)
                .collect(Collectors.toList());
        if (validList.isEmpty()) {
            return new ArrayList<>();
        }
        aiIntelligentAssistantMapper.insertList(validList);
        return validList;
    }

    /**
     * 查询聊天记录
     * 只返回最近7天内的记录
     */
    @Override
    public List<AiIntelligentAssistant> selectAiIntelligentAssistant(String userId, String time, Integer talkSource) {
        // 参数校验
        if (StringUtils.isEmpty(userId) || StringUtils.isEmpty(time) || talkSource == null) {
            return new ArrayList<>();
        }
        
        // 解析time字符串为Date类型
        Date queryTime;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            queryTime = sdf.parse(time);
        } catch (Exception e) {
            // 如果解析失败，使用当前时间
            queryTime = new Date();
        }
        
        // 计算7天前的时间
        Date now = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        calendar.add(Calendar.DAY_OF_YEAR, -7);
        Date sevenDaysAgo = calendar.getTime();
        
        // 确保查询时间不早于7天前
        if (queryTime.before(sevenDaysAgo)) {
            queryTime = sevenDaysAgo;
        }
        
        // 查找最后一个type=0的记录作为分页标记点（限制在7天内）
        LambdaQueryWrapper<AiIntelligentAssistant> last = new LambdaQueryWrapper<AiIntelligentAssistant>()
                .lt(AiIntelligentAssistant::getCreatedTime, queryTime)
                .ge(AiIntelligentAssistant::getCreatedTime, sevenDaysAgo) // 只查询7天内的记录
                .eq(AiIntelligentAssistant::getDeleteFlag, 0)
                .eq(AiIntelligentAssistant::getType, 0)
                .eq(AiIntelligentAssistant::getTalkSource, talkSource)
                .eq(AiIntelligentAssistant::getUserId, userId)
                .orderByDesc(AiIntelligentAssistant::getCreatedTime)
                .last("limit 1");
        AiIntelligentAssistant aiIntelligentAssistant = aiIntelligentAssistantMapper.selectOne(last);
        
        if (ObjectUtils.isNotEmpty(aiIntelligentAssistant)) {
            // 找到了标记点，从标记点开始查询到time之间的记录
            Date markPointTime = aiIntelligentAssistant.getCreatedTime();
            // 确保标记点时间不早于7天前
            if (markPointTime.before(sevenDaysAgo)) {
                markPointTime = sevenDaysAgo;
            }
            
            LambdaQueryWrapper<AiIntelligentAssistant> queryWrapper = new LambdaQueryWrapper<AiIntelligentAssistant>()
                    .ge(AiIntelligentAssistant::getCreatedTime, markPointTime)
                    .lt(AiIntelligentAssistant::getCreatedTime, queryTime)
                    .eq(AiIntelligentAssistant::getDeleteFlag, 0)
                    .eq(AiIntelligentAssistant::getUserId, userId)
                    .eq(AiIntelligentAssistant::getTalkSource, talkSource)
                    .orderByAsc(AiIntelligentAssistant::getCreatedTime);
            return aiIntelligentAssistantMapper.selectList(queryWrapper);
        } else {
            // 如果找不到type=0的标记点，直接查询7天内的所有记录（支持首次加载）
            LambdaQueryWrapper<AiIntelligentAssistant> queryWrapper = new LambdaQueryWrapper<AiIntelligentAssistant>()
                    .ge(AiIntelligentAssistant::getCreatedTime, sevenDaysAgo)
                    .lt(AiIntelligentAssistant::getCreatedTime, queryTime)
                    .eq(AiIntelligentAssistant::getDeleteFlag, 0)
                    .eq(AiIntelligentAssistant::getUserId, userId)
                    .eq(AiIntelligentAssistant::getTalkSource, talkSource)
                    .orderByAsc(AiIntelligentAssistant::getCreatedTime);
            return aiIntelligentAssistantMapper.selectList(queryWrapper);
        }
    }
}
