package com.dgtis.dorm.manager.wx.web;

import com.dgtis.dorm.manager.db.domain.*;
import com.dgtis.dorm.manager.db.service.*;
import com.dgtis.dorm.manager.db.util.ResponseUtil;
import com.dgtis.dorm.manager.wx.annotation.LoginUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

@RestController
@RequestMapping("/wx/news")
public class NewsController {

    @Autowired
    private NewsService newsService;
    @Autowired
    private AdminService adminService;
//    @Autowired
//    private ActivityUserService activityUserService;
    @Autowired
    private NewsOrganizeService newsOrganizeService;
    @Autowired
    private UserService userService;
    @Autowired
    private NewsCommentService newsCommentService;
    @Autowired
    private NewsZanService newsZanService;
//    @Autowired
//    private AlumniOrganizeUserService alumniOrganizeUserService;

    /**
     * 获取 交互内容列表
     * @return
     */
    @PostMapping("list")
    public Object list(@LoginUser Integer adminId, @RequestBody NewsCriterion newsCriterion) {

//        if(adminId == null) {
//            return ResponseUtil.unlogin();
//        }

        News news = new News();
        news.setNewsCriterion(newsCriterion);
        news.setType(newsCriterion.getType());
        List<News> lstNews = null;
        int total = 0;

        // 获取我参加的活动-并将它作为返回参数
        if (newsCriterion.isMyJoin()) {
            total = newsService.countSelectiveForMyJoin(news);
            lstNews = newsService.querySelectiveForMyJoin(news);

            for(News newsItem : lstNews) {
                newsItem.setJoin(true);
            }

        } else {

            if (StringUtils.isBlank(newsCriterion.getType()) || newsCriterion.getType().equals("activityNews")) {
                lstNews = newsService.querySelectiveForActivityNews(news);
            } else {
                if (newsCriterion.isCommentOn()) {
                    lstNews = newsService.querySelctiveWithComment(news);
                } else {
                    lstNews = newsService.querySelective(news);
                }
            }
            // List<News> lstNews = newsService.findNews(news);
            total = newsService.countSelective(news);


            /*List<ActivityUser> lstActivityUser = null;
            // 获取用户已参加的活动
            ActivityUser activityUser = new ActivityUser();
            int createId = adminId == null ? newsCriterion.getUserId() : adminId;

            if (StringUtils.isBlank(newsCriterion.getType())) {

                for (News newsItem : lstNews) {
                    if (newsItem.getType().equals("activity")) {
                        if (lstActivityUser == null) {
                            lstActivityUser = activityUserService.findActivityUser(activityUser);
                        }

                        for (ActivityUser activityUserItem : lstActivityUser) {
                            if (newsItem.getId() == activityUserItem.getNewsId()) {
                                newsItem.setJoin(true);
                                break;
                            }
                        }
                    }
                }

            } else if (newsCriterion.getType() != null && newsCriterion.getType().equals("activity")) {

                if (createId != 0) {
                    activityUser.setUserId(createId);
                    lstActivityUser = activityUserService.findActivityUser(activityUser);

                    List<News> lstMyJoin = new ArrayList<News>();
                    for (News newsItem : lstNews) {

                        for (ActivityUser activityUserItem : lstActivityUser) {
                            if (newsItem.getId() == activityUserItem.getNewsId()) {
                                newsItem.setJoin(true);
                                break;
                            }
                        }
                    }
                }
            }*/
        }
        
        if(newsCriterion.getType() != null && newsCriterion.getType().equals("tidings")){
        	for(News newsItem : lstNews) {
        		NewsComment newsComment = new NewsComment();
                newsComment.setNewsId(newsItem.getId());
                List<NewsComment> lstCommont = newsCommentService.querySelective(newsComment, 1, 1000, null);
                newsItem.setLstNewsComment(lstCommont);

                NewsZan newsZan =  new NewsZan();
                newsZan.setNewsId(newsItem.getId());
                List<NewsZan> lstNewsZan = newsZanService.querySelective(newsZan, 1, 1000, null);
                newsItem.setLstNewsZan(lstNewsZan);
        	}
        }

        Map<String, Object> data = new HashMap<String, Object>();
        data.put("total", total);
        data.put("items", lstNews);

        return ResponseUtil.ok(data);
    }

