package com.gyee.frame.controller.ticket;

import com.gyee.frame.common.conf.UserLoginContext;
import com.gyee.frame.common.dataSources.DataSource;
import com.gyee.frame.common.dataSources.DataSourceType;
import com.gyee.frame.common.domain.AjaxResult;
import com.gyee.frame.model.enumeration.Messagetype;
import com.gyee.frame.model.ticket.Ibsusers;
import com.gyee.frame.model.ticket.Labor;
import com.gyee.frame.netty.websocket.util.SocketToolController;
import com.gyee.frame.service.ticket.IbsusersService;
import com.gyee.frame.service.ticket.LaborService;
import com.gyee.frame.service.ticket.ShiroService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.websocket.Session;
import java.util.Map;

@RestController
public class LoginController  extends SocketToolController {

    @Autowired
    LaborService laborService;
    @Autowired
    IbsusersService ibsusersService;
    @Autowired
    ShiroService shiroService;

    @SneakyThrows
    @DataSource(value = DataSourceType.TICKET)
    @PostMapping(value = "sys/login")
    public AjaxResult login(@RequestParam("username") String username, @RequestParam("password") String password){
        Labor labor = laborService.getLabor(username, password);
        Ibsusers user = ibsusersService.findUser(username, password);
        if (labor == null || user == null)
            return AjaxResult.error(4004, "用户名或密码错误");

        String id=String.valueOf(labor.getId());
        if(UserLoginContext.userLoginMap.containsKey(id))
        {


            this.pushToWeb("pageNumber_4","functionNumber_5",id,"loginout", Messagetype.MESSAGE);
            Session session= UserLoginContext.userLoginMap.get(id);
            session.close();
            UserLoginContext.userLoginMap.remove(id);

        }

        Map<String, Object> token = shiroService.createToken(labor);


        return AjaxResult.successData(token);
    }

    @PostMapping(value = "sys/logout")
    public AjaxResult logout(@RequestHeader("token")String token){
        shiroService.logout(token);

        return AjaxResult.successData("您已安全退出系统");
    }
}
