package com.moka.gdtauto.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moka.gdtauto.entity.AccountGroup;
import com.moka.gdtauto.entity.AccountGroupAccountRelationship;
import com.moka.gdtauto.entity.TencentAccount;
import com.moka.gdtauto.mapper.AccountGroupAccountRelationshipMapper;
import com.moka.gdtauto.mapper.AccountGroupMapper;
import com.moka.gdtauto.service.AccountGroupService;
import com.moka.gdtauto.service.TencentAccountService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 账号组服务实现类
 * 
 * @author moka
 * @since 2026-02-24
 */
@Slf4j
@Service
public class AccountGroupServiceImpl extends ServiceImpl<AccountGroupMapper, AccountGroup> implements AccountGroupService {

    @Autowired
    private AccountGroupAccountRelationshipMapper relationshipMapper;
    
    @Autowired
    private TencentAccountService tencentAccountService;

    /**
     * 校验账号ID是否存在
     * 
     * @param accountIds 账号ID列表
     * @return 不存在的账号ID列表
     */
    private List<Long> validateAccountIds(List<Long> accountIds) {
        if (accountIds == null || accountIds.isEmpty()) {
            return new ArrayList<>();
        }
        
        List<Long> invalidIds = new ArrayList<>();
        for (Long accountId : accountIds) {
            TencentAccount account = tencentAccountService.lambdaQuery()
                    .eq(TencentAccount::getAccountId, accountId)
                    .eq(TencentAccount::getDeleted, 0)
                    .one();
            if (account == null) {
                invalidIds.add(accountId);
            }
        }
        return invalidIds;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createAccountGroup(Long userId, String groupName, Integer deliveryMode, String remark, List<Long> accountIds) {
        AccountGroup accountGroup = new AccountGroup();
        accountGroup.setUserId(userId);
        accountGroup.setGroupName(groupName);
        accountGroup.setDeliveryMode(deliveryMode);
        accountGroup.setRemark(remark);
        accountGroup.setCreateTime(LocalDateTime.now());
        accountGroup.setUpdateTime(LocalDateTime.now());
        accountGroup.setDeleted(0);
        
        this.save(accountGroup);
        log.info("创建账号组成功，用户ID: {}, 账号组ID: {}, 账号组名称: {}", userId, accountGroup.getId(), groupName);
        
        // 如果有账号ID列表，批量添加关系
        if (accountIds != null && !accountIds.isEmpty()) {
            List<AccountGroupAccountRelationship> relationships = new ArrayList<>();
            LocalDateTime now = LocalDateTime.now();
            for (Long accountId : accountIds) {
                AccountGroupAccountRelationship relationship = new AccountGroupAccountRelationship();
                relationship.setGroupId(accountGroup.getId());
                relationship.setAccountId(accountId);
                relationship.setCreateTime(now);
                relationship.setUpdateTime(now);
                relationships.add(relationship);
            }
            relationshipMapper.batchInsert(relationships);
            log.info("批量添加账号到账号组，账号组ID: {}, 账号数: {}", accountGroup.getId(), accountIds.size());
        }
        
        return accountGroup.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateAccountGroup(Long groupId, Long userId, String groupName, Integer deliveryMode, String remark, List<Long> accountIds) {
        // 验证账号组是否属于该用户
        AccountGroup existingGroup = this.getOne(new LambdaQueryWrapper<AccountGroup>()
                .eq(AccountGroup::getId, groupId)
                .eq(AccountGroup::getUserId, userId)
                .eq(AccountGroup::getDeleted, 0));
        
        if (existingGroup == null) {
            log.warn("账号组不存在或无权限，账号组ID: {}, 用户ID: {}", groupId, userId);
            return false;
        }
        
        
        existingGroup.setGroupName(groupName);
        existingGroup.setDeliveryMode(deliveryMode);
        existingGroup.setRemark(remark);
        existingGroup.setUpdateTime(LocalDateTime.now());
        
        boolean result = this.updateById(existingGroup);
        log.info("更新账号组成功，账号组ID: {}, 用户ID: {}", groupId, userId);
        
        // 如果有账号ID列表，更新关系（先删除旧关系，再添加新关系）
        if (accountIds != null) {
            // 删除旧关系
            relationshipMapper.delete(new LambdaQueryWrapper<AccountGroupAccountRelationship>()
                    .eq(AccountGroupAccountRelationship::getGroupId, groupId));
            
            // 添加新关系
            if (!accountIds.isEmpty()) {
                List<AccountGroupAccountRelationship> relationships = new ArrayList<>();
                LocalDateTime now = LocalDateTime.now();
                for (Long accountId : accountIds) {
                    AccountGroupAccountRelationship relationship = new AccountGroupAccountRelationship();
                    relationship.setGroupId(groupId);
                    relationship.setAccountId(accountId);
                    relationship.setCreateTime(now);
                    relationship.setUpdateTime(now);
                    relationships.add(relationship);
                }
                relationshipMapper.batchInsert(relationships);
                log.info("更新账号组关联账号，账号组ID: {}, 新账号数: {}", groupId, accountIds.size());
            } else {
                log.info("清空账号组关联账号，账号组ID: {}", groupId);
            }
        }
        
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteAccountGroup(Long groupId, Long userId) {
        // 验证账号组是否属于该用户
        AccountGroup existingGroup = this.getOne(new LambdaQueryWrapper<AccountGroup>()
                .eq(AccountGroup::getId, groupId)
                .eq(AccountGroup::getUserId, userId)
                .eq(AccountGroup::getDeleted, 0));
        
        if (existingGroup == null) {
            log.warn("账号组不存在或无权限，账号组ID: {}, 用户ID: {}", groupId, userId);
            return false;
        }
        
        // 逻辑删除账号组
        existingGroup.setDeleted(1);
        existingGroup.setUpdateTime(LocalDateTime.now());
        this.updateById(existingGroup);
        
        // 删除关联关系
        relationshipMapper.delete(new LambdaQueryWrapper<AccountGroupAccountRelationship>()
                .eq(AccountGroupAccountRelationship::getGroupId, groupId));
        
        log.info("删除账号组成功，账号组ID: {}, 用户ID: {}", groupId, userId);
        return true;
    }

    @Override
    public Page<AccountGroup> getUserAccountGroups(Long userId, Integer pageNum, Integer pageSize) {
        Page<AccountGroup> page = new Page<>(pageNum, pageSize);
        
        LambdaQueryWrapper<AccountGroup> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AccountGroup::getDeleted, 0)
                .orderByDesc(AccountGroup::getCreateTime);
        
        return this.page(page, queryWrapper);
    }

    @Override
    public AccountGroup getAccountGroupById(Long groupId, Long userId) {
        return this.getOne(new LambdaQueryWrapper<AccountGroup>()
                .eq(AccountGroup::getId, groupId)
                .eq(AccountGroup::getDeleted, 0));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addAccountsToGroup(Long groupId, List<Long> accountIds, Long userId) {
        // 验证账号组是否属于该用户
        AccountGroup existingGroup = this.getAccountGroupById(groupId, userId);
        if (existingGroup == null) {
            log.warn("账号组不存在或无权限，账号组ID: {}, 用户ID: {}", groupId, userId);
            return false;
        }
        
        // 查询已存在的关系
        List<AccountGroupAccountRelationship> existingRelations = relationshipMapper.selectList(
                new LambdaQueryWrapper<AccountGroupAccountRelationship>()
                        .eq(AccountGroupAccountRelationship::getGroupId, groupId)
                        .in(AccountGroupAccountRelationship::getAccountId, accountIds));
        
        List<Long> existingAccountIds = existingRelations.stream()
                .map(AccountGroupAccountRelationship::getAccountId)
                .collect(Collectors.toList());
        
        // 过滤出需要新增的账号ID
        List<Long> newAccountIds = accountIds.stream()
                .filter(id -> !existingAccountIds.contains(id))
                .collect(Collectors.toList());
        
        if (newAccountIds.isEmpty()) {
            log.info("所有账号已存在于账号组中，账号组ID: {}", groupId);
            return true;
        }
        
        // 批量插入关系
        List<AccountGroupAccountRelationship> relationships = new ArrayList<>();
        LocalDateTime now = LocalDateTime.now();
        for (Long accountId : newAccountIds) {
            AccountGroupAccountRelationship relationship = new AccountGroupAccountRelationship();
            relationship.setGroupId(groupId);
            relationship.setAccountId(accountId);
            relationship.setCreateTime(now);
            relationship.setUpdateTime(now);
            relationships.add(relationship);
        }
        relationshipMapper.batchInsert(relationships);
        
        log.info("添加账号到账号组成功，账号组ID: {}, 新增账号数: {}", groupId, newAccountIds.size());
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeAccountsFromGroup(Long groupId, List<Long> accountIds, Long userId) {
        // 验证账号组是否属于该用户
        AccountGroup existingGroup = this.getAccountGroupById(groupId, userId);
        if (existingGroup == null) {
            log.warn("账号组不存在或无权限，账号组ID: {}, 用户ID: {}", groupId, userId);
            return false;
        }
        
        // 删除关系
        int deletedCount = relationshipMapper.delete(new LambdaQueryWrapper<AccountGroupAccountRelationship>()
                .eq(AccountGroupAccountRelationship::getGroupId, groupId)
                .in(AccountGroupAccountRelationship::getAccountId, accountIds));
        
        log.info("从账号组移除账号成功，账号组ID: {}, 移除账号数: {}", groupId, deletedCount);
        return true;
    }

    @Override
    public List<Long> getAccountIdsByGroupId(Long groupId, Long userId) {
        // 验证账号组是否属于该用户
        AccountGroup existingGroup = this.getAccountGroupById(groupId, userId);
        if (existingGroup == null) {
            log.warn("账号组不存在或无权限，账号组ID: {}, 用户ID: {}", groupId, userId);
            return List.of();
        }
        
        List<AccountGroupAccountRelationship> relationships = relationshipMapper.selectList(
                new LambdaQueryWrapper<AccountGroupAccountRelationship>()
                        .eq(AccountGroupAccountRelationship::getGroupId, groupId));
        
        return relationships.stream()
                .map(AccountGroupAccountRelationship::getAccountId)
                .collect(Collectors.toList());
    }
}