    /**
     * 获取圈子动态列表
     */
    @GetMapping("lstOrgNews")
    public Object listOrgNews(@LoginUser Integer adminId, Integer orgId, Integer userIdForZan,
                              @RequestParam(value = "page", defaultValue = "1")Integer page,
                              @RequestParam(value = "limit", defaultValue = "10")Integer limit) {
    	Map<String, Object> data = new HashMap<String, Object>();
//        if(adminId == null) {
//            return ResponseUtil.unlogin();
//        }

        List<News> lstNews = newsService.queryByOrgIdForNews(orgId, userIdForZan, page, limit);
        int total = newsService.countByOrgIdForNews(orgId);
        
        
        //筛选出管理员发布的，用于匹配昵称头像
        List ids = new ArrayList();
        for(News news : lstNews) {
        	if("1".equals(news.getIsAdmin())){
        		ids.add(news.getCreatorId());
        	}
        }
        if(ids.size()>0){
        	List<Admin> adminInfos = adminService.findByIdList(ids);
	        for(int i=0;i<lstNews.size();i++){
	        	for(int j=0;j<adminInfos.size();j++){
		        	if("1".equals( lstNews.get(i).getIsAdmin()) && lstNews.get(i).getCreatorId().equals(adminInfos.get(j).getId().toString()) ){
		        		lstNews.get(i).setCreator(adminInfos.get(j).getNickname());
		        		lstNews.get(i).setPhoto(adminInfos.get(j).getAvatar());
		        		break;
		        	}
		        }
	        }	
        }
        
        
        
        
      //  List<List<Map<String, Object>>> commentsVoAll = new ArrayList<>(total);
        for(News news : lstNews) {
            NewsComment newsComment = new NewsComment();
            newsComment.setNewsId(news.getId());
            
            List<NewsComment> lstCommont = newsCommentService.querySelective(newsComment, 1, 10, null);
            news.setLstNewsComment(lstCommont);//原本的多个变10条
            
            int totalcm = newsCommentService.countSelective(newsComment);
            //单个新闻、活动下的所有评论回复数据
            List<Map<String, Object>> commentsVo = new ArrayList<>(totalcm);
            for(NewsComment nc:lstCommont){
            	Map<String, Object> mp=new HashMap<>();
        		mp.put("entity",nc);
        		
        		List<NewsComment> zicommen = newsCommentService.selectByZiExample(nc.getId());
    			List<Map<String, Object>> subcommentsVo = new ArrayList<>(zicommen.size());
    			 for(NewsComment zn:zicommen){
    				 Map<String, Object> subc = new HashMap<>();
    				 subc.put("entity", zn);
    				 subcommentsVo.add(subc);
    			 }
    			 mp.put("zisize", zicommen.size());
    			 mp.put("subcomment", subcommentsVo);
    			 commentsVo.add(mp);
            }
            if(commentsVo.size()>0){
            	news.setListObject(commentsVo);
//            	commentsVoAll.add(commentsVo);//评论数据
            }
            
            NewsZan newsZan =  new NewsZan();
            newsZan.setNewsId(news.getId());
            List<NewsZan> lstNewsZan = newsZanService.querySelective(newsZan, 1, 1000, null);
            news.setLstNewsZan(lstNewsZan);
        }

       // data.put("datas", commentsVoAll);
        data.put("total", total);
        data.put("items", lstNews);

        return ResponseUtil.ok(data);
    }

