package cn.api.system;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson2.JSONObject;
import cn.facade.abs.IService;
import cn.common.page.response.Result;
import cn.api.websocket.WebSocket;
import cn.constant.CommonConst;
import cn.facade.constant.CommonSendStatus;
import cn.facade.constant.WebsocketConst;
import cn.orm.sqltoy.plus.Wrappers;
import cn.orm.sqltoy.plus.query.QueryWrapper;
import cn.orm.sqltoy.plus.update.LambdaUpdateWrapper;
import cn.pojo.entity.TSysAnnouncement;
import cn.pojo.entity.TSysAnnouncementSend;
import cn.service.util.UnifyFieldsUtil;
import cn.util.core.IsKit;
import cn.util.time.TimeKit;

import javax.annotation.Resource;

/**系统通告表annountCement
 * 用户通告阅读标记表sysAnnouncementSend
 * 这里只移植部分方法，其他方法可采用通用方法实现
 * */
@RestController
@RequestMapping("/api/sys")
public class SysNoticeCtrl extends IService
{
	@Resource
	private WebSocket webSocket;

	/**
	 * 功能：更新用户系统消息阅读状态
	 */
	@PutMapping(value = "/sysAnnouncementSend//editByAnntIdAndUserId")
	public Result<?> editById(@RequestBody JSONObject json)
	{	
		String anntId = json.getString("anntId");
		String userId = UnifyFieldsUtil.getUserName();
		LambdaUpdateWrapper<TSysAnnouncementSend> updateWrapper = Wrappers.lambdaUpdateWrapper(TSysAnnouncementSend.class)
				.set(TSysAnnouncementSend::getReadTime, TimeKit.getNowLocalDateTime())
				.set(TSysAnnouncementSend::getReadFlag, CommonConst.CHAR_NUM_1)
				.eq(TSysAnnouncementSend::getAnntId,anntId) 
				.eq(TSysAnnouncementSend::getUserId,userId);
		long result = daoService.update(updateWrapper);
		return result>0? Result.ok("全部已读"): Result.warnMsg("全部读失败");
	}
	/**功能：一键已读*/
	@PutMapping(value = "/sysAnnouncementSend/readAll")
	public Result<?> readAll()
	{
		String userId = UnifyFieldsUtil.getUserName();
		LambdaUpdateWrapper<TSysAnnouncementSend> updateWrapper = Wrappers.lambdaUpdateWrapper(TSysAnnouncementSend.class)
				.set(TSysAnnouncementSend::getReadTime, TimeKit.getNowLocalDateTime())
				.set(TSysAnnouncementSend::getReadFlag, CommonConst.CHAR_NUM_1)
				.eq(TSysAnnouncementSend::getUserId,userId);
		long result = daoService.update(updateWrapper);
		return result>0? Result.okMsg("全部已读"): Result.warnMsg("全部读失败");
	}

