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;

    @GetMapping("/whitelist")
    public JsonResult addLoginWhiteList(String namespace, String key, Integer keyType) {
        boolean result = commonService.addLoginWhiteList(namespace, key, keyType);
        return JsonResult.success(result);
    }

    @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);
    }
}