    /**
     * 获取关注好友的动态列表
     */
    @GetMapping("lstFirendNews")
    public Object lstFirendNews(@LoginUser Integer adminId, Integer userId,
                              @RequestParam(value = "page", defaultValue = "1")Integer page,
                              @RequestParam(value = "limit", defaultValue = "10")Integer limit) {



        userId = adminId != null ? adminId : userId;
//        if(userId == null) {
//            return ResponseUtil.unlogin();
//        }
        List<News> lstNews = newsService.queryByFriendNews(userId, page, limit);
        int total = newsService.countByFriendForNews(userId);
        
        
        //  List<List<Map<String, Object>>> commentsVoAll = new ArrayList<>(total);
        for(News news : lstNews) {
            NewsComment newsComment = new NewsComment();
            newsComment.setNewsId(news.getId());
            
            List<NewsComment> lstCommont = newsCommentService.querySelective(newsComment, 1, 10, null);
            news.setLstNewsComment(lstCommont);//原本的多个变10条
            
            int totalcm = newsCommentService.countSelective(newsComment);
            //单个新闻、活动下的所有评论回复数据
            List<Map<String, Object>> commentsVo = new ArrayList<>(totalcm);
            for(NewsComment nc:lstCommont){
            	Map<String, Object> mp=new HashMap<>();
        		mp.put("entity",nc);
        		
        		List<NewsComment> zicommen = newsCommentService.selectByZiExample(nc.getId());
    			List<Map<String, Object>> subcommentsVo = new ArrayList<>(zicommen.size());
    			 for(NewsComment zn:zicommen){
    				 Map<String, Object> subc = new HashMap<>();
    				 subc.put("entity", zn);
    				 subcommentsVo.add(subc);
    			 }
    			 mp.put("zisize", zicommen.size());
    			 mp.put("subcomment", subcommentsVo);
    			 commentsVo.add(mp);
            }
            if(commentsVo.size()>0){
            	news.setListObject(commentsVo);
//            	commentsVoAll.add(commentsVo);//评论数据
            }
            
            NewsZan newsZan =  new NewsZan();
            newsZan.setNewsId(news.getId());
            List<NewsZan> lstNewsZan = newsZanService.querySelective(newsZan, 1, 1000, null);
            news.setLstNewsZan(lstNewsZan);
        }
        

        Map<String, Object> data = new HashMap<String, Object>();
        data.put("total", total);
        data.put("items", lstNews);

        return ResponseUtil.ok(data);
    }

    /**
     * 获取交互内容 详情
     * @Param id 活动编号
     * @return
     */
    @GetMapping("read")
    public Object read(@LoginUser Integer adminId, Integer id, Integer userIdForZan) {

//        if(adminId == null) {
//            return ResponseUtil.unlogin();
//        }

        if(id == null){
            return ResponseUtil.badArgument();
        }

        News news = null;
        if(userIdForZan == null) {
            news = newsService.findById(id);
        } else {
            news = newsService.findByIdWithCommon(id, userIdForZan);
        }
        Map<String, Object> data = new HashMap<String, Object>();

        if(news != null && news.getType().equals("activity")) {
//            ActivityUser activityUser = new ActivityUser();
//            activityUser.setNewsId(id);
//            List<ActivityUser> lstActivityUser = activityUserService.findActivityUser(activityUser);

//            news.setUserCount(lstActivityUser.size());//参加人数
            data.put("activity", news);
//            data.put("activityUsers", lstActivityUser);
        } else {
            data.put("news", news);
        }

        return ResponseUtil.ok(data);
    }
    
    /**
     * 获取活动参加人员
     * @return
     */
    @GetMapping("listActUser")
    public Object list(@LoginUser Integer adminId,
                       Integer newsId,
                       @RequestParam(value = "page", defaultValue = "1")Integer page,
                       @RequestParam(value = "limit", defaultValue = "10")Integer limit,
                       String sort){
//        if(adminId == null) {
//            return ResponseUtil.unlogin();
//        }
//        List<ActivityUser> listActUser = activityUserService.selectByNewsId(newsId,page,limit,sort);
//        int total = activityUserService.countByNewsId(newsId);
        Map<String, Object> data = new HashMap<String, Object>();
//        data.put("items", listActUser);
//        data.put("total", total);
        return ResponseUtil.ok(data);
    }

