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

import com.easemob.server.example.api.impl.EasemobIMUsers;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.JPushClientUtil;
import com.jeeplus.common.utils.JedisUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.utils.ErrorCode;
import com.jeeplus.modules.workmeeting.entity.Workmeetinginfo;
import com.jeeplus.modules.workmeeting.entity.Workmeetinguser;
import com.jeeplus.modules.workmeeting.service.WorkmeetinginfoService;
import com.jeeplus.modules.workmeeting.service.WorkmeetinguserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;

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

@Controller
@RequestMapping(value = "${frontPath}/meeting")
public class MeetingCortroller extends BaseController {
    @Autowired
    private WorkmeetinginfoService workmeetinginfoService;
    @Autowired
    private WorkmeetinguserService workmeetinguserService;
	@ResponseBody
    @RequestMapping(value = "pushMeetingToUsers", method = RequestMethod.GET)
    public AjaxJson pushMeetingToUsers(String id,String ids,String roomName,HttpServletRequest request, HttpServletResponse response) {
        logger.info("pushMeetingToUsers------------------------------------------------");
        logger.info("http://116.62.246.213:8084/jeeplus/f/meeting/pushMeetingToUsers?id="+id+"&ids="+ids+"&roomName"+roomName);
        AjaxJson json = new AjaxJson();
        try {
            json.setSuccess(false);
            json.setErrorCode(ErrorCode.code_2001);
            if (StringUtils.isBlank(id)){
                json.setMsg("获取失败：参数id不能为空");
                return json;
            }
            if (StringUtils.isBlank(ids)){
                json.setMsg("获取失败：参数ids不能为空");
                return json;
            }
            if (StringUtils.isBlank(roomName)){
                json.setMsg("获取失败：参数roomName不能为空");
                return json;
            }
            User user = UserUtils.get(id);
            String title= user.getName()+"邀请您加入会议！";
            String content= user.getName()+"邀请您加入会议！";
            List<String> list = new ArrayList<>();
            Workmeetinginfo workmeetinginfo = new Workmeetinginfo();
            workmeetinginfo.setRoomName(roomName);
            List<Workmeetinginfo> Workmeetinginfos = workmeetinginfoService.findList(workmeetinginfo);
            if (Workmeetinginfos==null || Workmeetinginfos.size()==0){
                workmeetinginfo.setStatus("1");
                workmeetinginfoService.save(workmeetinginfo);
            }else {
                workmeetinginfo = Workmeetinginfos.get(0);
                if (!workmeetinginfo.getStatus().equals("1")){
                    json.setMsg("当前会议已结束！");
                    return json;
                }
            }
            Workmeetinguser select = new Workmeetinguser();
            select.setMeetingId(roomName);
            select.setUser(new User(id));
            Workmeetinguser meetinguser1 = workmeetinguserService.getByMeetingIdAndUser(select);
            if (meetinguser1 == null){
                meetinguser1 = new Workmeetinguser();
                meetinguser1.setMeetingId(roomName);
                meetinguser1.setUser(new User(id));
            }
            meetinguser1.setStatus("1");
            meetinguser1.setType("1");
            meetinguser1.preUpdate();
            workmeetinguserService.save(meetinguser1);
            if (ids.length()>0){
                String[] userIds = ids.split(",");
                for (String userId:userIds){
                    Workmeetinguser workmeetinguser = new Workmeetinguser();
                    workmeetinguser.setUser(new User(userId));
                    workmeetinguser.setStatus("1");
                    List<Workmeetinguser> userList = workmeetinguserService.getByUserId(workmeetinguser);
                    if (userList==null || userList.size()==0){
                        list.add(userId);
                        Workmeetinguser selectUser = new Workmeetinguser();
                        selectUser.setMeetingId(roomName);
                        selectUser.setUser(new User(userId));
                        Workmeetinguser meetinguser = workmeetinguserService.getByMeetingIdAndUser(selectUser);
                        if (meetinguser == null){
                            meetinguser = new Workmeetinguser();
                        }
                        meetinguser.setStatus("0");
                        meetinguser.setUser(new User(userId));
                        meetinguser.setMeetingId(roomName);
                        meetinguser.setType("2");
                        meetinguser.preUpdate();
                        workmeetinguserService.save(meetinguser);
                    }else {
                        Workmeetinguser selectUser = new Workmeetinguser();
                        selectUser.setMeetingId(roomName);
                        selectUser.setUser(new User(id));
                        Workmeetinguser meetinguser = workmeetinguserService.getByMeetingIdAndUser(selectUser);
                        if (meetinguser == null){
                            meetinguser = new Workmeetinguser();
                        }
                        meetinguser.setStatus("3");
                        meetinguser.setUser(new User(userId));
                        meetinguser.setMeetingId(roomName);
                        meetinguser.setType("2");
                        meetinguser.preUpdate();
                        workmeetinguserService.save(meetinguser);
                    }
                }
            }

            Map extras = new HashMap();
            extras.put("type", "6001");
            extras.put("title", title);
            extras.put("roomName", roomName);
            extras.put("name", user.getName());
            extras.put("photo", user.getPhoto());
            LinkedHashMap<String, Object> map = new LinkedHashMap<>();
            map.put("roomName", roomName);
            if (list==null || list.size()==0){
                json.setSuccess(false);
                json.setMsg("用户忙！");
                json.setErrorCode(ErrorCode.code_2005);
                json.setBody(map);
            }else {
                Map<String,Object> map1 = JPushClientUtil.sendNotificationToAliasesMap(title, content, extras, list);
                if (map1.get("status")!=null && map1.get("status").equals("true")) {
                    List<String> returnList = (List<String>)map1.get("list");
                    if (returnList!=null && returnList.size()!=0){
                        for (String uid:returnList ){
                            Workmeetinguser selectUser = new Workmeetinguser();
                            selectUser.setMeetingId(roomName);
                            selectUser.setUser(new User(uid));
                            Workmeetinguser meetinguser = workmeetinguserService.getByMeetingIdAndUser(selectUser);
                            meetinguser.setStatus("4");
                            meetinguser.setUser(new User(uid));
                            meetinguser.setMeetingId(roomName);
                            meetinguser.setType("2");
                            meetinguser.preUpdate();
                            workmeetinguserService.save(meetinguser);
                        }
                    }
                    json.setSuccess(true);
                    json.setMsg("已通知用户参加会议！");
                    json.setErrorCode(ErrorCode.code_1004);
                    json.setBody(map);
                } else {
                    workmeetinguserService.deleteByRoomName(roomName);
                    workmeetinginfoService.deleteByRoomName(roomName);
                    json.setSuccess(false);
                    json.setMsg("发送推送失败！");
                    json.setErrorCode(ErrorCode.code_2004);
                    json.setBody(map);
                }
            }
        }catch (Exception e){
            json.setSuccess(false);
            json.setMsg("数据异常！");
            json.setErrorCode(ErrorCode.code_2004);
            logger.info("Exception e"+e);
        }

        return json;
    }

