package com.manage.controller;

import com.alibaba.fastjson.JSON;
import com.manage.dao.Power_Login_SetMapper;
import com.manage.encrypt.Base64;
import com.manage.encrypt.MD5;
import com.manage.entity.*;
import com.manage.service.*;
import com.manage.service.cache.Cache;
import com.manage.service.cache.CacheManager;
import com.manage.util.*;
import com.manage.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
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 org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class LoginController {
    @Value("${TOKEN_EXPIRE_TIME}")
    private long TOKEN_EXPIRE_TIME;
    @Value("${sysFlag}")
    private Integer sysFlag;
    @Autowired
    private Power_UserService powerUserService;
    @Autowired
    private Power_MenuService powerMenuService;
    @Autowired
    private LogService logService;
    @Autowired
    private Power_DeptService power_deptService;
    @Autowired
    private Power_Login_SetMapper powerLoginSetMapper;

    @Value("${EMRMEDICALRECORD_URLHEAD}")
    private String EMRMEDICALRECORD_URLHEAD;

    @Value("${EMRMEDICALRECORD_IP}")
    private String ip;

    @Value("${EMRMEDICALRECORD_PORT}")
    private String port;

    @Value("${POWER_PORT}")
    private String POWER_PORT;

    @RequestMapping(value = "login",method = RequestMethod.GET)
    public String toLogin(Model model){
        Power_Login_Set loginSet = powerLoginSetMapper.selectByPrimaryKey(sysFlag);
        model.addAttribute("loginSet",loginSet);
        CacheManager.addExcCount("noExc");
        return "loginDir/login";
    }

    @RequestMapping(value = "login",method = RequestMethod.POST)
    @ResponseBody
    public Msg login(Power_User powerUser,HttpServletResponse response, HttpServletRequest request,Model model){
        try {
            Power_UserVo user = powerUserService.findPowerUserByUserNameAndUserPwd(powerUser);
            //添加进操作日志
            Power_Log log = new Power_Log();
            if(user != null){
                //存session密码置空
                //是否记住密码功能
                MyCookieUtil.remember(request, response);
                //设置token缓存
                String token = UUID.randomUUID().toString();
                //查询归属医院
                /*long start5 = System.currentTimeMillis();
                Power_User_Dict powerUserDict = powerUserDictMapper.selectDictIdByUserId(user.getUserId());
                long end5  = System.currentTimeMillis();
                System.out.println("查询医院时间="+(end5-start5)/1000.0+"s");
                user.setDictId(powerUserDict.getDictId());*/
                //设置用户登录次数缓存
                //CacheManager.addloginUserCount(fmt.format(new Date()),user.getUserName());
                CacheManager.addExcCount("noExc");
                List<Power_Menu> list = null;
                List<User_Dept_Menu> menuList = new ArrayList<>();
                Set<String> menus = new LinkedHashSet<>();
                if (user.getRoleId().equals(0) || user.getRoleId().equals(-100)) {
                    list = powerMenuService.queryAllPowerMenu(null,user.getRoleId());
                } else {
                    list = powerMenuService.selectUserAndRoleMenuListPower(user.getUserId(),null);
                }
                if(null != list && !list.isEmpty()){
                    for (Power_Menu powerMenu : list) {
                        User_Dept_Menu deptMenu = new User_Dept_Menu();
                        String menuUrl = powerMenu.getMenuUrl();
                        if (StringUtils.isNotBlank(menuUrl)) {
                            BeanUtils.copyProperties(powerMenu, deptMenu);
                            deptMenu.setMethodParent(powerMenu.getParentId());
                            menuList.add(deptMenu);
                        }
                        if (StringUtils.isNotBlank(powerMenu.getMethod())) {
                            menus.add(powerMenu.getMenuUrl());
                        }
                    }
                }
                user.setMenuList(menuList);
                user.setMenus(menus);
                //设置科室
                StringBuilder powerDepts = new StringBuilder();
                List<Power_Dept> powerDeptsList = power_deptService.selectByPrimaryKeys(user.getDeptId());
                for(int j=0;j<powerDeptsList.size();j++){
                    if(j<powerDeptsList.size()-1){
                        powerDepts.append(powerDeptsList.get(j).getDeptName()).append(",");
                    }else{
                        powerDepts.append(powerDeptsList.get(j).getDeptName());
                    }
                }
                Integer roleId = user.getRoleId();
                if(null != roleId && roleId != 0 && roleId != -100){
                    user.setRemark(powerDepts.toString());
                }
                //清除用户登录错误次数缓存
                CacheManager.clearOnly(powerUser.getUserName());
                //设置进缓存
                CacheManager.putCache(token,new Cache(user,System.currentTimeMillis(),TOKEN_EXPIRE_TIME*1000));
                ActionScopeUtils.setSessionAttribute("token",token,Integer.valueOf(String.valueOf(TOKEN_EXPIRE_TIME)));
                ActionScopeUtils.setSessionAttribute("CURRENT_USER",user,Integer.valueOf(String.valueOf(TOKEN_EXPIRE_TIME)));
                //单点登录跳转
                String url = "";
                if(sysFlag == 2){
                    url = EMRMEDICALRECORD_URLHEAD+"/login?token="+token+"&userName="+user.getUserName()+"&flag=1";
                }else{
                    url = "http://"+ip+":"+POWER_PORT+"/power/gatewayPage";
                }
                //request.getRequestDispatcher(url).forward(request, response);

                //response.sendRedirect(url);
                //return "redirect:gatewayPage";
                return Msg.success().add("url",url);
            }else{
                //登录失败
                Integer wrongNum = 1;
                Cache cache = CacheManager.getCacheInfo(powerUser.getUserName());
                if(cache != null){
                    //缓存中错误次数
                    Integer currentNum = (Integer)cache.getValue();
                    //叠加1
                    wrongNum += currentNum;
                }
                //添加缓存
                CacheManager.putCache(powerUser.getUserName(),new Cache(wrongNum));
                log.setCreater(powerUser.getUserName());
                log.setLogTitle("登录");
                log.setLogContent("用户密码错误");
                log.setRemark("已错误【"+wrongNum+"】次");
                logService.insert(log);
                request.setAttribute("msg", "用户名或密码不正确");
            }
        }catch (Exception e){
            e.printStackTrace();
            CacheManager.addExcCount("exc");
        }
        return null;
    }
    @RequestMapping("refuse")
    public String refuse(){
        return "refuse";
    }


    //获取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();
        Object attribute = request.getSession().getAttribute(sessionId);
        if(null != attribute){
            lastAccessTime = (long)attribute;
            return JSON.toJSONString(TOKEN_EXPIRE_TIME-(System.currentTimeMillis()-lastAccessTime));
        }else{
            return null;
        }
    }
}
