package com.ssyf.module.robot.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ssyf.common.web.apicode.ApiCodeUser;
import com.ssyf.common.web.error.ServiceRuntimeException;
import com.ssyf.module.auth.domain.entity.User;
import com.ssyf.module.auth.domain.query.UserPageQuery;
import com.ssyf.module.auth.service.UserService;
import com.ssyf.module.robot.domain.entity.RRobotAccount;
import com.ssyf.module.robot.domain.entity.UserRobotRelation;
import com.ssyf.module.robot.domain.query.UserRobotAssignQuery;
import com.ssyf.module.robot.domain.query.UserRobotRelationQuery;
import com.ssyf.module.robot.service.RRobotAccountService;
import com.ssyf.module.robot.service.UserRobotRelationService;
import com.ssyf.module.robot.mapper.UserRobotRelationMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
* @author ELSA
* @description 针对表【user_robot_relation】的数据库操作Service实现
* @createDate 2025-12-24 17:45:24
*/
@Service
public class UserRobotRelationServiceImpl extends ServiceImpl<UserRobotRelationMapper, UserRobotRelation>
    implements UserRobotRelationService{

    @Autowired
    private RRobotAccountService robotAccountService;

    @Autowired
    private UserService userService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void assignRobotToUser(UserRobotAssignQuery query) {
        // 参数验证
        if (query == null || StrUtil.isBlank(query.getUserUuid()) || CollectionUtil.isEmpty(query.getRobotUuids())) {
            ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode(), "参数不能为空");
        }

        User user = userService.getOneByUid(query.getUserUuid());
        if(user == null){
            ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode(), "用户不存在");
        }

        // 验证粉丝是否存在
        List<String> RobotUuids = query.getRobotUuids();
        List<RRobotAccount> RobotList = robotAccountService.list(new LambdaQueryWrapper<RRobotAccount>().in(RRobotAccount::getUuid, RobotUuids));
        if (RobotList.size() != RobotUuids.size()) {
            ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode(), "部分粉丝不存在");
        }

        // 构建用户粉丝关系数据
        List<UserRobotRelation> relations = new ArrayList<>();

        for (RRobotAccount fan : RobotList) {
            UserRobotRelation relation = new UserRobotRelation();
            relation.setUserId(user.getId());
            relation.setRobotId(fan.getId());
            relations.add(relation);
        }

        // 分批插入，避免一次性插入大量数据
        int batchSize = 1000;
        for (int i = 0; i < relations.size(); i += batchSize) {
            int endIndex = Math.min(i + batchSize, relations.size());
            List<UserRobotRelation> batch = relations.subList(i, endIndex);
            // 使用 ignore 策略插入，忽略重复数据导致的错误
            this.saveBatchIgnoreError(batch);
        }
    }

    @Override
    public void clear(UserRobotAssignQuery query) {
        // 参数验证
        if (query == null || StrUtil.isBlank(query.getUserUuid()) ) {
            ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode(), "参数不能为空");
        }

        User user = userService.getOneByUid(query.getUserUuid());
        if(user == null){
            ServiceRuntimeException.throw0(ApiCodeUser.PARAMETER_ERROR.getCode(), "用户不存在");
        }
        this.remove(new LambdaQueryWrapper<UserRobotRelation>().eq(UserRobotRelation::getUserId, user.getId()));
    }

    @Override
    public List<UserRobotRelation> getList(UserRobotRelationQuery query) {
        return this.list(createBaseWrapper(query));
    }

    @Override
    public List<RRobotAccount> getAccountList(UserRobotRelationQuery query) {
        List<UserRobotRelation> list = this.list(createBaseWrapper(query));
        if(CollectionUtil.isEmpty(list)){
            return Collections.emptyList();
        }

        return robotAccountService.list(new LambdaQueryWrapper<RRobotAccount>().in(RRobotAccount::getId, list.stream().map(UserRobotRelation::getRobotId).collect(Collectors.toList())));
    }
    @Override
    public List<Long> getRobotIdsByUserId(Integer userId) {
        return this.list(new LambdaQueryWrapper<UserRobotRelation>().eq(UserRobotRelation::getUserId, userId)).stream().map(UserRobotRelation::getRobotId).collect(Collectors.toList());
    }

    @Override
    public List<User> getUserListByRobot(UserRobotRelationQuery query) {
        // 构建查询条件
        LambdaQueryWrapper<UserRobotRelation> wrapper = new LambdaQueryWrapper<>();

        if (query.getRobotId() != null) {
            wrapper.eq(UserRobotRelation::getRobotId, query.getRobotId());
        }

        // 查询用户粉丝关系
        List<UserRobotRelation> relations = this.list(wrapper);

        if (CollectionUtil.isEmpty(relations)) {
            return Collections.emptyList();
        }

        // 提取用户ID列表
        List<Integer> userIds = relations.stream()
                .map(UserRobotRelation::getUserId)
                .distinct()
                .collect(Collectors.toList());

        // 查询用户信息
        return userService.getList(new UserPageQuery().setIds(userIds));
    }

    // 添加批量保存并忽略错误的方法
    private void saveBatchIgnoreError(List<UserRobotRelation> list) {
        if (CollectionUtil.isEmpty(list)) {
            return;
        }

        try {
            // 通过自定义SQL实现 INSERT IGNORE
            String sql = "INSERT IGNORE INTO user_robot_relation (user_id, robot_id) VALUES ";
            StringBuilder values = new StringBuilder();

            for (int i = 0; i < list.size(); i++) {
                if (i > 0) {
                    values.append(",");
                }
                UserRobotRelation relation = list.get(i);
                values.append("(")
                        .append(relation.getUserId()).append(",")
                        .append(relation.getRobotId())
                        .append(")");
            }

            if (values.length() > 0) {
                String finalSql = sql + values.toString();
                System.err.println(finalSql);
                this.baseMapper.insertBatchIgnore(finalSql);
            }
        } catch (Exception e) {
            log.error("批量保存用户粉丝关系时发生异常", e);
            // 不抛出异常，继续处理其他批次
        }
    }


    private LambdaQueryWrapper<UserRobotRelation> createBaseWrapper(UserRobotRelationQuery query) {
        LambdaQueryWrapper<UserRobotRelation> wrapper = new LambdaQueryWrapper<>();
        if (query == null) {
            return wrapper;
        }
        wrapper.eq(query.getUserId() != null ,UserRobotRelation::getUserId, query.getUserId());
        wrapper.eq(query.getRobotId() != null ,UserRobotRelation::getRobotId, query.getRobotId());
        return wrapper;
    }
}




