package org.wfc.user.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.wfc.common.core.constant.WifiConstants;
import org.wfc.common.core.domain.LoginUser;
import org.wfc.common.security.utils.SecurityUtils;
import org.wfc.omada.api.client.OmadaClientApi;
import org.wfc.omada.api.client.model.ClientInfo;
import org.wfc.omada.api.client.model.OperationResponseClientGridVoClientInfo;
import org.wfc.user.api.domain.bo.UClientBo;
import org.wfc.user.domain.UClient;
import org.wfc.user.domain.vo.UClientCurrentVo;
import org.wfc.user.domain.vo.UClientHistoryUserVo;
import org.wfc.user.mapper.UClientMapper;
import org.wfc.user.service.IUAccountService;
import org.wfc.user.service.IUClientService;

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

/**
 * <p>
 * 用户平台_用户设备表 服务实现类
 * </p>
 *
 * @author cyc
 * @since 2024-12-09
 */
@Service
public class UClientServiceImpl extends ServiceImpl<UClientMapper, UClient> implements IUClientService {

    @Autowired
    private IUAccountService accountService;

    @Autowired
    private OmadaClientApi omadaClientApi;

    @Override
    public boolean recordClientUser(UClientBo uClientBo) {
        if (StrUtil.isBlank(uClientBo.getClientMac()) || StrUtil.isBlank(uClientBo.getSiteId())) {
            return false;
        }
        UClient hasUClient = this.getOne(Wrappers.<UClient>lambdaQuery()
                .eq(UClient::getSiteId, uClientBo.getSiteId())
                .eq(UClient::getClientMac, uClientBo.getClientMac()), false);
        UClient uClient = new UClient();
        BeanUtils.copyProperties(uClientBo, uClient);
        if (hasUClient != null) {
            uClient.setId(hasUClient.getId());
        }
        boolean flag = this.saveOrUpdate(uClient);
        // 登录时如果当前用户有可用套餐和余额授权当前设备访问wifi，且根据套餐限制带宽
        if (StrUtil.isNotBlank(uClientBo.getClientMac()) && StrUtil.isNotBlank(uClientBo.getSiteId())) {
            accountService.authClientAndRateLimit(uClientBo);
        }
        return flag;
    }

    @Override
    public List<UClientCurrentVo> getCurrentClients(Long userId) {

        List<UClient> clients = this.list(Wrappers.<UClient>lambdaQuery()
                .eq(UClient::getUserId, userId)
                .isNotNull(UClient::getClientMac)
                .isNotNull(UClient::getSiteId));

        // 根据site分组
        Map<String, List<UClient>> siteMap = clients.stream().collect(Collectors.groupingBy(UClient::getSiteId));
        List<UClientCurrentVo> clientVos = new ArrayList<>();
        for (Map.Entry<String, List<UClient>> siteEntry : siteMap.entrySet()) {
            String siteId = siteEntry.getKey();
            // 查出在线client
            ResponseEntity<OperationResponseClientGridVoClientInfo> activeClientRes = omadaClientApi.getGridActiveClients(siteId, 1, 1000);
            if (activeClientRes.getBody() == null) {
                continue;
            }
            if (activeClientRes.getBody().getResult() == null) {
                continue;
            }
            List<ClientInfo> activeClients = activeClientRes.getBody().getResult().getData();
            List<UClient> loginClients = siteEntry.getValue();
            long i = 0;
            for (UClient loginClient : loginClients) {
                Optional<ClientInfo> clientOptional = activeClients.stream()
                        .filter(c -> Objects.equals(c.getMac(), loginClient.getClientMac()) && c.getAuthStatus() == WifiConstants.AUTH_STATUS_AUTHORIZED).findFirst();
                if (clientOptional.isPresent()) {
                    ClientInfo clientInfo = clientOptional.get();
                    UClientCurrentVo clientVo = new UClientCurrentVo();
                    clientVo.setId(i);
                    clientVo.setClientMac(clientInfo.getMac());
                    clientVo.setClientName(clientInfo.getName());
                    clientVo.setActivity(clientInfo.getActivity());
                    clientVo.setTrafficDown(clientInfo.getTrafficDown());
                    clientVo.setTrafficUp(clientInfo.getTrafficUp());
                    clientVo.setUpTime(clientInfo.getUptime());
                    clientVo.setSiteId(siteId);
                    clientVos.add(clientVo);
                    i++;
                }
            }
        }

        return clientVos;
    }

    @Override
    public List<UClientHistoryUserVo> getHistoryByUser() {
        LoginUser<Object> loginUser = SecurityUtils.getLoginUser();
        if (ObjectUtil.isNull(loginUser)) {
            return Collections.emptyList();
        }
        return this.baseMapper.getHistoryByUser(loginUser.getUserid());
    }
}
