package com.jeeplus.modules.API.works.notify;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.oss.OSSClientUtil;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.utils.IdGen;
import com.jeeplus.common.utils.JPushClientUtil;
import com.jeeplus.common.utils.RequestUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.common.websocket.onchat.ChatServerPool;
import com.jeeplus.modules.oa.dao.OaNotifyDao;
import com.jeeplus.modules.oa.dao.OaNotifyRecordDao;
import com.jeeplus.modules.oa.entity.OaNotify;
import com.jeeplus.modules.oa.entity.OaNotifyRecord;
import com.jeeplus.modules.oa.service.OaNotifyService;
import com.jeeplus.modules.pushinfo.entity.Pushinfo;
import com.jeeplus.modules.pushinfo.service.PushinfoService;
import com.jeeplus.modules.serialnum.service.SerialNumTplService;
import com.jeeplus.modules.sys.dao.OfficeDao;
import com.jeeplus.modules.sys.dao.RoleDao;
import com.jeeplus.modules.sys.dao.UserDao;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.entity.Role;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.entity.Workattachment;
import com.jeeplus.modules.sys.service.SystemService;
import com.jeeplus.modules.sys.service.WorkattachmentService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.utils.ErrorCode;
import com.jeeplus.modules.workprojectnotify.entity.WorkProjectNotify;
import com.jeeplus.modules.workprojectnotify.service.WorkProjectNotifyService;
import org.java_websocket.WebSocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
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.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

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

@Controller
@RequestMapping(value="${frontPath}/notify/notify")
public class NotifyController extends BaseController {

    @Autowired
    private OaNotifyDao oaNotifyDao;

    @Autowired
    private OaNotifyRecordDao oaNotifyRecordDao;

    @Autowired
    private OaNotifyService oaNotifyService;

    @Autowired
    private UserDao userDao;

    @Autowired
    private OfficeDao officeDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private SystemService systemService;
    @Autowired
    private WorkattachmentService workattachmentService;
    @Autowired
    private PushinfoService pushinfoService;
    @Autowired
    private SerialNumTplService serialNumTplService;
    @Autowired
    private WorkProjectNotifyService workProjectNotifyService;

    /**
     * 查看用户公告信息
     * @return json数据
     */
    @RequestMapping(value = "getNotifyList")
    @ResponseBody
    public AjaxJson getNotices(HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
        Long x = System.currentTimeMillis();
        AjaxJson j = new AjaxJson();
        String userId = request.getParameter("userId");
        String readFlag = request.getParameter("readFlag");
        String pageNo = request.getParameter("pageNo");
        OaNotify oaNotify = new OaNotify();
        User user = UserUtils.get(userId);
        oaNotify.setCurrentUser(user);
        oaNotify.setStatus("1");
        oaNotify.setCompany(new Office(user.getComId()));
        oaNotify.setSelf(true);
        //管理员查看所有
        if(readFlag.equals("-1")){
            //包括草稿状态
            oaNotify.setReadFlag("");
            try {
                if (UserUtils.isManager()) {
                    oaNotify.setSelf(false);
                }
            }catch (Exception e){

            }
        }else {
            oaNotify.setReadFlag(readFlag);
        }
        //oaNotify.setCompany(UserUtils.getSelectCompany());
        Page<OaNotify> page = oaNotifyService.findMyself(new Page<OaNotify>(request, response), oaNotify);
        List<OaNotify> list=page.getList();
        if(list==null){
            j.setSuccess(false);
            j.setErrorCode(ErrorCode.code_2005);
            j.setMsg("获取列表失败");
            j.put("data", list);
        }else{
            j.put("maxNum",page.getCount());
            if(Integer.parseInt(pageNo)<=page.getTotalPage()){
                for (OaNotify o:list){
                    List<Workattachment> workattachmentList = workattachmentService.getListByAttachmentIdAndFlag(o.getId(),"79");
                    String files = "";
                    if (workattachmentList!=null && workattachmentList.size()!=0){
                        for (Workattachment workattachment : workattachmentList){
                            files += workattachment.getUrl()+",";
                        }
                        if (files.length() > 1) {
                            files = files.substring(0, files.length() - 1);
                        }
                    }
                    o.setFiles(files);
                    if (o!=null && o.getContents()!=null && !o.getContents().equals("")){
                        o.setState("1");
                    }else {
                        o.setState("2");
                    }
                    o.setContents("");
                }
                j.put("data",list);
                j.setMsg("获取列表成功");
                j.setErrorCode(ErrorCode.code_1004);
            }else{
                j.put("data", Lists.newArrayList());
                j.setMsg("获取列表成功");
                j.setErrorCode(ErrorCode.code_1004);
            }
        }
        Long y = System.currentTimeMillis();
        logger.info("----------------------x="+x);
        logger.info("getNotifyList请求时间："+(y-x)+"毫秒！");
        logger.info("----------------------y="+y);
        return j;
    }

