package io.controller;

import io.annotation.Login;
import io.common.constant.Constant;
import io.common.utils.Result;
import io.common.validator.ValidatorUtils;
import io.common.validator.group.AddGroup;
import io.common.validator.group.DefaultGroup;
import io.entity.UserEntity;
import io.modules.item.dao.FrontUserDao;
import io.modules.item.dto.CommentDTO;
import io.modules.item.entity.FrontUserEntity;
import io.modules.item.service.CommentService;
import io.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 评论表
 */
@RestController
@RequestMapping("/api/comment")
@AllArgsConstructor
@Tag(name="在线咨询表")
@CrossOrigin
public class CommentController {
    private final CommentService commentService;
    private final UserService userService;
    @Autowired
    private FrontUserDao frontUserDao;


    @GetMapping("page")
    @Operation(summary = "分页")
    @Parameters({
        @Parameter(name = Constant.PAGE, description = "当前页码，从1开始", in = ParameterIn.QUERY, required = true, ref="int") ,
        @Parameter(name = Constant.LIMIT, description = "每页显示记录数", in = ParameterIn.QUERY,required = true, ref="int") ,
        @Parameter(name = Constant.ORDER_FIELD, description = "排序字段", in = ParameterIn.QUERY, ref="String") ,
        @Parameter(name = Constant.ORDER, description = "排序方式，可选值(asc、desc)", in = ParameterIn.QUERY, ref="String"),
        @Parameter(name = "itemId", description = "关联编号", in = ParameterIn.QUERY, ref="String")
    })
    public Result<List<CommentDTO>> page(@Parameter(hidden = true) @RequestParam Map<String, Object> params){
        List<CommentDTO> page = commentService.list(params);
        List<CommentDTO> updatedPage = page.stream()
                .map(comment -> {
                    Long userId = comment.getUserId();
                    // 如果缓存中已经存在该用户的信息，直接使用
                    UserEntity userInfo = userService.getUserByUserId(userId);
                    if (userInfo != null) {
                        // 否则调用 userService 获取用户信息并缓存
                        String nickName = userService.getUserByUserId(userId).getNickName();
                        comment.setNickName(nickName);  // 设置昵称
                    }
                    return comment;
                })
                .collect(Collectors.toList());
        return new Result<List<CommentDTO>>().ok(updatedPage);
    }

    @GetMapping("listUser")
    @Operation(summary = "医生在线沟通-查询用户")
    public Result< List<FrontUserEntity>> list(@Parameter(hidden = true) @RequestParam Map<String, Object> params){
        //获取医生下面的所有消息
        List<CommentDTO> list = commentService.list(params);

        //取出所有用户
        List<Long> userIds = list.stream()
                .filter(comment -> comment.getUserId() != null)  // 过滤掉 null 的 userId
                .collect(Collectors.toMap(
                        CommentDTO::getUserId,  // 根据 userId 作为键
                        CommentDTO::getUserId,  // 值为 userId
                        (existing, replacement) -> existing  // 如果 userId 相同，保留已有的值
                ))
                .values()
                .stream()
                .collect(Collectors.toList());
        if (userIds.isEmpty()){
            return new Result<List<FrontUserEntity>>().ok(new ArrayList<>());
        }
        List<FrontUserEntity> userEntities = frontUserDao.selectBatchIds(userIds);
        return new Result< List<FrontUserEntity>>().ok(userEntities);
    }
    @GetMapping("listmsg")
    @Operation(summary = "医生在线沟通-查询消息")

    public Result< List<CommentDTO>> msg(@Parameter(hidden = true) @RequestParam Map<String, Object> params){

        //获取医生下面的所有消息
        List<CommentDTO> list = commentService.list(params);
        return new Result<List<CommentDTO>>().ok(list);
    }

    @PostMapping("send")
    @Operation(summary = "send")
    public Result send(@RequestBody CommentDTO dto){
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
        commentService.save(dto);
        return new Result();
    }

    @GetMapping("list")
    @Operation(summary = "列表")
    @Parameters({
            @Parameter(name = Constant.PAGE, description = "当前页码，从1开始", in = ParameterIn.QUERY, required = true, ref="int") ,
            @Parameter(name = Constant.LIMIT, description = "每页显示记录数", in = ParameterIn.QUERY,required = true, ref="int") ,
            @Parameter(name = Constant.ORDER_FIELD, description = "排序字段", in = ParameterIn.QUERY, ref="String") ,
            @Parameter(name = Constant.ORDER, description = "排序方式，可选值(asc、desc)", in = ParameterIn.QUERY, ref="String"),
            @Parameter(name = "itemId", description = "关联编号", in = ParameterIn.QUERY, ref="String"),
            @Parameter(name = "userId", description = "关联编号", in = ParameterIn.QUERY, ref="String")
    })
    @Login
    public Result<List<CommentDTO>> list(@Parameter(hidden = true) @RequestParam Map<String, Object> params,@Parameter(hidden = true) @RequestAttribute("userId") Long userId){
       params.put("userId",String.valueOf(userId));
        List<CommentDTO> page = commentService.list(params);
        List<CommentDTO> updatedPage = page.stream()
                .map(comment -> {
                    // 如果缓存中已经存在该用户的信息，直接使用
                    UserEntity userInfo = userService.getUserByUserId(comment.getUserId());
                    if (userInfo != null) {
                        // 否则调用 userService 获取用户信息并缓存
                        String nickName = userService.getUserByUserId(comment.getUserId()).getNickName();
                        comment.setNickName(nickName);  // 设置昵称
                    }
                    return comment;
                })
                .collect(Collectors.toList());
        return new Result<List<CommentDTO>>().ok(updatedPage);
    }



    @Login
    @PostMapping
    @Operation(summary = "保存")
    public Result save(@RequestBody CommentDTO dto,@Parameter(hidden = true) @RequestAttribute("userId") Long userId){
        //效验数据
        dto.setUserId(userId);
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
        commentService.save(dto);
        return new Result();
    }
//
//
//    @DeleteMapping
//    @Operation(summary = "删除")
//    @LogOperation("删除")
//    @RequiresPermissions("item:comment:delete")
//    public Result delete(@RequestBody Long[] ids){
//        //效验数据
//        AssertUtils.isArrayEmpty(ids, "id");
//
//        commentService.delete(ids);
//
//        return new Result();
//    }


}
