package cn.qg.qaplatform.controller.yxm;

import cn.qg.qaplatform.config.SwitchDataSource;
import cn.qg.qaplatform.entity.loginrisk.LoginInfo;
import cn.qg.qaplatform.entity.loginrisk.WhiteList;
import cn.qg.qaplatform.entity.vo.LoginWhiteListVo;
import cn.qg.qaplatform.service.loginRisk.WhiteListService;
import cn.qg.qaplatform.service.loginRisk.LoginInfoService;
import cn.qg.qaplatform.utils.JsonResult;
import cn.qg.qaplatform.utils.Result;
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("/login")
public class LoginRiskController {

    @Autowired
    LoginInfoService loginInfoService;

    @Autowired
    WhiteListService whiteListService;

//    /**
//     * 添加登录白名单
//     * @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 loginWhiteListVo 登录白名单实体类
     * @return
     */
    @PostMapping("/addWhiteList")
    public Result addLoginWhiteList(@RequestBody LoginWhiteListVo loginWhiteListVo) {
        SwitchDataSource.dataSourceSwitch(loginWhiteListVo.getNamespace(), "login_risk");
        WhiteList whiteList = new WhiteList();
        whiteList.setEnable(1);
        whiteList.setKey(loginWhiteListVo.getKey());
        whiteList.setKeyType(loginWhiteListVo.getKeyType());
        return Result.buildSuccessResult(whiteListService.save(whiteList));
    }

    /**
     * 登录信息展示
     * @param namespace 环境
     * @param pageNum 第几页
     * @param pageSize 每页多少个
     * @return
     */
    @GetMapping("/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);
    }
}