    @ResponseBody
    @RequestMapping(value = "meetingUserInfo", method = RequestMethod.GET)
    public AjaxJson meetingUserInfo(String roomName,HttpServletRequest request, HttpServletResponse response) {
        AjaxJson json = new AjaxJson();
        try {
            json.setSuccess(false);
            json.setErrorCode(ErrorCode.code_2001);
            if (StringUtils.isBlank(roomName)){
                json.setMsg("获取失败：参数roomName不能为空");
                return json;
            }

            List<Map<String,Object>> mapList = new ArrayList<>();
            Workmeetinginfo workmeetinginfo = workmeetinginfoService.getByRoomName(roomName);
            if(workmeetinginfo!=null && StringUtils.isNotBlank(workmeetinginfo.getId())) {
                Workmeetinguser workmeetinguserSelect = new Workmeetinguser();
                workmeetinguserSelect.setMeetingId(roomName);
                List<Workmeetinguser> list = workmeetinguserService.getByMeetingId(workmeetinguserSelect);
                if (list!=null && list.size()!=0){
                    for (Workmeetinguser workmeetinguser: list){
                        Map<String,Object> map = new HashMap<>();
                        User user = workmeetinguser.getUser();
                        if (user!=null && StringUtils.isNotBlank(user.getId())){
                            map.put("userId",user.getId());
                            map.put("name",user.getName());
                            map.put("photo",user.getPhoto());
                            map.put("status",workmeetinguser.getStatus());
                            mapList.add(map);
                        }
                    }
                }
            }
            json.setSuccess(true);
            json.setMsg("已获取参与会议用户信息！");
            json.setErrorCode(ErrorCode.code_1004);
            json.put("data",mapList);
            json.put("roomName",roomName);
        }catch (Exception e){
            json.setSuccess(false);
            json.setMsg("数据异常！");
            json.setErrorCode(ErrorCode.code_2004);
        }

        return json;
    }

