package com.fs.feishu.service.impl;

import com.fs.common.exception.CustomException;
import com.fs.feishu.domain.FeishuAccount;
import com.fs.feishu.mapper.FeishuAccountMapper;
import com.fs.feishu.service.FeishuClientPool;
import com.fs.feishu.service.IFeishuAccountService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class FeishuAccountServiceImpl implements IFeishuAccountService {

    @Autowired
    private FeishuAccountMapper feishuAccountMapper;

    @Autowired
    private FeishuClientPool clientPool;

    @Override
    public List<FeishuAccount> selectFeishuAccountList(Map<String, Object> params) {
        return feishuAccountMapper.selectListByMap(params);
    }

    @Override
    public List<FeishuAccount> selectCompanyFeishuAccountList(Map<String, Object> params) {
        return feishuAccountMapper.selectCompanyListByMap(params);
    }

    @Override
    public List<FeishuAccount> selectEnabledByCompanyUserId(Long companyUserId) {
        return feishuAccountMapper.selectEnabledByCompanyUserId(companyUserId);
    }

    @Override
    public FeishuAccount selectFeishuAccountById(Long id) {
        return feishuAccountMapper.selectById(id);
    }

    @Override
    public int insertFeishuAccount(FeishuAccount account) {
        if (StringUtils.isBlank(account.getAppId()) || StringUtils.isBlank(account.getAppSecret())) {
            throw new CustomException("AppId and AppSecret are required");
        }
        if (account.getStatus() == null) {
            account.setStatus(1);
        }
        if (account.getNumberUse() == null) {
            account.setNumberUse(0L);
        }
        Date now = new Date();
        account.setCreateTime(now);
        account.setUpdateTime(now);
        int rows = feishuAccountMapper.insert(account);
        if (rows > 0) {
            clientPool.refreshPool(account.getCompanyUserId());
        }
        return rows;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertFeishuAccountBatch(List<FeishuAccount> accounts) {
        if (accounts == null || accounts.isEmpty()) {
            throw new CustomException("至少传入一条账号");
        }
        int count = 0;
        for (int i = 0; i < accounts.size(); i++) {
            FeishuAccount account = accounts.get(i);
            try {
                count += insertFeishuAccount(account);
            } catch (CustomException e) {
                throw new CustomException("第" + (i + 1) + "条账号新增失败: " + e.getMessage());
            }
        }
        return count;
    }

    @Override
    public int updateFeishuAccount(FeishuAccount account) {
        FeishuAccount existing = account.getId() != null ? feishuAccountMapper.selectById(account.getId()) : null;
        account.setUpdateTime(new Date());
        int rows = feishuAccountMapper.update(account);
        if (rows > 0 && existing != null) {
            clientPool.refreshPool(existing.getCompanyUserId());
            Long newCompanyUserId = account.getCompanyUserId();
            if (newCompanyUserId != null && !newCompanyUserId.equals(existing.getCompanyUserId())) {
                clientPool.refreshPool(newCompanyUserId);
            }
        }
        return rows;
    }

    @Override
    public int deleteFeishuAccountById(Long id) {
        FeishuAccount existing = feishuAccountMapper.selectById(id);
        int rows = feishuAccountMapper.deleteById(id);
        if (rows > 0 && existing != null) {
            clientPool.refreshPool(existing.getCompanyUserId());
        }
        return rows;
    }

    @Override
    public void validateOwnership(FeishuAccount account, Long companyId, Long companyUserId) {
        if (account == null) {
            throw new CustomException("账号不存在");
        }
        if (companyId != null && account.getCompanyId() != null && !companyId.equals(account.getCompanyId())) {
            throw new CustomException("权限校验不通过");
        }
        if (companyUserId != null && account.getCompanyUserId() != null && !companyUserId.equals(account.getCompanyUserId())) {
            throw new CustomException("权限校验不通过");
        }
    }

    @Override
    public void validateCompanyScope(FeishuAccount account, Long companyId) {
        if (account == null) {
            throw new CustomException("账号不存在");
        }
        if (companyId == null || account.getCompanyId() == null || !companyId.equals(account.getCompanyId())) {
            throw new CustomException("权限校验不通过");
        }
    }

    @Override
    public Long pollSendAccountId(Long companyUserId) {
        if (companyUserId == null) {
            throw new CustomException("用户ID不能为空");
        }
        return clientPool.pollNextAccountId(companyUserId);
    }

    @Override
    public Long resolveSendAccountId(Long companyUserId, Long feishuAccountId) {
        if (companyUserId == null) {
            throw new CustomException("用户ID不能为空");
        }
        if (feishuAccountId != null) {
            requireEnabledAccount(feishuAccountId, companyUserId);
            return feishuAccountId;
        }
        return pollSendAccountId(companyUserId);
    }

    @Override
    public FeishuAccount resolveEnabledOrLatestAccount(Long companyUserId, Long preferredAccountId) {
        if (companyUserId == null) {
            throw new CustomException("用户ID不能为空");
        }
        if (preferredAccountId != null) {
            FeishuAccount preferred = feishuAccountMapper.selectById(preferredAccountId);
            if (preferred != null
                    && companyUserId.equals(preferred.getCompanyUserId())
                    && Integer.valueOf(1).equals(preferred.getStatus())
                    && StringUtils.isNotBlank(preferred.getAppId())) {
                return preferred;
            }
        }
        List<FeishuAccount> enabled = feishuAccountMapper.selectEnabledByCompanyUserId(companyUserId);
        if (enabled == null || enabled.isEmpty()) {
            throw new CustomException("当前销售没有可用的飞书账号，请先配置或更换账号");
        }
        // 选最新启用账号（id 最大）；旧账号被封后应换新号重建飞书链接
        FeishuAccount latest = null;
        for (FeishuAccount account : enabled) {
            if (account == null || account.getId() == null || StringUtils.isBlank(account.getAppId())) {
                continue;
            }
            if (latest == null || account.getId() > latest.getId()) {
                latest = account;
            }
        }
        if (latest == null) {
            throw new CustomException("当前销售没有可用的飞书账号，请先配置或更换账号");
        }
        return latest;
    }

    private FeishuAccount requireEnabledAccount(Long feishuAccountId, Long companyUserId) {
        FeishuAccount account = feishuAccountMapper.selectById(feishuAccountId);
        if (account == null) {
            throw new CustomException("账号不存在");
        }
        if (!companyUserId.equals(account.getCompanyUserId())) {
            throw new CustomException("该账号不属于当前用户");
        }
        if (!Integer.valueOf(1).equals(account.getStatus())) {
            throw new CustomException("账号不可用: " + account.getErrorMsg());
        }
        return account;
    }

}
