package com.manage.service.ipml;

import com.manage.dao.Power_NoticeMapper;
import com.manage.dao.Power_Sys_DictMapper;
import com.manage.dao.Power_UserMapper;
import com.manage.dao.Power_User_DictMapper;
import com.manage.entity.Power_Notice;
import com.manage.entity.Power_Sys_Dict;
import com.manage.entity.Power_User;
import com.manage.service.webSocket.WsPool;
import com.manage.vo.PowerTree;
import com.manage.vo.Power_NoticeVo;
import com.manage.vo.Power_UserVo;
import com.manage.vo.Power_User_Dict;
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.Service;
import org.springframework.ui.Model;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ProjectName:
 * @Description:
 * @Param 传输参数
 * @Return
 * @Author: 曾文和
 * @CreateDate: 2019/8/23 16:11
 * @UpdateUser: 曾文和
 * @UpdateDate: 2019/8/23 16:11
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
@Service
public class Power_NoticeServiceImpl{
    @Value("${STR_SPLIT}")
    private String STR_SPLIT;
    @Autowired
    private Power_NoticeMapper noticeMapper;
    @Autowired
    private Power_UserMapper userMapper;
    @Autowired
    private Power_User_DictMapper userDictMapper;

    /**
     * @MethodName getNoticeTypeTree
     * @Description: 获取通知类别树
     * @Param 无
     * @Returnt Msg
     * @Author: 曾文和
     * @CreateDate: 2019-08-26
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-08-26
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    public List<Power_Notice> selectNoticeTypeList(Power_NoticeVo powerNotice){
        List<Power_Notice> power_notices = noticeMapper.selectNoticeTypeList(powerNotice);
        return power_notices;
    }

    /**
     * @MethodName getNoticeTypeTree
     * @Description: 获取通知类别树
     * @Param 无
     * @Returnt Msg
     * @Author: 曾文和
     * @CreateDate: 2019-08-26
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-08-26
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    public List<PowerTree> getNoticeTypeTree(){
        List<PowerTree> treeList = new ArrayList<>();
        PowerTree tree1 = new PowerTree();
        //第一层 类别列表
        tree1.setId(0);
        tree1.setName("通知类别列表");
        treeList.add(tree1);
        List<Power_Notice> powerNotice = noticeMapper.selectNoticeTypeList(null);
        if(null != powerNotice && !powerNotice.isEmpty()){
            for(Power_Notice notice : powerNotice){
                PowerTree tree2 = new PowerTree();
                tree2.setId(notice.getNoticeId());
                tree2.setName(notice.getNoticeTypeName());
                tree2.setNewName(notice.getNoticeTypeName());
                tree2.setParentId(0);
                tree2.setSysType(notice.getNoticeTypeFlag());
                treeList.add(tree2);
            }
        }
        return treeList;
    }

    /**
     * @MethodName checkTypeSysFlagOrTypeSysName
     * @Description: 校验类别标识或类别名称是否重复
     * @Param 无
     * @Returnt Msg
     * @Author: 曾文和
     * @CreateDate: 2019-08-23
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-08-23
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    public Power_Notice checkTypeSysFlagOrTypeSysName(String noticeTypeFlag,String noticeTypeName){
        Power_Notice powerNotice = noticeMapper.checkTypeSysFlagOrTypeSysName(noticeTypeFlag, noticeTypeName);
        return powerNotice;
    }

    /**
     * @MethodName update
     * @Description: 保存
     * @Param 无
     * @Returnt Msg
     * @Author: 曾文和
     * @CreateDate: 2019-08-23
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-08-23
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    public void update(Power_Notice powerNotice,HttpServletRequest request){
        Power_User user = (Power_User)request.getSession().getAttribute("CURRENT_USER");
        powerNotice.setEffective(1);
        if(null == powerNotice.getNoticeId()){
            //添加
            if(StringUtils.isBlank(powerNotice.getNoticeTypeFlag())){
                powerNotice.setNoticeSend(user.getUserId().toString());
                SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                powerNotice.setNoticeDate(fmt.format(new Date()));
                powerNotice.setReadFlag(0);
            }
            noticeMapper.insert(powerNotice);
            //发送通知
            sendRecive(powerNotice,user,powerNotice.getNoticeTitle(),powerNotice.getNoticeContent());
        }else{
            //修改
            noticeMapper.updateByPrimaryKeySelective(powerNotice);
            //修改发送通知 已读
            if(1 == powerNotice.getReadFlag()){
                sendRecive(powerNotice,user,"'"+powerNotice.getNoticeTitle()+"'主题修改",powerNotice.getNoticeContent());
            }
        }
    }
    private void sendRecive(Power_Notice powerNotice,Power_User user,String title,String content){
        //单个人
        if(StringUtils.isNotBlank(powerNotice.getNoticeReceive())){
            String receice = powerNotice.getNoticeReceive();
            if(!"all".equals(receice)){
                WsPool.sendMessageToAll(receice,title+STR_SPLIT+content+STR_SPLIT+powerNotice.getNoticeId());
            }else{
                //all 该系统全部，不包括自己
                //系统标识是power则该医院全部，否则该系统全部
                Integer parentId = powerNotice.getParentId();
                Power_Notice power_notice = noticeMapper.selectByPrimaryKey(parentId);
                String sysFlag = power_notice.getNoticeTypeFlag();
                //查询该用户医院id
                Integer hospitalId = null;
                if(null != user.getUserId() && user.getRoleId() != 0){
                    hospitalId = userMapper.selectHospitalIdByUserId(user.getUserId());
                }
                if("power".equals(sysFlag)){
                    if(user.getRoleId() == 0){
                        WsPool.sendMessageToAll(null,title+STR_SPLIT+content+STR_SPLIT+powerNotice.getNoticeId());
                    }else{
                        if(null != hospitalId){
                            List<Power_UserVo> userList = userMapper.selectAllBySysId(hospitalId, null);
                            if(null != userList && !userList.isEmpty()){
                                for (Power_UserVo userVo : userList){
                                    //排除自己
                                    if(!user.getUserId().equals(userVo.getUserId())){
                                        WsPool.sendMessageToAll(userVo.getUserId().toString(),title+STR_SPLIT+content+STR_SPLIT+powerNotice.getNoticeId());
                                    }
                                }
                            }
                        }
                    }
                }else{
                    //该系统全部
                    List<Power_UserVo> powerUserVos = new ArrayList<>();
                    if(user.getRoleId() == 0){
                        //根据系统标识查医院集合
                        List<Power_UserVo> users = userMapper.selectUsersBySysFlagAndHospitalId(sysFlag,null);
                        powerUserVos.addAll(users);
                    }else{
                        powerUserVos = userMapper.selectUsersBySysFlagAndHospitalId(sysFlag, hospitalId);
                    }
                    if(null != powerUserVos && !powerUserVos.isEmpty()){
                        for (Power_UserVo users:powerUserVos){
                            if(!user.getUserId().equals(users.getUserId())){
                                WsPool.sendMessageToAll(users.getUserId().toString(),title+STR_SPLIT+content+STR_SPLIT+powerNotice.getNoticeId());
                            }
                        }
                    }
                }
            }
        }
    }
    /**
     * @MethodName delete
     * @Description: 删除
     * @Param 无
     * @Returnt Msg
     * @Author: 曾文和
     * @CreateDate: 2019-08-26
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-08-26
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    public void delete(Integer noticeId){
       noticeMapper.deleteByPrimaryKey(noticeId);
    }


    /**
     * @MethodName loadSys
     * @Description: 加载权限标识集合
     * @Param 无
     * @Returnt model
     * @Author: 曾文和
     * @CreateDate: 2019-08-26
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-08-26
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    public void loadSys(HttpServletRequest request, Model model){
        List<Power_Notice> dicts = new ArrayList<>();
        Power_User user = (Power_User)request.getSession().getAttribute("CURRENT_USER");
        Integer roleId = user.getRoleId();
        if(roleId == 0){
            //roleId==0,全查
            dicts = noticeMapper.selectSysByAdmin(null,null,new Power_NoticeVo());
        }else if(roleId == -100){
            dicts = noticeMapper.selectSysByNotAdmin(user.getUserId(),null);
        }else{
            dicts = noticeMapper.selectSysByNotAdmin(user.getUserId(),0);
        }
        model.addAttribute("dicts",dicts);
    }

    public List<Power_UserVo> getUserNameListByNoticeTypeId(Integer noticeTypeId, HttpServletRequest request){
        Power_UserVo user = (Power_UserVo)request.getSession().getAttribute("CURRENT_USER");
        List<Power_UserVo> userList = new ArrayList<>();
        Power_NoticeVo noticeVo = new Power_NoticeVo();
        noticeVo.setNoticeId(noticeTypeId);
        List<Power_Notice> power_notices = noticeMapper.selectNoticeTypeList(noticeVo);
        String noticeTypeFlag = power_notices.get(0).getNoticeTypeFlag();
        //系统管理员，全查
        if(user.getRoleId() == 0){
            //权限系统，全查
            if("power".equals(noticeTypeFlag)){
                userList = userMapper.selectAllNotAdmin();
            }else{
                //非权限系统按系统标识查
                userList = userMapper.selectUserListByNoticeTypeId(noticeTypeId,null);
            }

        }else{
            Power_User_Dict power_user_dict = userDictMapper.selectDictIdByUserId(user.getUserId());
            if("power".equals(noticeTypeFlag)){
                //权限系统，全查该医院
                userList = userMapper.selectAllBySysId(power_user_dict.getDictId(),user.getUserName());
            }else{
                //非权限系统，查该医院该系统用户
                userList = userMapper.selectUserListByNoticeTypeId(noticeTypeId,power_user_dict.getDictId());
            }
        }
        return userList;
    }

    public void export(Power_NoticeVo notice, String noticeIds,HttpServletResponse response,HttpServletRequest request) throws Exception {
        List<Power_NoticeVo> noticeVos = new ArrayList<>();
        Power_User user = (Power_User)request.getSession().getAttribute("CURRENT_USER");
        List<Power_NoticeVo>power_notices = new ArrayList<Power_NoticeVo>();
        if(StringUtils.isNotBlank(noticeIds)){
            //按选中id集合查
            power_notices = noticeMapper.selectAllByIds(noticeIds);
        }else{
            //按搜索条件查
            if(user.getRoleId() == 0){
                power_notices = this.noticeMapper.selectALlByPowerWithExport(null,null,notice);
            }else{
                power_notices = this.noticeMapper.selectALlByPowerWithExport(user.getRoleId(),user.getUserId(),notice);
            }
        }

        if(null != power_notices && !power_notices.isEmpty()){
            for (Power_NoticeVo powerNotice:power_notices){
                Power_NoticeVo noticeVo1 = new Power_NoticeVo();
                if(null != powerNotice.getEffective()){
                    BeanUtils.copyProperties(powerNotice,noticeVo1);
                    if(powerNotice.getEffective() == 1){
                        noticeVo1.setEffectiveCn("是");
                    }else{
                        noticeVo1.setEffectiveCn("否");
                    }
                }
                if(null != powerNotice.getReadFlag()){
                    if(powerNotice.getReadFlag() == 1){
                        noticeVo1.setReadFlagCn("已读");
                    }else{
                        noticeVo1.setReadFlagCn("未读");
                    }
                }
                noticeVos.add(noticeVo1);
            }
        }
        String tableThNames = "类型名称,通知主题,通知内容,通知人,接收人,通知时间,已读否,有效否";
        String fieldCns = "noticeTypeName,noticeTitle,noticeContent,noticeSend,noticeDate,noticeReceive,readFlagCn,effectiveCn";
        //文件名
        String fileName = "通知列表(" + new SimpleDateFormat("yyyy_MM_dd HH_mm_ss").format(new Date()) + ").xls";
        //ExportExcelUtil
        com.manage.util.ExportExcelUtil exportExcelUtil = new com.manage.util.ExportExcelUtil();
        //导出excel的操作
        exportExcelUtil.expordExcel(tableThNames,fieldCns,noticeVos,fileName,response);
    }

    /**
     * @MethodName loadSys
     * @Description: 加载权限标识集合
     * @Param 无
     * @Returnt model
     * @Author: 曾文和
     * @CreateDate: 2019-08-26
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-08-26
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    public void updateNoticeReadFlag(Integer noticeId){
        if(null != noticeId){
            Power_Notice powerNotice = noticeMapper.selectByPrimaryKey(noticeId);
            powerNotice.setReadFlag(1);
            noticeMapper.updateByPrimaryKeySelective(powerNotice);
        }
    }

    /**
     * @MethodName getUnReadCount
     * @Description: 根据用户查询用户未读通知数量
     * @Param 无
     * @Returnt unReadCount
     * @Author: 曾文和
     * @CreateDate: 2019-10-17
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-10-17
     * @UpdateRemark: 更新说明
     * @Version: 1.2.2
     */
    public int getUnReadCount(Integer userId){
        //获取登陆者信息
        int unReadCount = noticeMapper.getUnReadCount(null);
        return unReadCount;
    }
}
