package com.imdroid.sec_exapi.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.imdroid.common.util.GsonUtil;
import com.imdroid.sec_exapi.auth.TokenUtils;
import com.imdroid.sec_exapi.entity.LoginResponse;
import com.imdroid.secapi.dto.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
public class UserApi {
    @Autowired
    private TenantMapper tenantMapper;
    @Autowired
    ApiKeyMapper apiMapper;
    @Autowired
    OpLogManager opLogManager;
    @Autowired
    GnssDeviceMapper deviceMapper;

    final Logger logger = LoggerFactory.getLogger(UserApi.class);

    // 登录
    @PostMapping(value = "/login" )
    public String login(String apiKey, String apiSecret, HttpServletResponse response) {
        QueryWrapper<ApiKey> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("apikey", apiKey);
        ApiKey api = apiMapper.selectOne(queryWrapper1);
        LoginResponse loginResponse = new LoginResponse();
        if (api == null || !api.getSecret().equals(apiSecret)) {
            loginResponse.failed();
        }
        else {
            opLogManager.addLog(api.getApikey(), api.getTenantid(),
                    OpLogManager.OP_TYPE_LOGIN,
                    OpLogManager.OP_OBJ_USER,
                    "api login");
            loginResponse.OK();
            String token = TokenUtils.getToken(apiKey, apiSecret);
            loginResponse.setToken(token);

            //查询项目
            Tenant tenant = tenantMapper.selectById(api.getTenantid());
            QueryWrapper<GnssDevice> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("tenantid", tenant.getId());
            queryWrapper.eq("opmode", GnssDevice.OP_MODE_USE);
            queryWrapper.select("project_id");
            queryWrapper.groupBy("project_id");
            List<GnssDevice> gnssDeviceList = deviceMapper.selectList(queryWrapper);
            for(GnssDevice device:gnssDeviceList){
                loginResponse.addProject(device.getProject_id());
            }

            Cookie cookie = new Cookie("token", token);
            cookie.setPath("/");
            response.addCookie(cookie);
        }

        String json = GsonUtil.toJson(loginResponse);
        logger.info(json);

        return json;
    }

}


