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.stereotype.Service;
import org.wfc.common.core.domain.LoginUser;
import org.wfc.common.security.utils.SecurityUtils;
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.Collections;
import java.util.List;

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

    @Autowired
    private IUAccountService accountService;

    @Override
    public boolean recordClientUser(UClientBo uClientBo) {
        if (StrUtil.isBlank(uClientBo.getClientMac())) {
            return false;
        }
        UClient hasUClient = this.getOne(Wrappers.<UClient>lambdaQuery()
                .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.getClientName()) && StrUtil.isNotBlank(uClientBo.getSiteId())) {
            accountService.authClientAndRateLimit(uClientBo);
        }
        return flag;
    }

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

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