    /**
     * 创建交互内容
     * @return
     */
    @PostMapping("create")
    public Object create(@LoginUser Integer adminId, @RequestBody News news) {

    	if(adminId == null && StringUtils.isBlank(news.getCreatorId())) {
            return ResponseUtil.unlogin();
        }
        
        if(StringUtils.isBlank(news.getType())) {
            return ResponseUtil.badArgument();
        }

        int creatorId = adminId == null ? Integer.valueOf(news.getCreatorId()) : adminId;
        AlumniUser user = userService.findById(creatorId);
        if(user != null) {
            news.setCreator(user.getUserName());
        }
        news.setCreatorId(String.valueOf(creatorId));
        news.setCreateDate(LocalDateTime.now());
        newsService.add(news);

       if(news.getOrganizeId() != null && news.getOrganizeId().length > 0) {
            for(int organizeId : news.getOrganizeId()) {
                NewsOrganize newsOrganize = new NewsOrganize();
                newsOrganize.setNewsId(news.getId());
                newsOrganize.setOrganizeId(organizeId);
                newsOrganize.setUserId(creatorId);
                newsOrganize.setFromType("1");

                newsOrganizeService.add(newsOrganize);
            }
        }
        /*else {
            // 创建活动的时候默认将互动推送到用户参加的圈子
            if(news.getType().equals("activity")) {
                //获取用户参加的圈子
                Map<String,Object> mapOrganizeUser = alumniOrganizeUserService.selectByOrgIdAndUse(null, null, creatorId, null,1, 1000);
                List<AlumniOrganizeUserCustom> listOrganizeUser = mapOrganizeUser.get("items") == null ? null :
                        (List<AlumniOrganizeUserCustom>)mapOrganizeUser.get("items");

                if(listOrganizeUser != null) {
                    for(AlumniOrganizeUserCustom alumniOrganizeUserCustom : listOrganizeUser) {
                        NewsOrganize newsOrganize = new NewsOrganize();
                        newsOrganize.setNewsId(news.getId());
                        newsOrganize.setOrganizeId(alumniOrganizeUserCustom.getFkOrganizeId());
                        newsOrganize.setUserId(creatorId);
                        newsOrganize.setFromType("1");

                        newsOrganizeService.add(newsOrganize);
                    }
                }
            }
        }*/
        return ResponseUtil.ok(news);
    }

    /**
     * 更新交互内容
     * @return
     */
    @PostMapping("update")
    public Object update(@LoginUser Integer adminId, @RequestBody News news) {

//        if(adminId == null && StringUtils.isBlank(news.getCreatorId())) {
//            return ResponseUtil.unlogin();
//        }

        newsService.updateById(news);

        newsOrganizeService.deleteByActivityId(news.getId());
        if(news.getOrganizeId() != null) {
            for(int organizeId : news.getOrganizeId()) {
                NewsOrganize newsOrganize = new NewsOrganize();
                newsOrganize.setNewsId(news.getId());
                newsOrganize.setOrganizeId(organizeId);
                newsOrganize.setFromType("1");

                newsOrganizeService.add(newsOrganize);
            }
        }

        return ResponseUtil.ok(news);
    }

    /**
     * 删除交互内容
     * @return
     */
    @PostMapping("delete")
    public Object delete(@LoginUser Integer adminId, @RequestBody News news) {

//        if(adminId == null && StringUtils.isBlank(news.getCreatorId())) {
//            return ResponseUtil.unlogin();
//        }

        Integer id = news.getId();
        if(id == null) {
            return ResponseUtil.badArgument();
        }

        newsService.deleteById(id);
        // 删除活动推送圈子信息
        newsOrganizeService.deleteByActivityId(id);
        // 删除活动参加人
        /*ActivityUser activityUser = new ActivityUser();
        activityUser.setNewsId(news.getId());
        activityUserService.delete(activityUser);*/

        return ResponseUtil.ok();
    }

