package cn.qg.qaplatform.controller.stools;

import cn.qg.qaplatform.config.SwitchDataSource;
import cn.qg.qaplatform.entity.stools.LoginInfo;
import cn.qg.qaplatform.service.stools.CommonService;
import cn.qg.qaplatform.service.stools.LoginInfoService;
import cn.qg.qaplatform.utils.JsonResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/common")
public class CommonController {

    @Autowired
    CommonService commonService;

    @Autowired
    LoginInfoService loginInfoService;

    /**
     * 添加登录白名单
     * @param namespace 环境
     * @param key 白名单值，设备id/手机号
     * @param keyType 白名单类型，0-手机号，1-设备id
     * @return
     */
    @GetMapping("/whitelist")
    public JsonResult addLoginWhiteList(String namespace, String key, Integer keyType) {
        boolean result = commonService.addLoginWhiteList(namespace, key, keyType);
        return JsonResult.success(result);
    }

    /**
     * 登录信息展示
     * @param namespace 环境
     * @param pageNum 第几页
     * @param pageSize 每页多少个
     * @return
     */
    @GetMapping("/logininfo/list")
    public JsonResult getLoginInfoList(String namespace, Integer pageNum, Integer pageSize) {
        SwitchDataSource.dataSourceSwitch(namespace, "login_risk");
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc("created_at");
        IPage<LoginInfo> page = new Page<>(pageNum, pageSize);
        IPage<LoginInfo> pageEntity = loginInfoService.page(page, queryWrapper);
        Map<String, Object> result = new HashMap<>();
        result.put("list", pageEntity.getRecords());
        result.put("total", pageEntity.getTotal());
        return JsonResult.success(result);
    }
}