    @ResponseBody
    @RequestMapping(value = "meetingInfo", method = RequestMethod.GET)
    public AjaxJson meetingInfo(String id,String type,String roomName,String status,HttpServletRequest request, HttpServletResponse response) {
        logger.info("meetingInfo接口------------------------------------------------");
        logger.info("http://116.62.246.213:8084/jeeplus/f/meeting/meetingInfo?id="+id+"&type="+type+"&roomName"+roomName);
	    AjaxJson json = new AjaxJson();
        try{
            json.setSuccess(false);
            json.setErrorCode(ErrorCode.code_2001);
            if (StringUtils.isBlank(id)){
                json.setMsg("获取失败：参数id不能为空");
                return json;
            }
            if (StringUtils.isBlank(type)){
                json.setMsg("获取失败：参数type不能为空");
                return json;
            }
            if (StringUtils.isBlank(roomName)){
                json.setMsg("获取失败：参数roomName不能为空");
                return json;
            }
            User user = UserUtils.get(id);
            Workmeetinguser workmeetinguser = new Workmeetinguser();
            workmeetinguser.setMeetingId(roomName);
            LinkedHashMap<String,Object> map = new LinkedHashMap<>();
            if (type.equals("4")){
                String title = user.getName()+"已结束会议";
                map.put("info",title);
                map.put("type","4");
                List<Workmeetinguser> userList = workmeetinguserService.getByMeetingId(workmeetinguser);
                if (userList != null && userList.size() != 0) {
                    Map extras = new HashMap();
                    extras.put("type", "6002");
                    extras.put("roomName", roomName);
                    List list = new ArrayList();
                    for (Workmeetinguser wmu:userList){
                        if(wmu.getType().equals("2") &&(wmu.getStatus().equals("1") || wmu.getStatus().equals("0"))){
                            list.add(wmu.getUser().getId());
                        }
                    }
                    Workmeetinguser select = new Workmeetinguser();
                    select.setMeetingId(roomName);
                    select.setStatus("2");
                    select.preUpdate();
                    workmeetinguserService.updateByRoomName(select);
                    Workmeetinginfo workmeetinginfo = new Workmeetinginfo();
                    workmeetinginfo.setRoomName(roomName);
                    workmeetinginfo.setStatus("2");
                    workmeetinginfo.preUpdate();
                    workmeetinginfoService.updateByRoomName(workmeetinginfo);
                    boolean b = JPushClientUtil.sendNotificationToAliases(title, title, extras, list);
                    if (!b){
                        json.setMsg("当前无推送人员！");
                    }
                }else {
                    json.setMsg("获取失败：当前用户数据异常");
                    return json;
                }
            }else {
                Workmeetinguser meetingUser = new Workmeetinguser();
                workmeetinguser.setUser(new User(id));
                List<Workmeetinguser> userList = workmeetinguserService.getByMeetingId(workmeetinguser);
                if (userList == null || userList.size() != 1) {
                    json.setMsg("获取失败：当前用户重复加入");
                    return json;
                }
                meetingUser = userList.get(0);
                String state = "2";
                if (type.equals("1")){
                    map.put("info",user.getName()+"已申请接入");
                    state = "1";
                    map.put("type","1");
                }else if (type.equals("2")){
                    map.put("info",user.getName()+"已拒绝接入");
                    meetingUser.setStatus("2");
                    map.put("type","2");
                    /*Map extras = new HashMap();
                    extras.put("type", "6002");
                    extras.put("status", "2");
                    extras.put("roomName", roomName);
                    boolean b = JPushClientUtil.sendNotificationToAlias(user.getName()+"已拒绝接入", user.getName()+"已拒绝接入", extras, meetingUser.getCreateBy().getId());
                    if (!b){
                        json.setSuccess(false);
                        json.setMsg("推送失败！");
                        return json;
                    }*/
                }else if (type.equals("3")){
                    map.put("info",user.getName()+"已退出会议");
                    map.put("type","3");
                   /* Map extras = new HashMap();
                    extras.put("type", "6002");
                    extras.put("status", "3");
                    extras.put("roomName", roomName);
                    boolean b = JPushClientUtil.sendNotificationToAlias(user.getName()+"已退出会议", user.getName()+"已退出会议", extras, meetingUser.getCreateBy().getId());
                    if (!b){
                        json.setSuccess(false);
                        json.setMsg("推送失败！");
                        return json;
                    }*/
                }else {
                    json.setMsg("获取失败：参数type类型错误");
                    return json;
                }
                if(status==null || status.equals("0")) {
                    Map extras = new HashMap();
                    extras.put("type", "6003");
                    extras.put("roomName", roomName);
                    logger.info("---推送人:"+ meetingUser.getCreateBy().getId());
                    logger.info("---meetingUser:"+ meetingUser.toString());
                    boolean b = JPushClientUtil.sendNotificationToAlias(user.getName()+"会议状态改变", user.getName()+"会议状态改变", extras, meetingUser.getCreateBy().getId());
                    if (!b){
                        json.setSuccess(false);
                        json.setMsg("推送失败！");
                        return json;
                    }
                }

                meetingUser.setStatus(state);
                meetingUser.preUpdate();
                workmeetinguserService.save(meetingUser);
            }

            json.setSuccess(true);
            json.setErrorCode(ErrorCode.code_1004);
        }catch (Exception e){
            json.setSuccess(false);
            json.setMsg("数据异常！");
            json.setErrorCode(ErrorCode.code_2004);
            logger.info("Exception e"+e);
        }
        return json;
    }

