package com.sptg.gateway.controller.auth;

import com.sptg.common.core.beans.ResultBean;
import com.sptg.common.core.beans.ResultEnum;
import com.sptg.common.security.annotation.Security;
import com.sptg.common.security.enums.DataFormatEnum;
import com.sptg.common.security.service.SecurityServiceInterface;
import com.sptg.permissions.api.entity.DeviceAdminUser;
import com.sptg.permissions.api.feigns.DeviceAdminUserFeign;
import lombok.RequiredArgsConstructor;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * title: LoginController
 * description: 登陆控制器
 *
 *                  
 *            
 */
@RestController
@RequiredArgsConstructor
public class LoginController {

    private final DeviceAdminUserFeign userFeign;
    private final SecurityServiceInterface<DeviceAdminUser> securityServiceInterface;

    @PostMapping(value = "/auth/login")
    public ResultBean<DeviceAdminUser> login(@RequestBody DeviceAdminUser user){
        Assert.hasText(user.getLoginName(),"登录名称不能为空");
        Assert.hasText(user.getLoginPwd(),"登录密码不能为空");
        //  登陆校验
        ResultBean<DeviceAdminUser> resultBean = this.userFeign.login(user);
        if (resultBean.getCode().equals(ResultEnum.SUCCESS.getCode())){
            //  登陆成功
            String token = this.securityServiceInterface.createUserToken(resultBean.getData());
            DeviceAdminUser data = resultBean.getData();
            data.setLoginToken(token);
            //  TODO    更新账号

        }
        return resultBean;
    }

    @Security(format = DataFormatEnum.JSON)
    @PostMapping(value = "/auth/logout")
    public ResultBean logout(){
        this.securityServiceInterface.removeUserToken();
        return new ResultBean<>(ResultEnum.SUCCESS);
    }

}