    /**
     * 查看公告详情
     * @return  json数据
     */
    @RequestMapping(value = "getNotifyById", method=RequestMethod.GET)
    @ResponseBody
    public AjaxJson getNotifyById(HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
        AjaxJson j = new AjaxJson();
        String notifyId = request.getParameter("notifyId");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Map<String, Object> map = Maps.newHashMap();
        OaNotify oaNotify = oaNotifyDao.get(notifyId);
        if(oaNotify!=null){
            User user = userDao.get(oaNotify.getCreateBy());
            if(user!=null){
                map.put("userName", user.getName());
                map.put("photo", user.getPhoto());
            }else{
                map.put("userName", "");
                map.put("photo", "");
            }
            map.put("title", oaNotify.getTitle());

            String contents = "";
            if(oaNotify.getContents()!=null && oaNotify.getContents().contains("img")){
                String[] arr = oaNotify.getContents().split("<img alt=\"\" src=\"");
                for(int i=0;i<arr.length;i++){
                    if(i==0){
                        contents += arr[0];
                    }else {
                        contents += "<img alt=\"\" src=\""+request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+arr[i];
                    }

                }
                oaNotify.setContents(contents);
                map.put("contents", contents);
            }else {
                map.put("contents", oaNotify.getContents());
            }

            String type = oaNotify.getType();
            if(StringUtils.isNotBlank(type)){
                if("1".equals(type)){type = "会议通告";}
                if("2".equals(type)){type = "奖惩通告";}
                if("3".equals(type)){type = "活动通告";}
            }else{
                type = "";
            }
            map.put("type",type);
            List<Workattachment> workattachmentList = workattachmentService.getListByAttachmentIdAndFlag(oaNotify.getId(),"79");
            String files = "";
            if (workattachmentList!=null && workattachmentList.size()!=0){
                for (Workattachment workattachment : workattachmentList){
                    files += workattachment.getUrl()+",";
                }
                if (files.length() > 1) {
                    files = files.substring(0, files.length() - 1);
                }
            }
            map.put("files", files);
            //map.put("files", oaNotify.getFiles());
            map.put("content", oaNotify.getContent());
            map.put("createDate",sdf.format(oaNotify.getCreateDate()));
            map.put("readNum", oaNotify.getReadNum());
            map.put("unReadNum", oaNotify.getUnReadNum());
            map.put("companyId", oaNotify.getCompany().getId());
            map.put("startDate", oaNotify.getStartDate());
            map.put("endDate", oaNotify.getEndDate());
            map.put("number", oaNotify.getNumber());

            //记录已读
            if (StringUtils.isNotBlank(oaNotify.getId())){
                oaNotifyService.updateReadFlag(oaNotify);
            }
        }
        if( map==null){
            j.setSuccess(false);
            j.setMsg("获取公告失败");
            j.setErrorCode(ErrorCode.code_2005);
            j.put("data",map);
        }
        else{
            j.put("data", map);
            j.setMsg("获取公告成功");
            j.setErrorCode(ErrorCode.code_1004);
        }

        return j;
    }



