package com.aegis.web.controller.notification;

import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.aegis.common.annotation.Log;
import com.aegis.common.core.controller.BaseController;
import com.aegis.common.core.domain.AjaxResult;
import com.aegis.common.core.page.TableDataInfo;
import com.aegis.common.enums.BusinessType;
import com.aegis.common.utils.SecurityUtils;
import com.aegis.notification.domain.Notification;
import com.aegis.notification.domain.NotificationTemplate;
import com.aegis.notification.service.INotificationService;
import org.springframework.validation.annotation.Validated;

/**
 * 通知管理Controller
 * 
 * @author aegis
 */
@RestController
@RequestMapping("/notification")
public class NotificationController extends BaseController {
    
    @Autowired
    private INotificationService notificationService;
    
    /**
     * 查询我的通知列表
     */
    @PreAuthorize("@ss.hasPermi('notification:list')")
    @GetMapping("/list")
    public TableDataInfo list(@RequestParam(required = false) String status, 
                              @RequestParam(required = false) String channel) {
        startPage();
        Long receiverId = SecurityUtils.getUserId();
        List<Notification> list = notificationService.selectNotificationList(receiverId, status, channel);
        return getDataTable(list);
    }
    
    /**
     * 查询未读通知数量
     */
    @PreAuthorize("@ss.hasPermi('notification:query')")
    @GetMapping("/unread-count")
    public AjaxResult getUnreadCount() {
        Long receiverId = SecurityUtils.getUserId();
        int count = notificationService.countUnreadNotifications(receiverId);
        return success(count);
    }
    
    /**
     * 根据ID获取通知详情
     */
    @PreAuthorize("@ss.hasPermi('notification:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable Long id) {
        Long receiverId = SecurityUtils.getUserId();
        Notification notification = notificationService.selectNotificationById(id, receiverId);
        return success(notification);
    }
    
    /**
     * 发送通知（单个接收者）
     */
    @PreAuthorize("@ss.hasPermi('notification:send')")
    @Log(title = "通知管理", businessType = BusinessType.INSERT)
    @PostMapping("/send")
    public AjaxResult send(@RequestBody Map<String, Object> params) {
        Long receiverId = Long.valueOf(params.get("receiverId").toString());
        String title = params.get("title").toString();
        String content = params.get("content").toString();
        String channel = params.containsKey("channel") ? params.get("channel").toString() : "station";
        String businessType = params.containsKey("businessType") ? params.get("businessType").toString() : null;
        Long businessId = params.containsKey("businessId") ? Long.valueOf(params.get("businessId").toString()) : null;
        
        Long notificationId = notificationService.sendNotification(receiverId, title, content, 
                                                                    channel, businessType, businessId);
        return success(notificationId);
    }
    
    /**
     * 发送通知（批量接收者）
     */
    @PreAuthorize("@ss.hasPermi('notification:send')")
    @Log(title = "通知管理", businessType = BusinessType.INSERT)
    @PostMapping("/send-batch")
    public AjaxResult sendBatch(@RequestBody Map<String, Object> params) {
        @SuppressWarnings("unchecked")
        List<Long> receiverIds = (List<Long>) params.get("receiverIds");
        String title = params.get("title").toString();
        String content = params.get("content").toString();
        String channel = params.containsKey("channel") ? params.get("channel").toString() : "station";
        String businessType = params.containsKey("businessType") ? params.get("businessType").toString() : null;
        Long businessId = params.containsKey("businessId") ? Long.valueOf(params.get("businessId").toString()) : null;
        
        List<Long> notificationIds = notificationService.sendBatchNotification(receiverIds, title, content, 
                                                                                channel, businessType, businessId);
        return success(notificationIds);
    }
    
    /**
     * 使用模板发送通知
     */
    @PreAuthorize("@ss.hasPermi('notification:send')")
    @Log(title = "通知管理", businessType = BusinessType.INSERT)
    @PostMapping("/send-template")
    public AjaxResult sendTemplate(@RequestBody Map<String, Object> params) {
        Long receiverId = Long.valueOf(params.get("receiverId").toString());
        String templateCode = params.get("templateCode").toString();
        @SuppressWarnings("unchecked")
        Map<String, Object> variables = params.containsKey("variables") ? 
            (Map<String, Object>) params.get("variables") : null;
        String channel = params.containsKey("channel") ? params.get("channel").toString() : null;
        String businessType = params.containsKey("businessType") ? params.get("businessType").toString() : null;
        Long businessId = params.containsKey("businessId") ? Long.valueOf(params.get("businessId").toString()) : null;
        
        Long notificationId = notificationService.sendNotificationByTemplate(receiverId, templateCode, variables, 
                                                                              channel, businessType, businessId);
        return success(notificationId);
    }
    
