package com.manage.controller;

import com.manage.dao.Power_Sys_DictMapper;
import com.manage.encrypt.Base64;
import com.manage.encrypt.MD5;
import com.manage.entity.Power_Log;
import com.manage.entity.Power_Menu;
import com.manage.entity.Power_Sys_Dict;
import com.manage.service.LogService;
import com.manage.service.Power_MenuService;
import com.manage.service.cache.Cache;
import com.manage.service.cache.CacheManager;
import com.manage.service.ipml.PageServiceImpl;
import com.manage.service.ipml.Power_NoticeServiceImpl;
import com.manage.util.Msg;
import com.manage.vo.Echarts;
import com.manage.vo.Power_UserVo;
import com.manage.vo.User_Dept_Menu;
import org.apache.commons.lang3.StringUtils;
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.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * 跳转页面 不做业务处理
 * @Author: ljx
 * @Date: 2019/4/16 9:26
 * @Version 1.0
 */
@Controller
public class PageController {
    @Value("${EMRMEDICALRECORD_URLHEAD}")
    private String EMRMEDICALRECORD_URLHEAD;
    @Value("${EMRRECORD_URLHEAD}")
    private String EMRRECORD_URLHEAD;
    @Value("${EMRAPPLYCOPY_URLHEAD}")
    private String EMRAPPLYCOPY_URLHEAD;
    @Value("${EMRFILES_URLHEAD}")
    private String EMRFILES_URLHEAD;

