package com.emr.controller;

import com.alibaba.fastjson.JSON;
import com.emr.entity.Power_User;
import com.emr.service.CommomService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.cxf.endpoint.Client;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @author HJL
 * @create 2019/4/29
 */
@Slf4j
@Controller
public class LoginController {
    @Value("${STR_SPLIT}")
    private String STR_SPLIT;
    @Value("${POWER_URLHEAD}")
    private String POWER_URLHEAD;
    @Value("${POWER_JSP}")
    private String POWER_JSP;
    @Value("${WEBSOCKET_URLHEAD}")
    private String WEBSOCKET_URLHEAD;
    @Value("${TOKEN_EXPIRE_TIME}")
    private long TOKEN_EXPIRE_TIME;
    @Autowired
    private CommomService commomService;

    @RequestMapping(value = "/toLogin")
    public String toLogin(Model model) {
        return "Login";
    }

    @RequestMapping(value = "/login")
    public String login(String token, Model model, String userName, HttpServletRequest request) throws Exception {
        if (StringUtils.isNoneBlank(token)) {
            //创建连接工厂
            JAXDynamicClientFactory dcf = JAXDynamicClientFactory.newInstance();
            //创建客户端
            Object[] objects = new Object[0];
            Client client = null;
            try {
                client = dcf.createClient(POWER_URLHEAD + "/WebService/PowerWebService?wsdl");
                //动态调用getInfosByUserId方法
                objects = client.invoke("getInfosByUserId", token, "emr_record");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if(null != client) {
                    client.destroy();
                }
            }

            Power_User powerUser = JSON.parseObject(objects[0].toString(), Power_User.class);
            //返回用户为空跳转到登录权限系统界面
            if (null == powerUser) {
                return "redirect:" + POWER_URLHEAD + "/login";
            }
            powerUser.setUserName(userName);
            //设置进session
            request.getSession().setAttribute("CURRENT_USER", powerUser);
            request.getSession().setAttribute("power_menus", powerUser.getMenus());
            request.getSession().setAttribute("token", token);

            //验证shiro(有shiro才此操作)
            UsernamePasswordToken userToken = new UsernamePasswordToken(userName, "123456");
            Subject subject = SecurityUtils.getSubject();
            subject.login(userToken);
            model.addAttribute("POWER_URLHEAD", POWER_URLHEAD);
            model.addAttribute("POWER_JSP", POWER_JSP);
            //传递通知需要的数据
            model.addAttribute("WEBSOCKET_URLHEAD", WEBSOCKET_URLHEAD);
            model.addAttribute("STR_SPLIT", STR_SPLIT);
            //获取用户列表
            // 获得Http客户端
            if (StringUtils.isNotBlank(userName) && powerUser.getRoleId() == -100) {
                try {
                    commomService.getUserList(userName, request);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else {
            return "redirect:" + POWER_URLHEAD + "/login";
        }
        return "redirect:/index.jsp";
    }

    @RequestMapping("/refuse")
    public String refuse() {
        return "redirect:refuse.jsp";
    }

    //获取session所剩时间
    @RequestMapping(value = "getSessionRemainingTime", method = RequestMethod.GET, produces = {"text/json;charset=UTF-8"})
    @ResponseBody
    public String getSessionRemainingTime(HttpServletRequest request) throws Exception {
        long lastAccessTime = 0L;
        String sessionId = request.getSession().getId();
        lastAccessTime = (long) request.getSession().getAttribute(sessionId);
        return JSON.toJSONString(TOKEN_EXPIRE_TIME - (System.currentTimeMillis() - lastAccessTime));
    }
}
 

