package com.manage.controller;

import com.alibaba.fastjson.JSON;
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.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

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;
    @Autowired
    private Power_UserService powerUserService;
    @Autowired
    private Power_MenuService powerMenuService;
    @Autowired
    private LogService logService;
    @Autowired
    private Power_DeptService power_deptService;

    @RequestMapping(value = "login",method = RequestMethod.GET)
    public String toLogin(){
        CacheManager.addExcCount("noExc");
        return "loginDir/login";
    }

    @RequestMapping(value = "login",method = RequestMethod.POST)
    public String login(Power_User powerUser,HttpServletResponse response, HttpServletRequest request){
        try {
            Power_UserVo user = powerUserService.findPowerUserByUserNameAndUserPwd(powerUser);
            //添加进操作日志
            Power_Log log = new Power_Log();
            if( user != null){
                //如处于登录状态，先清除缓存
                //CacheManager.removeCacheByObject(user);
                //记住
                MyCookieUtil.remember(request, response);

                //清除用户登录错误次数缓存
                CacheManager.clearOnly(powerUser.getUserName());
                //存session密码置空
                //是否记住密码功能
                MyCookieUtil.remember(request, response);
                //设置token缓存
                String date = String.valueOf(DateUtils.getDate());
                String token = Base64.encode(MD5.KL(date));


                //查询归属医院
                //科室id科室名
                ActionScopeUtils.setSessionAttribute("token",token,Integer.valueOf(String.valueOf(TOKEN_EXPIRE_TIME))/1000);

                //设置用户登录次数缓存
                SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
                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 TreeSet<>();
                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 (int i = 0; i < list.size(); i++) {
                        User_Dept_Menu deptMenu = new User_Dept_Menu();
                        String menuUrl = list.get(i).getMenuUrl();
                        if(StringUtils.isNotBlank(menuUrl)){
                            BeanUtils.copyProperties(list.get(i),deptMenu);
                            deptMenu.setMethodParent(list.get(i).getParentId());
                            menuList.add(deptMenu);
                        }
                        if(StringUtils.isNotBlank(list.get(i).getMethod())){
                            menus.add(list.get(i).getMenuUrl());
                        }
                    }
                }
                user.setMenuList(menuList);
                user.setMenus(menus);

                //设置科室
                StringBuilder power_depts = new StringBuilder();
                List<Power_Dept> power_depts1 = power_deptService.selectByPrimaryKeys(user.getDeptId());
                for(int j=0;j<power_depts1.size();j++){
                    if(j<power_depts1.size()-1){
                        power_depts.append(power_depts1.get(j).getDeptName()).append(",");
                    }else{
                        power_depts.append(power_depts1.get(j).getDeptName());
                    }
                }
                user.setRemark(power_depts.toString());

                //设置进缓存
                CacheManager.putCache(date,new Cache(date,user,TOKEN_EXPIRE_TIME));
                ActionScopeUtils.setSessionAttribute("CURRENT_USER",user,Integer.valueOf(String.valueOf(TOKEN_EXPIRE_TIME))/1000);
                return "redirect:gatewayPage";
            }else{
                //登录失败
                Integer wrongNum = 1;
                Cache cache = CacheManager.getCacheInfo(powerUser.getUserName());
                if(cache != null){
                    //缓存中错误次数
                    Integer currentNum = (Integer)cache.getValue();
                    //叠加1
                    wrongNum += currentNum;
                }
                //先清除后添加缓存
                CacheManager.clearOnly(powerUser.getUserName());
                CacheManager.putCache(powerUser.getUserName(),new Cache(powerUser.getUserName(),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 "loginDir/login";
    }
    @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();
        lastAccessTime = (long)request.getSession().getAttribute(sessionId);
        return JSON.toJSONString(TOKEN_EXPIRE_TIME-(System.currentTimeMillis()-lastAccessTime));
    }
}
