package shop.alien.lawyer.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import shop.alien.entity.result.R;
import shop.alien.entity.store.vo.LifeNoticeVo;
import shop.alien.lawyer.service.LawyerNoticeService;

/**
 * 律师通知控制器
 *
 * @author system
 */
@Api(tags = {"律师模块-通知"})
@Slf4j
@RestController
@CrossOrigin
@RequestMapping("/lawyerNotice")
@RequiredArgsConstructor
public class LawyerNoticeController {

    private final LawyerNoticeService lawyerNoticeService;

    /**
     * 获取律师通知列表
     *
     * @param pageNum    页码，从1开始
     * @param pageSize   每页大小
     * @param receiverId 接收人ID
     * @param noticeType 通知类型：0-系统通知和订单提醒之外的类型，1-系统通知，2-订单提醒
     * @return 分页通知列表
     */
    @GetMapping("/list")
    @ApiOperation("律师通知列表")
    @ApiOperationSupport(order = 1)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", dataType = "Integer", paramType = "query", required = true, example = "1"),
            @ApiImplicitParam(name = "pageSize", value = "每页大小", dataType = "Integer", paramType = "query", required = true, example = "10"),
            @ApiImplicitParam(name = "receiverId", value = "接收人ID", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "noticeType", value = "通知类型：0-系统通知和订单提醒之外的类型，1-系统通知，2-订单提醒", dataType = "Integer", paramType = "query", example = "0")})
    public R<IPage<LifeNoticeVo>> getLawyerNoticeList(
            @RequestParam Integer pageNum,
            @RequestParam Integer pageSize,
            @RequestParam String receiverId,
            @RequestParam(defaultValue = "0") Integer noticeType) {
        log.info("LawyerNoticeController.getLawyerNoticeList, pageNum={}, pageSize={}, receiverId={}, noticeType={}", 
                pageNum, pageSize, receiverId, noticeType);
        
        // 参数校验
        if (pageNum == null || pageNum < 1) {
            log.warn("分页参数无效，pageNum={}", pageNum);
            return R.fail("页码必须大于0");
        }
        if (pageSize == null || pageSize < 1) {
            log.warn("分页参数无效，pageSize={}", pageSize);
            return R.fail("每页大小必须大于0");
        }
        if (StringUtils.isBlank(receiverId)) {
            log.warn("接收人ID为空");
            return R.fail("接收人ID不能为空");
        }
        if (noticeType == null || noticeType < 0) {
            log.warn("通知类型参数无效，noticeType={}", noticeType);
            return R.fail("通知类型参数无效");
        }
        
        return lawyerNoticeService.getLawyerNoticeList(pageNum, pageSize, receiverId, noticeType);
    }

    /**
     * 查询接收人是否有未读通知
     *
     * @param receiverId 接收人ID，不能为空
     * @return 是否有未读通知，true-有未读，false-无未读
     */
    @GetMapping("/hasUnread")
    @ApiOperation("查询是否有未读通知")
    @ApiOperationSupport(order = 2)
    @ApiImplicitParam(name = "receiverId", value = "接收人ID", dataType = "String", paramType = "query", required = true)
    public R<Boolean> hasUnreadNotice(@RequestParam String receiverId) {
        log.info("LawyerNoticeController.hasUnreadNotice, receiverId={}", receiverId);
        
        // 参数校验
        if (StringUtils.isBlank(receiverId)) {
            log.warn("接收人ID为空");
            return R.fail("接收人ID不能为空");
        }
        
        return lawyerNoticeService.hasUnreadNotice(receiverId);
    }
    /**
     * 标记通知为已读
     * <p>
     * 根据通知ID将指定通知标记为已读状态
     * </p>
     * <p>
     * 处理流程：
     * 1. 参数校验：通知ID必须大于0且不能为null
     * 2. 调用Service层方法执行更新操作
     * 3. 根据更新结果返回相应的响应
     * </p>
     *
     * @param id 通知ID，必须大于0且不能为null
     * @return 统一响应结果，true表示已读成功，false表示已读失败
     * @author system
     * @since 2025-01-XX
     */
    @GetMapping("/readNoticeById")
    @ApiOperation("通知已读")
    @ApiOperationSupport(order = 4)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "通知ID（主键id）", dataType = "Integer", paramType = "query", required = true)
    })
    public R<Boolean> readNoticeById(@RequestParam(value = "id", required = true) Integer id) {
        log.info("标记通知为已读请求开始，id={}", id);

        // 参数校验
        if (id == null || id <= 0) {
            log.warn("标记通知为已读请求失败：通知ID为空或无效，id={}", id);
            return R.fail("通知ID不能为空且必须大于0");
        }

        try {
            // 调用Service层方法执行更新
            int affectedRows = lawyerNoticeService.readNoticeById(id);

            // 根据更新结果返回响应
            if (affectedRows > 0) {
                log.info("标记通知为已读请求成功，id={}，受影响记录数={}", id, affectedRows);
                return R.success("已读成功");
            } else {
                log.warn("标记通知为已读请求失败，id={}，受影响记录数={}，可能是通知不存在或已被删除", id, affectedRows);
                return R.fail("已读失败，通知不存在或已被删除");
            }
        } catch (IllegalArgumentException e) {
            log.warn("标记通知为已读请求参数校验失败，id={}，错误信息：{}", id, e.getMessage());
            return R.fail(e.getMessage());
        } catch (RuntimeException e) {
            log.error("标记通知为已读请求异常，id={}，异常信息：{}", id, e.getMessage(), e);
            return R.fail("标记通知为已读失败：" + e.getMessage());
        } catch (Exception e) {
            log.error("标记通知为已读请求未知异常，id={}，异常信息：{}", id, e.getMessage(), e);
            return R.fail("标记通知为已读失败，请稍后重试");
        }
    }
}