    /**
     * 查看用户
     * @return  json数据
     */
    @RequestMapping(value = "getUserByOaNotifyId", method=RequestMethod.GET)
    @ResponseBody
    public AjaxJson getUserByOaNotifyId(HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
        AjaxJson j = new AjaxJson();
        String notifyId = request.getParameter("notifyId");
        String readFlag = request.getParameter("readFlag");
        OaNotifyRecord oaNotifyRecord = new OaNotifyRecord();
        OaNotify oaNotify= new OaNotify();
        oaNotify.setId(notifyId);
        oaNotifyRecord.setOaNotify(oaNotify);
        oaNotifyRecord.setReadFlag(readFlag);
        List<Map<String, Object>> mapList = Lists.newArrayList();
        List<OaNotifyRecord> list =	oaNotifyRecordDao.findUserList(oaNotifyRecord);
        for (int i = 0; i < list.size(); i++) {
            OaNotifyRecord o=list.get(i);
            User user = userDao.get(o.getUser());
            if(user!=null){
                Map<String, Object> map = Maps.newHashMap();
                if(user.getName()==null){
                    map.put("userName", "");
                }else{
                    map.put("userName", user.getName());
                }
                if(user.getPhoto()==null){
                    map.put("photo", "");
                }else{
                    map.put("photo", user.getPhoto());
                }
                mapList.add(map);
            }
        }
        if( mapList==null){
            j.setSuccess(false);
            j.setMsg("获取用户失败");
            j.setErrorCode(ErrorCode.code_2005);
            j.put("data",mapList);
        }
        else{
            j.put("data", mapList);
            j.setMsg("获取用户成功");
            j.setErrorCode(ErrorCode.code_1004);
        }

        return j;
    }