    /**
     * 标记通知为已读
     */
    @PreAuthorize("@ss.hasPermi('notification:edit')")
    @Log(title = "通知管理", businessType = BusinessType.UPDATE)
    @PutMapping("/{id}/read")
    public AjaxResult markAsRead(@PathVariable Long id) {
        Long receiverId = SecurityUtils.getUserId();
        return toAjax(notificationService.markAsRead(id, receiverId));
    }
    
    /**
     * 批量标记为已读
     */
    @PreAuthorize("@ss.hasPermi('notification:edit')")
    @Log(title = "通知管理", businessType = BusinessType.UPDATE)
    @PutMapping("/batch-read")
    public AjaxResult markBatchAsRead(@RequestBody Long[] ids) {
        Long receiverId = SecurityUtils.getUserId();
        return toAjax(notificationService.markBatchAsRead(ids, receiverId));
    }
    
    /**
     * 标记全部为已读
     */
    @PreAuthorize("@ss.hasPermi('notification:edit')")
    @Log(title = "通知管理", businessType = BusinessType.UPDATE)
    @PutMapping("/all-read")
    public AjaxResult markAllAsRead() {
        Long receiverId = SecurityUtils.getUserId();
        return toAjax(notificationService.markAllAsRead(receiverId));
    }
    
    /**
     * 删除通知
     */
    @PreAuthorize("@ss.hasPermi('notification:remove')")
    @Log(title = "通知管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id) {
        Long receiverId = SecurityUtils.getUserId();
        return toAjax(notificationService.deleteNotification(id, receiverId));
    }
    
    /**
     * 批量删除通知
     */
    @PreAuthorize("@ss.hasPermi('notification:remove')")
    @Log(title = "通知管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/batch-delete")
    public AjaxResult batchRemove(@RequestBody Long[] ids) {
        Long receiverId = SecurityUtils.getUserId();
        return toAjax(notificationService.deleteBatchNotification(ids, receiverId));
    }
    
    // ========== 模板管理接口 ==========
    
    /**
     * 查询通知模板列表
     */
    @PreAuthorize("@ss.hasPermi('notification:template:list')")
    @GetMapping("/template/list")
    public TableDataInfo templateList(NotificationTemplate template) {
        startPage();
        List<NotificationTemplate> list = notificationService.selectTemplateList(template);
        return getDataTable(list);
    }
    
    /**
     * 根据ID获取模板详情
     */
    @PreAuthorize("@ss.hasPermi('notification:template:query')")
    @GetMapping(value = "/template/{id}")
    public AjaxResult getTemplateInfo(@PathVariable Long id) {
        return success(notificationService.selectTemplateById(id));
    }
    
    /**
     * 新增通知模板
     */
    @PreAuthorize("@ss.hasPermi('notification:template:add')")
    @Log(title = "通知模板", businessType = BusinessType.INSERT)
    @PostMapping("/template")
    public AjaxResult addTemplate(@Validated @RequestBody NotificationTemplate template) {
        template.setCreateBy(getUsername());
        return toAjax(notificationService.insertTemplate(template));
    }
    
    /**
     * 修改通知模板
     */
    @PreAuthorize("@ss.hasPermi('notification:template:edit')")
    @Log(title = "通知模板", businessType = BusinessType.UPDATE)
    @PutMapping("/template")
    public AjaxResult editTemplate(@Validated @RequestBody NotificationTemplate template) {
        template.setUpdateBy(getUsername());
        return toAjax(notificationService.updateTemplate(template));
    }
    
    /**
     * 删除通知模板
     */
    @PreAuthorize("@ss.hasPermi('notification:template:remove')")
    @Log(title = "通知模板", businessType = BusinessType.DELETE)
    @DeleteMapping("/template/{ids}")
    public AjaxResult removeTemplate(@PathVariable Long[] ids) {
        return toAjax(notificationService.deleteTemplateByIds(ids));
    }
}