package com.zehong.web.controller.system;

import com.alibaba.fastjson.JSONObject;
import com.zehong.common.annotation.Log;
import com.zehong.common.core.controller.BaseController;
import com.zehong.common.core.domain.AjaxResult;
import com.zehong.common.core.domain.entity.SysUser;
import com.zehong.common.core.page.TableDataInfo;
import com.zehong.common.enums.BusinessType;
import com.zehong.common.utils.SecurityUtils;
import com.zehong.common.utils.ServletUtils;
import com.zehong.common.utils.StringUtils;
import com.zehong.framework.web.service.TokenService;
import com.zehong.framework.web.service.WebSocketServer;
import com.zehong.system.domain.SysNotice;
import com.zehong.system.service.ISysNoticeService;
import com.zehong.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 公告 信息操作处理
 *
 * @author zehong
 */
@RestController
@RequestMapping("/system/notice")
public class SysNoticeController extends BaseController
{
    @Autowired
    private ISysNoticeService noticeService;

    @Autowired
    private WebSocketServer webSocketServer;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private TokenService tokenService;
    /**
     * 获取通知公告列表
     */
    @PreAuthorize("@ss.hasPermi('system:notice:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysNotice notice)
    {
        // 获取当前用户
        SysUser user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        notice.setUserId(user.getUserId());
        startPage();
        List<SysNotice> list = noticeService.selectNoticeList(notice);
        return getDataTable(list);
    }

    /**
     * 根据通知公告编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:notice:query')")
    @GetMapping(value = "/{noticeId}")
    public AjaxResult getInfo(@PathVariable Long noticeId)
    {
        return AjaxResult.success(noticeService.selectNoticeById(noticeId));
    }

    /**
     * 新增通知公告
     */
    @PreAuthorize("@ss.hasPermi('system:notice:add')")
    @Log(title = "通知公告", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysNotice notice)
    {
        notice.setCreateBy(SecurityUtils.getUsername());
        return toAjax(noticeService.insertNotice(notice));
    }

    /**
     * 修改通知公告
     */
//    @PreAuthorize("@ss.hasPermi('system:notice:edit')")
    @Log(title = "通知公告", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysNotice notice)
    {
        notice.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(noticeService.updateNotice(notice));
    }

    /**
     * 删除通知公告
     */
    @PreAuthorize("@ss.hasPermi('system:notice:remove')")
    @Log(title = "通知公告", businessType = BusinessType.DELETE)
    @DeleteMapping("/{noticeIds}")
    public AjaxResult remove(@PathVariable Long[] noticeIds)
    {
        return toAjax(noticeService.deleteNoticeByIds(noticeIds));
    }


    /**
     * 推送消息
     * @param notice 通知消息体
     * @return
     */
    @PostMapping("/sendNotice")
    public AjaxResult sendNotice(@RequestBody SysNotice notice){
        updateNoticeByRelationId(notice);
        notice.setCreateBy(SecurityUtils.getUsername());
        notice.setCreateTime(new Date());
        if(StringUtils.isNotNull(notice.getUserId())){
            //新增通知
            noticeService.insertNotice(notice);
            //推送通知消息
            webSocketServer.sendMessage(String.valueOf(notice.getUserId()));
        }

        //根据角色推送消息
        if(StringUtils.isNotEmpty(notice.getRoles())){
            Map<String,Object> map = new HashMap<>();
            if(StringUtils.isNotNull(notice.getDeptId())){
                map.put("deptId",notice.getDeptId());
            }
            map.put("roleKey", notice.getRoles());
            List<SysUser> userList = sysUserService.selectUserInfoByDeptAndRoleKey(map);
            userList.stream().forEach(item ->{
                //新增通知
                notice.setUserId(item.getUserId());
                noticeService.insertNotice(notice);
                //推送通知消息
                webSocketServer.sendMessage(String.valueOf(item.getUserId()));
            });
        }
        return AjaxResult.success("消息推送成功！");
    }

    @PostMapping("/deleteNoticeByRelationId")
    public AjaxResult deleteNoticeByRelationId(@RequestBody SysNotice notice){
        SysNotice noticeInfo = new SysNotice();
        noticeInfo.setStatus("0");
        noticeInfo.setRelationId(notice.getRelationId());
        List<SysNotice> noticeList = noticeService.selectNoticeList(noticeInfo);
        int rows = noticeService.deleteNoticeByRelationId(notice.getRelationId());
        noticeList.forEach(item ->{
            webSocketServer.sendMessage(String.valueOf(item.getUserId()));
        });
        return toAjax(rows);
    }

    @PostMapping("/noticeIsReadByRelationId")
    public AjaxResult noticeIsReadByRelationId(@RequestBody SysNotice notice){
        updateNoticeByRelationId(notice);
        return AjaxResult.success();
    }

    private int updateNoticeByRelationId(SysNotice notice){
        if(StringUtils.isNotEmpty(String.valueOf(notice.getRelationId())) && !notice.isStart()){
            SysNotice noticeInfo = new SysNotice();
            noticeInfo.setStatus("0");
            noticeInfo.setRelationId(notice.getRelationId());
            List<SysNotice> noticeList = noticeService.selectNoticeList(noticeInfo);
            SysNotice deleteNotice = new SysNotice();
            deleteNotice.setStatus("1");
            deleteNotice.setRelationId(notice.getRelationId());
            int rows =  noticeService.updateNoticeByRelationId(deleteNotice);
            noticeList.forEach(item ->{
                webSocketServer.sendMessage(String.valueOf(item.getUserId()));
            });
            return rows;
        }
        return 0;
    }

}
