package com.yushu.web.controller.system;

import java.util.List;
import java.util.Map;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.yushu.common.annotation.Log;
import com.yushu.common.core.controller.BaseController;
import com.yushu.common.core.domain.AjaxResult;
import com.yushu.common.core.page.TableDataInfo;
import com.yushu.common.enums.BusinessType;
import com.yushu.common.utils.SecurityUtils;
import com.yushu.common.utils.poi.ExcelUtil;
import com.yushu.system.domain.SysNotification;
import com.yushu.system.service.ISysNotificationService;
import com.yushu.web.websocket.MessageNotifier;

/**
 * 系统通知Controller
 * 
 * @author yushu
 * @date 2025-11-12
 */
@RestController
@RequestMapping("/system/notification")
public class SysNotificationController extends BaseController
{
    @Autowired
    private ISysNotificationService sysNotificationService;
    
    @Autowired
    private MessageNotifier messageNotifier;

    /**
     * 查询系统通知列表
     */
    @PreAuthorize("@ss.hasPermi('system:notification:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysNotification sysNotification)
    {
        startPage();
        List<SysNotification> list = sysNotificationService.selectSysNotificationList(sysNotification);
        return getDataTable(list);
    }

    /**
     * 获取所有系统通知（无权限要求）
     */
    @GetMapping("/public/list")
    public AjaxResult getAllNotifications()
    {
        List<Map<String, Object>> list = sysNotificationService.selectAllNotifications();
        return AjaxResult.success(list);
    }

    /**
     * 统计未读通知数
     */
    @GetMapping("/unread-count")
    public AjaxResult getUnreadCount()
    {
        int count = sysNotificationService.countUnreadNotifications();
        return AjaxResult.success(count);
    }

    /**
     * 标记通知为已读
     */
    @PostMapping("/mark-read/{notificationId}")
    public AjaxResult markNotificationAsRead(@PathVariable("notificationId") Long notificationId)
    {
        Long userId = SecurityUtils.getUserId();
        int result = sysNotificationService.markNotificationAsRead(notificationId, userId);
        return AjaxResult.success(result);
    }

    /**
     * 获取系统通知详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:notification:query')")
    @GetMapping(value = "/{notificationId}")
    public AjaxResult getInfo(@PathVariable("notificationId") Long notificationId)
    {
        return AjaxResult.success(sysNotificationService.selectSysNotificationByNotificationId(notificationId));
    }

    /**
     * 新增系统通知（新增后自动发布并推送WebSocket）
     */
    @PreAuthorize("@ss.hasPermi('system:notification:add')")
    @Log(title = "系统通知", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysNotification sysNotification)
    {
        sysNotification.setSenderId(SecurityUtils.getUserId());
        sysNotification.setSenderName(SecurityUtils.getUsername());
        sysNotification.setStatus("1"); // 直接设置为已发布
        
        int result = sysNotificationService.insertSysNotification(sysNotification);
        
        if (result > 0 && sysNotification.getTargetUsers() != null) {
            // 发布通知给目标用户
            sysNotificationService.publishNotification(sysNotification.getNotificationId());
            
            // 通过WebSocket推送通知
            try {
                Long[] targetUserIds = com.alibaba.fastjson2.JSON.parseObject(
                    sysNotification.getTargetUsers(), Long[].class);
                if (targetUserIds != null && targetUserIds.length > 0) {
                    messageNotifier.notifySystemMessage(
                        java.util.Arrays.asList(targetUserIds),
                        sysNotification.getTitle(),
                        sysNotification.getContent(),
                        sysNotification.getPriority()
                    );
                }
            } catch (Exception e) {
                logger.error("推送WebSocket通知失败", e);
            }
        }
        
        return toAjax(result);
    }

    /**
     * 修改系统通知
     */
    @PreAuthorize("@ss.hasPermi('system:notification:edit')")
    @Log(title = "系统通知", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysNotification sysNotification)
    {
        return toAjax(sysNotificationService.updateSysNotification(sysNotification));
    }

    /**
     * 删除系统通知
     */
    @PreAuthorize("@ss.hasPermi('system:notification:remove')")
    @Log(title = "系统通知", businessType = BusinessType.DELETE)
    @DeleteMapping("/{notificationIds}")
    public AjaxResult remove(@PathVariable Long[] notificationIds)
    {
        return toAjax(sysNotificationService.deleteSysNotificationByNotificationIds(notificationIds));
    }

    /**
     * 导出系统通知列表
     */
    @PreAuthorize("@ss.hasPermi('system:notification:export')")
    @Log(title = "系统通知", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysNotification sysNotification)
    {
        List<SysNotification> list = sysNotificationService.selectSysNotificationList(sysNotification);
        ExcelUtil<SysNotification> util = new ExcelUtil<SysNotification>(SysNotification.class);
        util.exportExcel(response, list, "系统通知数据");
    }

    /**
     * 发布通知
     */
    @PreAuthorize("@ss.hasPermi('system:notification:publish')")
    @Log(title = "发布通知", businessType = BusinessType.UPDATE)
    @PostMapping("/{notificationId}/publish")
    public AjaxResult publish(@PathVariable("notificationId") Long notificationId)
    {
        return toAjax(sysNotificationService.publishNotification(notificationId));
    }

    /**
     * 获取用户通知列表（无需权限）
     */
    @GetMapping("/my")
    public AjaxResult getMyNotifications()
    {
        List<Map<String, Object>> list = sysNotificationService.selectUserNotificationList(SecurityUtils.getUserId());
        return AjaxResult.success(list);
    }

    /**
     * 标记通知为已读（无需权限）
     */
    @PutMapping("/{notificationId}/read")
    public AjaxResult markAsRead(@PathVariable("notificationId") Long notificationId)
    {
        return toAjax(sysNotificationService.markNotificationAsRead(notificationId, SecurityUtils.getUserId()));
    }

    /**
     * 删除用户通知（无需权限）
     */
    @DeleteMapping("/{notificationId}/my")
    public AjaxResult deleteUserNotification(@PathVariable("notificationId") Long notificationId)
    {
        Long userId = SecurityUtils.getUserId();
        return toAjax(sysNotificationService.deleteUserNotification(notificationId, userId));
    }
}