	/**更新撤销操作*/
	@RequestMapping(value = "/annountCement//doReovkeData", method = RequestMethod.GET)
	public Result<?> doReovkeData(@RequestParam(name="id") String id)
	{
		QueryWrapper<TSysAnnouncement> queryWrapper = Wrappers.wrapper(TSysAnnouncement.class)
				.eq("anntId", id);
		TSysAnnouncement sysAnnouncement = daoService.findOne(queryWrapper);

		if(IsKit.isNullOrEmpty(sysAnnouncement)){
			return Result.warnMsg("未找到对应实体");
		}else {
			sysAnnouncement.setSendStatus(CommonSendStatus.REVOKE_STATUS_2);//撤销发布
			sysAnnouncement.setCancelTime(TimeKit.getNowLocalDateTime());
			Long ok = daoService.update(sysAnnouncement);
			if(ok>0 ) {
				return Result.okMsg("该系统通知撤销成功");
			}
		}
		return Result.okMsg("该系统通知撤销失败");
	}
	/** 更新发布操作*/
	@RequestMapping(value = "/annountCement/doReleaseData", method = RequestMethod.GET)
	public Result<?> doReleaseData(@RequestParam(name="id") String id)
	{
		QueryWrapper<TSysAnnouncement> queryWrapper = Wrappers.wrapper(TSysAnnouncement.class)
				.eq("anntId", id);
		TSysAnnouncement sysAnnouncement = daoService.findOne(queryWrapper);
		if(IsKit.isNullOrEmpty(sysAnnouncement)){
			return Result.warnMsg("未找到对应实体");
		}else {
			sysAnnouncement.setSendStatus(CommonSendStatus.PUBLISHED_STATUS_1);//发布中
			sysAnnouncement.setSendTime(TimeKit.getNowLocalDateTime());
			String currentUserName = UnifyFieldsUtil.getUserName();
			sysAnnouncement.setSender(currentUserName);
			Long ok = daoService.update(sysAnnouncement);
			if(ok>0 ) {				
				if(sysAnnouncement.getMsgType().equals(CommonConst.MSG_TYPE_ALL)) {
					JSONObject obj = new JSONObject();
					obj.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_TOPIC);
					obj.put(WebsocketConst.MSG_ID, sysAnnouncement.getId());
					obj.put(WebsocketConst.MSG_TXT, sysAnnouncement.getTitile());
					webSocket.sendAllMessage(obj.toJSONString());
				}else {
					// 2.插入用户通告阅读标记表记录
					String userId = sysAnnouncement.getUserIds();
					String[] userIds = userId.substring(0, (userId.length()-1)).split(",");
					//String anntId = sysAnnouncement.getId();Date refDate = new Date();
					JSONObject obj = new JSONObject();
					obj.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_USER);
					obj.put(WebsocketConst.MSG_ID, sysAnnouncement.getId());
					obj.put(WebsocketConst.MSG_TXT, sysAnnouncement.getTitile());
					webSocket.sendMoreMessage(userIds, obj.toJSONString());
				}
			}
		}
		return Result.ok("该系统通知发布成功");
	}

	/**同步消息 */
	@RequestMapping(value = "/annountCement/syncNotic", method = RequestMethod.GET)
	public Result<?> syncNotic(@RequestParam(name="anntId") String anntId)
	{
		JSONObject obj = new JSONObject();
		if(StringUtils.isNotBlank(anntId))
		{
			QueryWrapper<TSysAnnouncement> queryWrapper = Wrappers.wrapper(TSysAnnouncement.class)
					.eq("anntId", anntId);
			TSysAnnouncement sysAnnouncement = daoService.findOne(queryWrapper);

			if(IsKit.isNullOrEmpty(sysAnnouncement)){
				return Result.warnMsg("未找到对应实体");
			}
			else {
				if(sysAnnouncement.getMsgType().equals(CommonConst.MSG_TYPE_ALL)) {
					obj.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_TOPIC);
					obj.put(WebsocketConst.MSG_ID, sysAnnouncement.getId());
					obj.put(WebsocketConst.MSG_TXT, sysAnnouncement.getTitile());
					webSocket.sendAllMessage(obj.toJSONString());
				}else {
					// 2.插入用户通告阅读标记表记录
					String userId = sysAnnouncement.getUserIds();
					if(IsKit.isNotNullOrEmpty(userId)){
						String[] userIds = userId.substring(0, (userId.length()-1)).split(",");
						obj.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_USER);
						obj.put(WebsocketConst.MSG_ID, sysAnnouncement.getId());
						obj.put(WebsocketConst.MSG_TXT, sysAnnouncement.getTitile());
						webSocket.sendMoreMessage(userIds, obj.toJSONString());
					}
				}
			}
		}else{
			obj.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_TOPIC);
			obj.put(WebsocketConst.MSG_TXT, "批量设置已读");
			webSocket.sendAllMessage(obj.toJSONString());
		}
		return Result.ok("找到对应实体");
	}


}