    /**
     * 获取评论列表
     * 获取评论及回复所有数据 lurz
     * @Param id 新闻/活动 id
     */
    @GetMapping("listCommon")
    public Object listCommon(@LoginUser Integer adminId, Integer id,
                             @RequestParam(value = "page", defaultValue = "1")Integer page,
                             @RequestParam(value = "limit", defaultValue = "10")Integer limit,
                             String sort) {

        // if(adminId == null) {
        //  return ResponseUtil.unlogin();
        // }

        NewsComment newsComment = new NewsComment();
        newsComment.setNewsId(id);
        List<NewsComment> lstCommont = newsCommentService.querySelective(newsComment, page, limit, sort);
        int total = newsCommentService.countSelective(newsComment);
        
        //单个新闻、活动下的所有评论回复数据
    	List<Map<String, Object>> commentsVo = new ArrayList<>(total);
    	for(NewsComment nc:lstCommont){
    		Map<String, Object> mp=new HashMap<>();
    		mp.put("entity",nc);
    		
    		//获取子评论
    		 
    		List<NewsComment> zicommen = newsCommentService.selectByZiExample(nc.getId());
			List<Map<String, Object>> subcommentsVo = new ArrayList<>(zicommen.size());
			 for(NewsComment zn:zicommen){
				 Map<String, Object> subc = new HashMap<>();
				 subc.put("entity", zn);
				 subcommentsVo.add(subc);
			 }
			 mp.put("zisize", zicommen.size());
			 mp.put("subcomment", subcommentsVo);
			 commentsVo.add(mp);
    	}

        Map<String, Object> data = new HashMap<String, Object>();
        data.put("items", lstCommont);
        data.put("total", total);
        data.put("datas", commentsVo);//评论数据
        

        return ResponseUtil.ok(data);
    }

    /**
     * 创建新闻评论
     */
    @PostMapping("createCommon")
    public Object createCommon(@LoginUser Integer adminId, @RequestBody NewsComment newsComment) {

        // if(adminId == null) {
        //  return ResponseUtil.unlogin();
        // }

        //newsComment.setUserId(adminId);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        newsComment.setCreateDate(df.format(new Date()));
        newsCommentService.add(newsComment);
        try {
			newsComment.setContent(URLDecoder.decode(newsComment.getContent(), "utf-8"));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        return ResponseUtil.ok(newsComment);
    }

    /**
     * 删除评论
     */
    @PostMapping("deleteCommon")
    public Object deleteCommon(@LoginUser Integer adminId, @RequestBody NewsComment newsComment) {
        // if(adminId == null) {
        //  return ResponseUtil.unlogin();
        // }

        if(newsComment.getId() == 0) {
            return ResponseUtil.badArgument();
        }

        newsCommentService.delete(newsComment.getId());

        return ResponseUtil.ok();
    }

    /**
     * 新闻点赞
     */
    @PostMapping("zan")
    public Object zan(@LoginUser Integer adminId, @RequestBody NewsZan newsZan) {

        // if(adminId == null) {
        //  return ResponseUtil.unlogin();
        // }

        newsZanService.add(newsZan);
        return ResponseUtil.ok(newsZan);
    }

    /**
     * 删除新闻点赞
     */
    @PostMapping("deleteZan")
    public Object deleteZan(@LoginUser Integer adminId, @RequestBody NewsZan newsZan) {

//        if(adminId == null) {
//            return ResponseUtil.unlogin();
//        }

        newsZanService.deleteByExample(newsZan);
        return ResponseUtil.ok();

    }

    /**
     * 删除我发起的圈子动态和活动的关联(活动不删除，只删除与圈子的关联)
     * @return
     */
    @RequestMapping(value = "deleteMyOrganizeNews")
    public Object deleteMyOrganizeNews(String userId, Integer newId, String organizeId){
        if(userId == null || newId == null)
            return ResponseUtil.fail402();
        News news = newsService.findById(newId);
        if(news != null){
            String createId = news.getCreatorId();
            String newType = news.getType();
            if(newType.equals("activity")){//校友活动
                if(createId.equals(userId)){
                    //删除圈子里的关联活动
                    if(organizeId != null){//圈子id不为null
                        newsService.deleteOrganizeNewsByActivity(news.getId()+"", organizeId);
                    } else {
                        return ResponseUtil.fail("参数缺失：圈子id不能为空");
                    }
                }
            } else if (newType.equals("tidings")){//动态
                //删除我发布的动态
                if(createId.equals(userId)){
                    newsService.deleteDynamicByNewId(news.getId());
                }
            }
            return ResponseUtil.ok();
        } else {
            return ResponseUtil.fail();
        }

    }
}