    @ResponseBody
    @RequestMapping(value = "errOut", method = RequestMethod.GET)
    public AjaxJson errOut(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson json = new AjaxJson();
        try{
            User user = UserUtils.getUser();
            logger.info("----------------------------------");
            logger.info("user"+user.getId());
            logger.info("----------------------------------");
            Workmeetinguser workmeetinguser = new Workmeetinguser();
            workmeetinguser.setUser(user);
            workmeetinguser.setStatus("2");
            workmeetinguser.preUpdate();
            workmeetinguserService.updateByUser(workmeetinguser);
            Jedis jedis = null;
            try {
                jedis = JedisUtils.getResource();
                logger.info("-----UserUtils.getUser()："+UserUtils.getUser().getId());
                String userId = jedis.get(UserUtils.getUser().getId());
                if (StringUtils.isNotBlank(userId)){
                    logger.info("-----"+userId);
                    jedis.del(userId);
                }
                logger.info("-----"+(jedis.get(UserUtils.getUser().getId())==null?true:false));
            } catch (Exception e) {
                logger.error("getActiveSessions", e);
            } finally {
                JedisUtils.returnResource(jedis);
            }
            json.setSuccess(true);
            json.setErrorCode(ErrorCode.code_1004);
        }catch (Exception e){
            json.setSuccess(false);
            json.setMsg("数据异常！");
            json.setErrorCode(ErrorCode.code_2004);
            logger.info("Exception e"+e);
        }
        return json;
    }

    private static EasemobIMUsers easemobIMUsers = new EasemobIMUsers();

    @ResponseBody
    @RequestMapping(value = "userStatus", method = RequestMethod.GET)
    public AjaxJson userStatus(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson json = new AjaxJson();
	    User user = UserUtils.getUser();
        Object result = easemobIMUsers.getIMUserStatus(user.getId());
        json.put("result",result);
        return json;
    }

}
