package com.jeesharp.business.member.controller;

import com.jeesharp.business.member.support.MemberLetterInboxMobileSupport;
import com.jeesharp.framework.memberauth.utils.MemberAuthUtils;
import com.jeesharp.framework.pojo.AjaxResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import com.jeesharp.framework.memberauth.web.BaseMobileController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 移动端消息通知接口（兼容文档路径 /member/message；数据来自 jeesharp-spring-boot-starter-letter 站内信）。
 *
 * @author jeesharp
 * @since 2026-05-08
 */
@Slf4j
@RestController
@RequestMapping("${jeesharp.web.mobilePath}/member/message")
@Tag(name = "移动端-消息通知", description = "消息列表、已读标记等接口")
@AllArgsConstructor
public class MessageMobileController extends BaseMobileController {

    private final MemberLetterInboxMobileSupport memberLetterInboxMobileSupport;

    @Operation(summary = "获取消息列表")
    @PostMapping("/list")
    public AjaxResult<Map<String, Object>> list(@RequestBody Map<String, Object> params) {
        String memberId = MemberAuthUtils.getLoginUserId();
        long pageNo = toLong(params.get("pageNo"), 1L);
        long pageSize = toLong(params.get("pageSize"), 10L);
        Integer type = parseMsgType(params.get("msgType"));
        if (type == null && params.get("messageType") != null) {
            type = toInt(params.get("messageType"));
        }

        Map<String, Object> raw =
                memberLetterInboxMobileSupport.list(memberId, pageNo, pageSize, type, null);

        Map<String, Object> data = new LinkedHashMap<>();
        data.put("pageNo", raw.get("page"));
        data.put("pageSize", raw.get("pageSize"));
        data.put("totalCount", raw.get("total"));
        data.put("list", raw.get("list"));
        data.put("unreadCount", raw.get("unreadCount"));
        return AjaxResult.okData(data);
    }

    @SuppressWarnings("unchecked")
    @Operation(summary = "获取未读消息数")
    @GetMapping("/unreadCount")
    public AjaxResult<Map<String, Object>> unreadCount() {
        String memberId = MemberAuthUtils.getLoginUserId();
        Map<String, Object> inner = memberLetterInboxMobileSupport.unreadSummary(memberId);
        Map<String, Object> data = new LinkedHashMap<>();
        data.put("total", inner.get("count"));
        Map<String, Long> by = (Map<String, Long>) inner.get("byType");
        if (by != null) {
            data.put("system", by.getOrDefault("1", 0L));
            data.put("order", by.getOrDefault("2", 0L));
            data.put("activity", by.getOrDefault("3", 0L));
        }
        return AjaxResult.okData(data);
    }

    @Operation(summary = "标记消息已读")
    @PostMapping("/read")
    public AjaxResult<Void> read(@RequestBody Map<String, Object> params) {
        String memberId = MemberAuthUtils.getLoginUserId();
        @SuppressWarnings("unchecked")
        List<String> messageIds = (List<String>) params.get("messageIds");
        if (messageIds != null) {
            for (String mid : messageIds) {
                memberLetterInboxMobileSupport.markRead(memberId, mid);
            }
        }
        log.debug("标记消息已读: memberId={}, messageIds={}", memberId, messageIds);
        return AjaxResult.ok("标记成功");
    }

    @Operation(summary = "全部标记已读")
    @PostMapping("/readAll")
    public AjaxResult<Void> readAll(@RequestBody(required = false) Map<String, Object> params) {
        String memberId = MemberAuthUtils.getLoginUserId();
        memberLetterInboxMobileSupport.markAllRead(memberId);
        log.debug("全部标记已读: memberId={}", memberId);
        return AjaxResult.ok("全部标记已读");
    }

    private static long toLong(Object v, long def) {
        if (v == null) {
            return def;
        }
        if (v instanceof Number n) {
            return n.longValue();
        }
        try {
            return Long.parseLong(v.toString());
        } catch (NumberFormatException ex) {
            return def;
        }
    }

    private static Integer toInt(Object v) {
        if (v == null) {
            return null;
        }
        if (v instanceof Number n) {
            return n.intValue();
        }
        try {
            return Integer.parseInt(v.toString());
        } catch (NumberFormatException ex) {
            return null;
        }
    }

    /**
     * 文档中的 msgType 字符串与站内信 type 数值映射。
     */
    private static Integer parseMsgType(Object raw) {
        if (raw == null) {
            return null;
        }
        String s = raw.toString().trim();
        if (s.isEmpty()) {
            return null;
        }
        if (s.matches("\\d+")) {
            return Integer.parseInt(s);
        }
        return switch (s.toUpperCase()) {
            case "SYSTEM" -> 1;
            case "ORDER", "TRADE", "BUSINESS" -> 2;
            case "ACTIVITY", "MARKETING" -> 3;
            default -> null;
        };
    }
}
