package com.manage.controller;

import com.alibaba.fastjson.JSON;
import com.manage.annotation.OptionalLog;
import com.manage.dao.Power_NoticeMapper;
import com.manage.entity.Power_Notice;
import com.manage.entity.Power_User;
import com.manage.service.cache.CacheManager;
import com.manage.service.ipml.Power_NoticeServiceImpl;
import com.manage.util.ExceptionPrintUtil;
import com.manage.util.Msg;
import com.manage.util.PageHelper;
import com.manage.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
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.HttpServletResponse;
import java.util.*;

@Controller
@RequestMapping("notice/")
public class Power_NoticeController {
    @Autowired
    private Power_NoticeServiceImpl noticeService;
    @Autowired
    private Power_NoticeMapper noticeMapper;
    @OptionalLog(module = "查看",methods = "通知管理页面")
    @RequestMapping(value = "pageUI")
    public String notice(HttpServletRequest request, Model model){
        noticeService.loadSys(request,model);
        model.addAttribute("user",request.getSession().getAttribute("CURRENT_USER"));
        CacheManager.addExcCount("noExc");
        return "/noticeDir/noticePage";
    }

    @RequestMapping(value = "selectAll",produces = "application/json; charset=utf-8")
    @ResponseBody
    public PageHelper<Power_NoticeVo> selectAll(Power_NoticeVo notice, HttpServletRequest request) {
        PageHelper<Power_NoticeVo>pageHelper = new PageHelper<Power_NoticeVo>();
        Power_User user = (Power_User)request.getSession().getAttribute("CURRENT_USER");
        List<Power_NoticeVo>power_notices = new ArrayList<Power_NoticeVo>();
        List<Power_NoticeVo> getTatal = new ArrayList<Power_NoticeVo>();
        try {
            if(user.getRoleId() == 0){
                getTatal = this.noticeMapper.getTotal(null,null,notice);
                power_notices = this.noticeMapper.selectALlByPower(null,null,notice);
            }else{
                getTatal = this.noticeMapper.getTotal(user.getRoleId(),user.getUserId(),notice);
                power_notices = this.noticeMapper.selectALlByPower(user.getRoleId(),user.getUserId(),notice);
            }
            pageHelper.setTotal(getTatal.size());
            //查询当前页实体对象
            pageHelper.setRows(power_notices);
            CacheManager.addExcCount("noExc");
            return pageHelper;
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            CacheManager.addExcCount("exc");
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping(value = "getNoticeTypeTree",produces = {"text/json;charset=UTF-8"})
    @ResponseBody
    public String getNoticeTypeTree(){
        try {
            List<PowerTree> treeList = noticeService.getNoticeTypeTree();
            CacheManager.addExcCount("noExc");
            return JSON.toJSONString(treeList);
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            CacheManager.addExcCount("exc");
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping(value = "checkTypeSysFlagOrTypeSysName")
    @ResponseBody
    public Msg checkTypeSysFlag(String noticeTypeFlag,String noticeTypeName) throws Exception{
        if(StringUtils.isNoneBlank(noticeTypeFlag) || StringUtils.isNotBlank(noticeTypeName)) {
            Power_Notice powerNotice = noticeService.checkTypeSysFlagOrTypeSysName(noticeTypeFlag, noticeTypeName);
            CacheManager.addExcCount("noExc");
            if (null != powerNotice) {
                return Msg.fail();
            } else {
                return Msg.success();
            }
        }else{
            return Msg.fail("查询出错,请联系系统管理员!");
        }
    }

    @RequestMapping(value = "update")
    @ResponseBody
    public Msg udpate(Power_Notice powerNotice,HttpServletRequest request) throws Exception{
        //保存类别
        if(StringUtils.isNotBlank(powerNotice.getNoticeTypeFlag())){
            //验证用户名
            Power_Notice typeNotice = noticeService.checkTypeSysFlagOrTypeSysName(powerNotice.getNoticeTypeFlag(), null);
            Power_Notice nameNotice = noticeService.checkTypeSysFlagOrTypeSysName(null,powerNotice.getNoticeTypeName());
            //添加类别
            if (null == powerNotice.getNoticeId()) {
                if(null != typeNotice){
                    return Msg.fail("类别标志已存在!");
                }
                if(null != nameNotice){
                    return Msg.fail("类别名称已存在!");
                }
                noticeService.update(powerNotice,request);
            } else {
                //修改类别
                if(null != typeNotice && !typeNotice.getNoticeId().equals(powerNotice.getNoticeId())){
                    return Msg.fail("类别标志已存在!");
                }
                if(null != nameNotice && !nameNotice.getNoticeId().equals(powerNotice.getNoticeId())){
                    return Msg.fail("类别名称已存在!");
                }
                noticeService.update(powerNotice,request);
            }
        }else{
           //保存通知
            noticeService.update(powerNotice,request);
        }
        CacheManager.addExcCount("noExc");
        return Msg.success();
    }

    @OptionalLog(module = "删除",methods = "通知管理",fieldName = "noticeContent",fieldName1="noticeTypeName",tableName = "power_notice")
    @RequestMapping(value = "delete")
    @ResponseBody
    public Msg delete(Integer noticeId) throws Exception{
        noticeService.delete(noticeId);
        CacheManager.addExcCount("noExc");
        return Msg.success();
    }
/************************************************通知操作***************************************************/
    @RequestMapping(value = "getUserNameListByNoticeTypeId")
    @ResponseBody
    public Msg getUserNameListByNoticeTypeId(Integer noticeTypeId, HttpServletRequest request) throws Exception{
        List<Power_UserVo> userList = noticeService.getUserNameListByNoticeTypeId(noticeTypeId, request);
        CacheManager.addExcCount("noExc");
        return Msg.success().add("userList",userList);
    }

    @RequestMapping(value = "selectNoticeByNoticeId")
    @ResponseBody
    public Msg selectNoticeByNoticeId(Integer noticeId) throws Exception{
        Power_Notice powerNotice = noticeMapper.selectByPrimaryKey(noticeId);
        CacheManager.addExcCount("noExc");
        return Msg.success().add("powerNotice",powerNotice);
    }

    @OptionalLog(module = "导出excel",methods = "通知管理")
    @RequestMapping(value = "export")
    @ResponseBody
    public void export(Power_NoticeVo powerNoticeVo,String noticeIds, HttpServletResponse response, HttpServletRequest request){
        try {
            noticeService.export(powerNoticeVo,noticeIds,response,request);
            CacheManager.addExcCount("noExc");
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            CacheManager.addExcCount("exc");
            e.printStackTrace();

        }
    }

    @RequestMapping(value = "updateNoticeReadFlag")
    @ResponseBody
    public Msg updateNoticeReadFlag(Integer noticeId) throws Exception{
        noticeService.updateNoticeReadFlag(noticeId);
        CacheManager.addExcCount("noExc");
        return Msg.success();
    }

    /**
     * @MethodName getUnReadCount
     * @Description: 根据用户获取未读通知数量
     * @Param 无
     * @Returnt Msg
     * @Author: 曾文和
     * @CreateDate: 2019-10-17
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-10-17
     * @UpdateRemark: 更新说明
     * @Version: 1.2.2
     */
    @RequestMapping("getUnReadCount")
    @ResponseBody
    public Msg getUnReadCount(HttpServletRequest request) throws Exception{
        //获取登录者信息
        Power_UserVo user = (Power_UserVo)request.getSession().getAttribute("CURRENT_USER");
        Integer userId = null;
        //系统管理员userId为null,非系统管理员传入userId
        if(user.getRoleId() != 0){
            userId = user.getRoleId();
        }
        int unReadCount = noticeService.getUnReadCount();
        CacheManager.addExcCount("noExc");
        return Msg.success().add("unReadCount",unReadCount);
    }
}