    @Value("${WEBSOCKET_URLHEAD}")
    private String WEBSOCKET_URLHEAD;
    @Value("${STR_SPLIT}")
    private String STR_SPLIT;
    @Autowired
    private Power_NoticeServiceImpl powerNoticeService;
    @Autowired
    private PageServiceImpl pageService;
    @Autowired
    private Power_Sys_DictMapper sysDictMapper;
    @Autowired
    private LogService logService;
    @Value("${TOKEN_EXPIRE_TIME}")
    private long TOKEN_EXPIRE_TIME;
    @Autowired
    private Power_MenuService powerMenuService;
    @RequestMapping(value = "logout")
    public String logout(HttpSession session,String token){
        try {
            session.invalidate();
            token = MD5.JM(Base64.decode(token));
            Cache cache = CacheManager.getCacheInfo(token);
            if(cache != null){
                //CacheManager.removeCacheByObject((Power_UserVo)cache.getValue());
            }
            CacheManager.addExcCount("noExc");
        }catch (Exception e){
            e.printStackTrace();
            CacheManager.addExcCount("exc");
        }
        return "redirect:login";
    }
    @RequestMapping(value = "index")
    public String index(Model model,HttpServletRequest request){
        Power_UserVo user =(Power_UserVo)request.getSession().getAttribute("CURRENT_USER");
        model.addAttribute("WEBSOCKET_URLHEAD",WEBSOCKET_URLHEAD);
        model.addAttribute("STR_SPLIT",STR_SPLIT);
        CacheManager.addExcCount("noExc");
        Set<String> menus = new TreeSet<>();
        List<Power_Menu> list = null;
        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++) {
                if(StringUtils.isNotBlank(list.get(i).getMethod())){
                    menus.add(list.get(i).getMenuUrl());
                }
            }
        }
        user.setMenus(menus);
        return "/loginDir/index";
    }

    @RequestMapping(value = "gatewayPage")
    public String register(Model model, HttpServletRequest request,Integer noticeId){
        model.addAttribute("EMRMEDICALRECORD_URLHEAD",EMRMEDICALRECORD_URLHEAD);

        model.addAttribute("EMRRECORD_URLHEAD",EMRRECORD_URLHEAD);

        model.addAttribute("EMRAPPLYCOPY_URLHEAD",EMRAPPLYCOPY_URLHEAD);

        model.addAttribute("EMRFILES_URLHEAD",EMRFILES_URLHEAD);

        model.addAttribute("WEBSOCKET_URLHEAD",WEBSOCKET_URLHEAD);
        model.addAttribute("STR_SPLIT",STR_SPLIT);
        model.addAttribute("flag",noticeId);
        //登录成功
        //插入成功日志
        Power_UserVo powerUser = (Power_UserVo)request.getSession().getAttribute("CURRENT_USER");
        Power_Log log = new Power_Log();
        log.setLogTitle("登录");
        log.setLogContent("用户登录成功");
        log.setCreater(powerUser.getUserName());
        logService.insert(log);
        //修改该通知为已读
        if(null != noticeId && noticeId != -1){
            try {
                powerNoticeService.updateNoticeReadFlag(noticeId);
                CacheManager.addExcCount("noExc");
            }catch (Exception e){
                e.printStackTrace();
                CacheManager.addExcCount("exc");
            }
        }
      //查询当前用户
        Power_UserVo user = (Power_UserVo)request.getSession().getAttribute("CURRENT_USER");
        //查询系统权限
        List<Power_Sys_Dict> sysList = new ArrayList<>();
        if(user.getRoleId() == 0){
            sysList = sysDictMapper.selectSysFlagsByUserId(null,null);
        }else{
            sysList = sysDictMapper.selectSysFlagsByUserId(user.getUserId(),user.getRoleId());
        }
        int power = 0;
        int emr_medical_record = 0;
        int emr_record = 0;
        int emr_apply_copy = 0;
        int emr_files = 0;
        int power1 = 0;
        int emr_medical_record1 = 0;
        int emr_record1 = 0;
        int emr_apply_copy1 = 0;
        int emr_files1 = 0;
        if(null != sysList && !sysList.isEmpty()){
            //获取权限菜单
            List<User_Dept_Menu> menuList = powerUser.getMenuList();
            if(null != menuList && !menuList.isEmpty()) {
                for (User_Dept_Menu menu : menuList) {
                    String sysFlag = menu.getSysFlag();
                    if (StringUtils.isNotBlank(sysFlag)) {
                        if ("power".equals(sysFlag)) {
                            power1 = 1;
                            continue;
                        }
                        if ("emr_medical_record".equals(sysFlag)) {
                            emr_medical_record1 = 1;
                            continue;
                        }
                        if ("emr_record".equals(sysFlag)) {
                            emr_record1 = 1;
                            continue;
                        }
                        if ("emr_apply_copy".equals(sysFlag)) {
                            emr_apply_copy1 = 1;
                            continue;
                        }
                        if ("emr_files".equals(sysFlag)) {
                            emr_files1 = 1;
                            continue;
                        }
                    }
                }
            }
            for (int i = 0; i < sysList.size(); i++) {
                String sysFlag = sysList.get(i).getSysFlag();
                if(StringUtils.isNotBlank(sysFlag)){
                    if("power".equals(sysFlag)){
                        power = 1;
                        continue;
                    }
                    if("emr_medical_record".equals(sysFlag)){
                        emr_medical_record = 1;
                        continue;
                    }
                    if("emr_record".equals(sysFlag)){
                        emr_record = 1;
                        continue;
                    }
                    if("emr_apply_copy".equals(sysFlag)){
                        emr_apply_copy = 1;
                        continue;
                    }
                    if("emr_files".equals(sysFlag)){
                        emr_files = 1;
                        continue;
                    }
                }
            }
        }
        if(power == 1 && power1 == 1){
            power = 1;
        }else{
            power = 0;
        }
        if(emr_medical_record == 1 && emr_medical_record1 == 1){
            emr_medical_record = 1;
        }else{
            emr_medical_record = 0;
        }
        if(emr_record == 1 && emr_record1 == 1){
            emr_record = 1;
        }else{
            emr_record = 0;
        }
        if(emr_apply_copy == 1 && emr_apply_copy1 == 1){
            emr_apply_copy = 1;
        }else{
            emr_apply_copy = 0;
        }
        if(emr_files == 1 && emr_files1 == 1){
            emr_files = 1;
        }else{
            emr_files = 0;
        }
        model.addAttribute("power",power);
        model.addAttribute("emr_medical_record",emr_medical_record);
        model.addAttribute("emr_record",emr_record);
        model.addAttribute("emr_apply_copy",emr_apply_copy);
        model.addAttribute("emr_files",emr_files);
        return "/gatewayDir/gatewayIndex";
    }
    @RequestMapping(value = "main")
    public String main(){
        CacheManager.addExcCount("noExc");
        return "main";
    }

    /*@RequestMapping("getEcharts1")
    @ResponseBody
    public Msg getEcharts1(){
        List<Echarts> list = new ArrayList<>();
        try {
            //无异常
            Integer noExc = CacheManager.getExcCount("noExc");
            String valueArr1[] = {noExc.toString()};
            Echarts echarts1 = new Echarts("无异常",null,valueArr1);

            //异常
            Integer exc = CacheManager.getExcCount("exc");
            if(null == exc){
                exc = 0;
            }
            String valueArr2[] = {exc.toString()};
            Echarts echarts2 = new Echarts("异常",null,valueArr2);

            //锁定
            Integer effectiveCount = pageService.selectEffectiveCount();
            if(null == effectiveCount){
                effectiveCount = 0;
            }
            String valueArr3[] = {effectiveCount.toString()};
            Echarts echarts3 = new Echarts("锁定",null,valueArr3);

            list.add(echarts1);
            list.add(echarts2);
            list.add(echarts3);
        }catch (Exception e){
            e.printStackTrace();
            return Msg.fail(e.getMessage());
        }
        return Msg.success().add("list",list);
    }

    @RequestMapping("getEcharts2")
    @ResponseBody
    public Msg getEcharts2(){
        try {
            Map<String, List> map = pageService.getEcharts2();
            return Msg.success().add("list",map);
        }catch (Exception e){
            e.printStackTrace();
            return Msg.fail(e.getMessage());
        }
    }

    @RequestMapping("getEcharts3")
    @ResponseBody
    public Msg getEcharts3(){
        try {
            Map<String, List> map = pageService.getEcharts3();
            return Msg.success().add("list",map);
        }catch (Exception e){
            e.printStackTrace();
            return Msg.fail(e.getMessage());
        }
    }*/

    @RequestMapping("getEcharts4")
    @ResponseBody
    public Msg getEcharts4(){
        try {
            int cpuCount = pageService.getEcharts4();
            return Msg.success().add("list",cpuCount);
        }catch (Exception e){
            e.printStackTrace();
            return Msg.fail(e.getMessage());
        }
    }

    //返回40
    @RequestMapping("getEcharts5")
    @ResponseBody
    public Msg getEcharts5(){
        long temperature = 0;
        try {
            temperature = pageService.getEcharts5();
            return Msg.success().add("temperature",temperature);
        }catch (Exception e){
            e.printStackTrace();
            return Msg.success().add("temperature",temperature);
        }
    }

    //返回[8,7.8,5.3]
    @RequestMapping("getEcharts6")
    @ResponseBody
    public Msg getEcharts6(){
        try {
            List<String> list = pageService.getEcharts6();
            return Msg.success().add("list",list);
        }catch (Exception e){
            e.printStackTrace();
            return Msg.fail(e.getMessage());
        }
    }
}