    /**
     * 添加公告
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "addNotify", method=RequestMethod.POST)
    @ResponseBody
    public AjaxJson addNotify(HttpServletRequest request, HttpServletResponse response)throws Exception  {
        AjaxJson j = new AjaxJson();
        try {
            HashMap<String, String> requestMap = findRequestMap(request);
            String title = URLDecoder.decode(requestMap.get("title")==null?"":requestMap.get("title"), "UTF-8");
            String type = URLDecoder.decode(requestMap.get("type")==null?"":requestMap.get("type"), "UTF-8");
            String content = URLDecoder.decode(requestMap.get("content")==null?"":requestMap.get("content"), "UTF-8");
            String ids = URLDecoder.decode(requestMap.get("ids")==null?"":requestMap.get("ids"), "UTF-8");
            String files = URLDecoder.decode(requestMap.get("files")==null?"":requestMap.get("files"), "UTF-8");
            String officeIds = URLDecoder.decode(requestMap.get("officeIds")==null?"":requestMap.get("officeIds"), "UTF-8");
            String userId = URLDecoder.decode(requestMap.get("userId")==null?"":requestMap.get("userId"), "UTF-8");
            String startDate = URLDecoder.decode(requestMap.get("startDate")==null?"":requestMap.get("startDate"), "UTF-8");
            String endDate = URLDecoder.decode(requestMap.get("endDate")==null?"":requestMap.get("endDate"), "UTF-8");
            Office company  = UserUtils.getSelectCompany();
            OaNotify oaNotify = new OaNotify();
            Set<String> set = new HashSet<String>();
            List<OaNotifyRecord> oaNotifyRecordOfficeList = Lists.newArrayList();
            if(officeIds !=null && !officeIds.equals("")){
                String [] offices = officeIds.split(",");
                for (int i = 0; i < offices.length; i++) {
                    Office office = officeDao.get(offices[i]);
                    List<User> users = new ArrayList<>();
                    if ("2".equals(office.getType())){
                        OaNotifyRecord entity = new OaNotifyRecord();
                        entity.setId(IdGen.uuid());
                        entity.setOaNotify(oaNotify);
                        entity.setOfficeId(offices[i]);
                        oaNotifyRecordOfficeList.add(entity);
                        users = systemService.findUserByOfficeId(offices[i]);
                    }else {
                        users = systemService.findUserByOffices(office,company);
                        List<Office> officeList = officeDao.findAllListByParentIds(office);
                        for (Office o:officeList){
                            if ("2".equals(o.getType())){
                                OaNotifyRecord entity = new OaNotifyRecord();
                                entity.setId(IdGen.uuid());
                                entity.setOaNotify(oaNotify);
                                entity.setOfficeId(offices[i]);
                                oaNotifyRecordOfficeList.add(entity);
                            }
                        }
                    }
                    for (User user:users){
                        set.add(user.getId());
                    }
                }
                oaNotify.setOaNotifyRecordOfficeList(oaNotifyRecordOfficeList);
            }
            if(ids !=null && !ids.equals("")){
                String [] users = ids.split(",");
                for (int i = 0; i < users.length; i++) {
                    //userList.add(users[i]);
                    set.add(users[i]);
                }
            }
            String recordIds = "";
            if (set!=null && set.size()!=0){
                List aliases = new ArrayList();
                for (String id :set){
                    recordIds += id +",";
                    aliases.add(id);
                }
                if (StringUtils.isNotBlank(recordIds)){
                    recordIds = recordIds.substring(0,recordIds.length()-1);
                }
                //oaNotify.setCompany(UserUtils.getSelectCompany());
                SimpleDateFormat sdfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                try {
                    oaNotify.setStartDate(sdfs.parse(startDate));
                    oaNotify.setEndDate(sdfs.parse(endDate));
                }catch (Exception e){
                    j.put("notifyId", oaNotify.getId());
                    j.setErrorCode(ErrorCode.code_2002);
                    j.setMsg("发布公告失败，开始时间/结束时间格式异常");
                    return j;
                }
                oaNotify.setTitle(title);
                oaNotify.setType(type);
                oaNotify.setContent(content);
                oaNotify.setFiles(files);
                oaNotify.setCompany(company);
                oaNotify.setOffice(UserUtils.getSelectOffice());
                oaNotify.setStatus("1");
                oaNotify.setOaNotifyRecordIds(recordIds);
                User user=UserUtils.get(userId);
                oaNotify.setCreateBy(user);
                oaNotify.setUpdateBy(user);
//      oaNotify.preInsert();//自动生成ID 、createDate、createBy(createBy为登录用户、接口下该值为空)
                oaNotify.setNumber(serialNumTplService.genSerialNum(UserUtils.getSelectCompany(), "17"));
                oaNotifyService.save(oaNotify);


                // 更新发送接受人记录
                oaNotifyRecordDao.deleteByOaNotifyId(oaNotify.getId());
                if (oaNotify.getOaNotifyRecordList().size() > 0){
                    oaNotifyRecordDao.insertAll(oaNotify.getOaNotifyRecordList());
                }
                for (String uid:set){
                    UserUtils.pushIm(uid,("公告消息 "+title));
                   /* List<WebSocket> toUserConns = ChatServerPool.getWebSocketByUser(uid);
                    for (WebSocket toUserConn : toUserConns) {
                        String message = "{\"to\":\""+uid+"\"," +
                                "\"msg\":\"公告消息 "+title+"\"," +
                                "\"useType\":\"sys\"}";
                        ChatServerPool.sendMessageToUser(toUserConn, message);//同时向本人发送消息
                    }*/
                }
                Map extras = new HashMap();
                extras.put("type", "2001");
                extras.put("id", oaNotify.getId());
                //发布状态发推送
                if(StringUtils.isNotBlank(oaNotify.getStatus()) && "1".equals(oaNotify.getStatus())){

                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    String date = sdf.format(new Date());
                    Pushinfo pushinfo = new Pushinfo();
                    pushinfo.setCompanyId(UserUtils.getSelectCompany().getId());
                    pushinfo.setMobile("ios,android");
                    pushinfo.setCurrentUser(UserUtils.getUser());
                    pushinfo.setRemarks(content);
                    pushinfo.setUserId(UserUtils.getUser().getId());
                    pushinfo.setType("2001");
                    pushinfo.setPushId(oaNotify.getId());
                    pushinfo.setTitle("公告");
                    String status = oaNotify.getUpdateBy().getName() +"  "+date;
                    pushinfo.setStatus(status);
                    pushinfo.setContent(oaNotify.getTitle());
                    pushinfo.setPushUserId(ids);
                    pushinfo.setParentType("singleCompanyNews");
                    if (oaNotify.getFiles()!=null &&oaNotify.getFiles().length()>0){
                        pushinfo.setStatus(oaNotify.getFiles());
                    }
                    pushinfoService.save(pushinfo);

                    boolean b = JPushClientUtil.sendNotificationToAliases(oaNotify.getTitle(), content, extras, aliases);
                    j.put("notifyId", oaNotify.getId());
                    j.setErrorCode(ErrorCode.code_1004);
                    j.setMsg("发布公告成功");
                }
            }else {
                j.put("notifyId", oaNotify.getId());
                j.setErrorCode(ErrorCode.code_1004);
                j.setMsg("发布公告失败，发送人不能为空");
            }

        }catch (Exception e){
            j.put("notifyId", "");
            j.setSuccess(false);
            j.setErrorCode(ErrorCode.code_1004);
            j.setMsg("发布公告失败");
        }
        return j;
    }



    /**
     * 查看部门下的员工
     * @param request
     * @param response
     * @param redirectAttributes
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getUserByOffice", method=RequestMethod.GET)
    public AjaxJson  getUserTreeData(HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
        AjaxJson j = new AjaxJson();
        String officeId = request.getParameter("officeId");
        List<Map<String, Object>> mapList = Lists.newArrayList();
        List<User> list = systemService.findUserByOfficeId(officeId);
        Office office = officeDao.get(officeId);
        for (int i = 0; i < list.size(); i++) {
            User u = list.get(i);
            Map<String, Object> map = Maps.newHashMap();
            map.put("id", u.getId());
            map.put("name",u.getName());
            map.put("photo", u.getPhoto());
            if(office!=null){
                map.put("offcieName", office.getName());
            }
            mapList.add(map);
        }
        if(mapList==null){
            j.setSuccess(false);
            j.setMsg("获取部门人员失败");
            j.setErrorCode(ErrorCode.code_2005);
            j.put("data", mapList);
        }else{
            j.setMsg("获取部门人员信息成功");
            j.put("data", mapList);
            j.setErrorCode(ErrorCode.code_1004);
        }
        return j;
    }



    /**
     * 查看公司下的部门
     * @return
     */
    @RequestMapping(value = "getOffice", method=RequestMethod.GET)
    @ResponseBody
    public AjaxJson getOffice(HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
        AjaxJson j = new AjaxJson();
        String userId = request.getParameter("userId");
        String companyId = request.getParameter("companyId");
        List<Map<String,Object>> mapList = Lists.newArrayList();
        Role role1 = new Role();
        User user = UserUtils.get(userId);
        role1.setUser(user);
        List<Role> roleList=roleDao.findList(role1);
        Office comp =null;
        for (Role role : roleList) {
            if(role.getId() != null && role.getCompany() != null &&companyId.equals(role.getCompany().getId())){
                comp=officeDao.get(companyId);
            }
        }
        if(comp!=null){
            Map<String,Object> map = Maps.newHashMap();
            map.put("companyId",comp.getId());
            map.put("companyName", comp.getName());
            List<Map<String, Object>> mapList1 = Lists.newArrayList();
            Office office = new Office();
            office.setParentIds(comp.getId());
            List<Office> list = officeDao.findByParentIdsLike(office);
            for (int i = 0; i < list.size(); i++) {
                Office e = list.get(i);
                Map<String, Object> map1 = Maps.newHashMap();
                map1.put("officeId", e.getId());
                map1.put("officeName", e.getName());
                mapList1.add(map1);
            }
            map.put("下属部门", mapList1);

            mapList.add(map);
        }


		/*List<Map<String, Object>> mapList = Lists.newArrayList();
		List<Office> list = officeService.findList(false);
		for (int i=0; i<list.size(); i++){
			Office e = list.get(i);
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getId());
				map.put("pId", e.getParentId());
				map.put("pIds", e.getParentIds());
				map.put("name", e.getName());
				mapList.add(map);

		}*/
        if(mapList==null){
            j.setSuccess(false);
            j.setErrorCode(ErrorCode.code_2005);
            j.setMsg("获取公司机构失败");
            j.put("data",mapList);

        }else{
            j.setMsg("获取公司机构成功");
            j.put("data",mapList);
            j.setErrorCode(ErrorCode.code_1004);
        }
        return j;
    }
    /**
     * 保存公告附件
     */
    @Transactional
    @ResponseBody
    @RequestMapping(value = "saveFile",method=RequestMethod.POST)
    public AjaxJson saveFile(HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) throws Exception{
        AjaxJson j=new AjaxJson();
        try {
            HashMap<String, String> requestMap = findRequestMap(request);
            String notifyId = URLDecoder.decode(requestMap.get("id")==null?"":requestMap.get("id"), "UTF-8");
            String urls = URLDecoder.decode(requestMap.get("urls")==null?"":requestMap.get("urls"), "UTF-8");
            String flag = URLDecoder.decode(requestMap.get("type")==null?"":requestMap.get("type"), "UTF-8");
            User user = UserUtils.getUser();
            Office company = UserUtils.getSelectCompany();
            Calendar cal = Calendar.getInstance();
            cal.setTime(new Date());
            if (StringUtils.isNotBlank(urls)){
                j.setMsg("上传成功！");
                j.setErrorCode(ErrorCode.code_1004);
                for (String url:urls.split(",")){
                    String[] arr = url.split("/");
                    String fileName = arr[arr.length-1];
                    String[] typeArr = fileName.split("\\.");
                    String type = typeArr[typeArr.length-1];
                    Workattachment workattachment = new Workattachment();
                    workattachment.setAttachmentUser(user.getId());
                    workattachment.setUrl("http://cdn.gangwaninfo.com/"+url);
                    workattachment.setAttachmentName(fileName);
                    workattachment.setCompanyId(company.getId());
                    workattachment.setAttachmentFlag(flag);
                    workattachment.setType(type);
                    workattachment.setAttachmentId(notifyId);
                    workattachment.setId(IdGen.uuid());
                    if (org.apache.commons.lang3.StringUtils.isNotBlank(user.getId())){
                        workattachment.setUpdateBy(user);
                        workattachment.setCreateBy(user);
                    }
                    cal.add(Calendar.SECOND, 1);
                    workattachment.setCreateDate( cal.getTime());
                    workattachment.setUpdateDate( cal.getTime());
                    workattachmentService.insert(workattachment);
                }
            }else {
                j.setSuccess(false);
                j.setMsg("上传失败！");
                j.setErrorCode(ErrorCode.code_2004);
            }
        }catch (Exception e){
            j.setSuccess(false);
            j.setMsg("上传失败！");
            j.setErrorCode(ErrorCode.code_2004);
        }finally {
            return j;
        }
    }

    /**
     * 保存公告附件
     */
    @Transactional
    @ResponseBody
    @RequestMapping(value = "saveNotifyFile",method=RequestMethod.POST)
    public AjaxJson saveUserPhoto(MultipartHttpServletRequest multiRequest,HttpServletRequest servletRequest) throws Exception{
        AjaxJson j=new AjaxJson();
        try {
            String notifyId = multiRequest.getParameter("notifyId");
            OaNotify oaNotify =  oaNotifyService.get(notifyId);
            OSSClientUtil ossUtil =new OSSClientUtil();

            Iterator<String> fileNames = multiRequest.getFileNames();
            String thisFiles = oaNotify.getFiles();
            String filePaths= "";
            System.out.println("-----------开始------------------");
            while(fileNames.hasNext()){

                //取得上传文件
                MultipartFile file = multiRequest.getFile(fileNames.next());
                if(file != null){
                    //取得当前上传文件的文件名称
                    //String filePath= ossUtil.uploadFile2OSS(file, "notify");
                    OSSClientUtil ossClientUtil = new OSSClientUtil();
                    String filePath= oaNotifyService.uploadFile(ossClientUtil,file,oaNotify,"79");
                    filePaths = filePath;
                }
            }
            /*if(thisFiles==null || thisFiles.equals("")){
                if(filePaths.contains(",")){
                    oaNotify.setFiles(filePaths.substring(1, filePaths.length() - 1));
                }else {
                    oaNotify.setFiles(filePaths);
                }
            }else{
                filePaths = thisFiles+","+filePaths;
                oaNotify.setFiles(filePaths);
            }
            logger.info(","+oaNotify.getFiles());
            oaNotifyService.saveNotifyFile(oaNotify);*/
            System.out.println("-----------结束------------------");
            j.put("filePath",filePaths);
            j.setSuccess(true);
            j.setErrorCode(ErrorCode.code_1004);
            j.setMsg("上传成功！");
        }catch (Exception e){
            j.put("filePath","");
            j.setSuccess(false);
            j.setMsg("上传失败！");
            j.setErrorCode(ErrorCode.code_2004);
        }finally {
            return j;
        }
    }


    /**
     * 考勤规则权限密码验证 
     * @param
     * @param request
     * @param response
     * @param redirectAttributes
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "passwordAuth", method=RequestMethod.POST)
    public AjaxJson  passwordAuth(HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
        AjaxJson j = new AjaxJson();
        HashMap<String, String> requestMap = RequestUtils.findRequestMap(request);
        String password = requestMap.get("password");
        String userId =  requestMap.get("userId");
        if(userId == null || userId.equals("") ){
            userId = UserUtils.getUser().getId();
        }else{
            if(!userId.equals(UserUtils.getUser().getId())){
                j.setSuccess(false);
                j.setMsg("用户名错误");
                j.setErrorCode(ErrorCode.code_2003);
                return j;
            }
        }
        System.out.println("userId="+userId);
        User user = systemService.getUser(userId);
        boolean status = systemService.validatePassword(password,user.getPassword());
        if(status){
            j.setSuccess(status);
            j.setMsg("考勤规则权限密码验证成功");
            j.setErrorCode(ErrorCode.code_1004);
        }else{
            j.setSuccess(status);
            j.setMsg("考勤规则权限密码验证失败");
            j.setErrorCode(ErrorCode.code_1012);
        }
        return j;
    }

    /**
     * 查看已读未读用户
     * @return  json数据
     */
    @RequestMapping(value = "getNotifyRecord", method=RequestMethod.GET)
    @ResponseBody
    public AjaxJson getNotifyRecord(HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
        AjaxJson j = new AjaxJson();

        String notifyId = request.getParameter("notifyId");
        OaNotifyRecord oaNotifyRecord = new OaNotifyRecord();
        oaNotifyRecord.setOaNotify(new OaNotify(notifyId));
        oaNotifyRecord.setReadFlag("1");
        List<OaNotifyRecord> readList = oaNotifyRecordDao.findList(oaNotifyRecord);
        OaNotifyRecord o = new OaNotifyRecord();
        o.setOaNotify(new OaNotify(notifyId));
        o.setReadFlag("0");
        List<OaNotifyRecord> noReadList = oaNotifyRecordDao.findList(o);
        List<Map<String, Object>> mapList1 = Lists.newArrayList();
        List<Map<String, Object>> mapList2 = Lists.newArrayList();
        Map<String, Object> totalMap = new HashMap<String, Object>();
        if (readList != null && readList.size() != 0) {
            for (OaNotifyRecord onr : readList) {
                Map<String, Object> map = Maps.newHashMap();
                map.put("userId", onr.getUser() == null ? "" : onr.getUser().getId());
                map.put("photo", onr.getUser() == null ? "" : onr.getUser().getPhoto());
                map.put("userName", onr.getUser() == null ? "" : onr.getUser().getName());
                mapList1.add(map);
            }
        }
        if (noReadList != null && noReadList.size() != 0) {
            for (OaNotifyRecord onr : noReadList) {
                Map<String, Object> map = Maps.newHashMap();
                map.put("userId", onr.getUser() == null ? "" : onr.getUser().getId());
                map.put("photo", onr.getUser() == null ? "" : onr.getUser().getPhoto());
                map.put("userName", onr.getUser() == null ? "" : onr.getUser().getName());
                mapList2.add(map);
            }
        }
        totalMap.put("read", mapList1);
        totalMap.put("unread", mapList2);

        j.put("data", totalMap);
        j.setMsg("获取公告读取用户成功");
        j.setSuccess(true);
        j.setErrorCode(ErrorCode.code_1004);
        return j;
    }

    /**
     * 删除公告详情
     * @return  json数据
     */
    @RequestMapping(value = "deleteNotifyById", method=RequestMethod.GET)
    @ResponseBody
    public AjaxJson deleteNotifyById(HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
        AjaxJson j = new AjaxJson();
        String notifyId = request.getParameter("notifyId");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        OaNotify oaNotify = oaNotifyDao.get(notifyId);
        if(notifyId!=null){
            WorkProjectNotify notify = new WorkProjectNotify();
            notify.setNotifyId(oaNotify.getId());
            //workProjectNotifyService.readByNotifyId(notify);
            pushinfoService.updateDelflagByPushId(notify.getId(),"1");
            //oaNotifyDao.delete(oaNotify);
            oaNotifyRecordDao.deleteByOaNotifyId(notifyId);
            oaNotify.setRemarks("关闭");
            oaNotifyDao.saveRemarks(oaNotify);
            j.put("data", "");
            j.setMsg("删除公告成功");
            j.setErrorCode(ErrorCode.code_1004);
        }else{
            j.setSuccess(false);
            j.setMsg("获取公告失败");
            j.setErrorCode(ErrorCode.code_2005);
            j.put("data","");
        }

        return j;
    }

}
