package com.tourism.webadmin.app.website.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.tourism.common.additional.config.ApplicationConfig;
import com.tourism.common.additional.utils.UrlConvertUtils;
import com.tourism.common.core.annotation.MyRequestBody;
import com.tourism.common.core.constant.ErrorCodeEnum;
import com.tourism.common.core.object.MyOrderParam;
import com.tourism.common.core.object.MyPageData;
import com.tourism.common.core.object.ResponseResult;
import com.tourism.common.core.object.TokenData;
import com.tourism.common.core.util.MyCommonUtil;
import com.tourism.common.core.util.MyModelUtil;
import com.tourism.common.core.util.MyPageUtil;
import com.tourism.common.log.annotation.OperationLog;
import com.tourism.common.log.model.constant.SysOperationLogType;
import com.tourism.webadmin.app.website.dto.TravelNotesCommentToWebDto;
import com.tourism.webadmin.back.dto.TourTravelNotesCommentDto;
import com.tourism.webadmin.back.model.TourTravelNotesComment;
import com.tourism.webadmin.back.service.TourTravelNotesCommentService;
import com.tourism.webadmin.back.vo.TourTravelNotesCommentVo;
import com.tourism.webadmin.back.vo.TourismProjectTravelNotesWriteVo;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

/**
 * 游记评论操作控制器类。
 *
 * @author 吃饭睡觉
 * @date 2024-09-06
 */
@Tag(name = "游记评论门户接口")
@Slf4j
@RestController
@RequestMapping("/website/comment/tourTravelNotesComment")
public class TravelNotesCommentController {

    @Autowired
    private TourTravelNotesCommentService tourTravelNotesCommentService;
    @Autowired
    private ApplicationConfig applicationConfig;

    /**
     * 新增游记评论数据。
     *
     * @param tourTravelNotesCommentDto 新增对象。
     * @return 应答结果对象，包含新增对象主键Id。
     */
    @ApiOperationSupport(ignoreParameters = {"tourTravelNotesCommentDto.id"})
    @OperationLog(type = SysOperationLogType.ADD)
    @PostMapping("/add")
    public ResponseResult<String> add(@RequestBody TourTravelNotesCommentDto tourTravelNotesCommentDto){
        String errorMessage = MyCommonUtil.getModelValidationError(tourTravelNotesCommentDto, false);
        if (errorMessage != null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, errorMessage);
        }
        TourTravelNotesComment tourTravelNotesComment = MyModelUtil.copyTo(tourTravelNotesCommentDto, TourTravelNotesComment.class);
        tourTravelNotesCommentService.saveNewComment(tourTravelNotesComment);

        return ResponseResult.success(tourTravelNotesComment.getId());
    }

    /**
     * 删除游记评论数据。
     *
     * @param id 删除对象主键Id。
     * @return 应答结果对象。
     */
    @OperationLog(type = SysOperationLogType.DELETE)
    @PostMapping("/delete")
    public ResponseResult<Void> delete(@MyRequestBody Long id) {
        if (MyCommonUtil.existBlankArgument(id)) {
            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST);
        }
        return this.doDelete(id);
    }

    /**
     * 列出符合过滤条件的游记评论列表。
     *
     * @param dto 过滤对象、排序参数、分页参数。
     * @return 应答结果对象，包含查询结果集。
     */
    @SaIgnore
    @GetMapping("/list")
    public ResponseResult<List<TourTravelNotesCommentVo>> list(TravelNotesCommentToWebDto dto) {
//        if (dto != null) {
//            PageMethod.startPage(dto.getPageNum(), dto.getPageSize(), dto.getCount());
//        }
        TourTravelNotesComment tourTravelNotesCommentFilter = MyModelUtil.copyTo(dto, TourTravelNotesComment.class);
        tourTravelNotesCommentFilter.setTravelNoteId(Long.valueOf(dto.getTravelNoteId()));

        MyOrderParam myOrderParam = new MyOrderParam();
        myOrderParam.add(new MyOrderParam.OrderInfo("createTime",true,null));
        String orderBy = MyOrderParam.buildOrderBy(myOrderParam, TourTravelNotesComment.class);
        List<TourTravelNotesComment> commentList =
                tourTravelNotesCommentService.getTourTravelNotesCommentListWithRelation(tourTravelNotesCommentFilter, orderBy);
        // commentList转为TourTravelNotesCommentVo类型list
        List<TourTravelNotesCommentVo> commentVoList = MyModelUtil.copyCollectionTo(commentList, TourTravelNotesCommentVo.class);

        TokenData tokenData = TokenData.takeFromRequest();
        if(TokenData.takeFromRequest() != null) {
            // 评论是否为当前用户
            List<TourTravelNotesCommentVo> commentVos = commentVoList.stream().filter(e -> e.getCreateUserId().equals(tokenData.getUserId())).toList();
            commentVos.forEach(e -> {
                e.setSelf(true);
            });
        }

        // 一级评论和二级评论分开
        List<TourTravelNotesCommentVo> firstCommentList = commentVoList.stream().filter(e->e.getParentId() == null).toList();
        List<TourTravelNotesCommentVo> secondCommentList = commentVoList.stream().filter(e->e.getParentId() != null).toList();
        // 二级评论做map数据
        Map<String, List<TourTravelNotesCommentVo>> collect = secondCommentList.stream().collect(Collectors.groupingBy(e -> e.getParentId()));
        // 作为子评论追加到一级评论
        firstCommentList.forEach(e->{
            List<TourTravelNotesCommentVo> childList = collect.get(e.getId());
            if(childList != null && childList.size() > 0){
                e.setChildrenList(childList);
            }
        });

        return ResponseResult.success(firstCommentList);
    }

    /**
     * 我的评论
     * @param dto
     * @return
     */
//    @SaIgnore
    @GetMapping("/my-comments")
    public ResponseResult<MyPageData<TourTravelNotesCommentVo>> myComments(TravelNotesCommentToWebDto dto) {
        if(dto.getCommentType() == null){
            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST);
        }

        List<TourTravelNotesComment> list = tourTravelNotesCommentService.getMyTravelNoteComments(dto);
        list.forEach(e->{
            Map<String, Object> travelNoteDictMap = e.getTravelNoteDictMap();
            String url = null;
            if(travelNoteDictMap != null){
                url = (String)travelNoteDictMap.get("name");
            }
            e.setTravelNoteUrl(UrlConvertUtils.urlConvertSingle(applicationConfig.getHostIpPort(), url));
        });
        MyPageData<TourTravelNotesCommentVo> tourTravelNotesCommentVoMyPageData = MyPageUtil.makeResponseData(list, TourTravelNotesCommentVo.class);
        return ResponseResult.success(tourTravelNotesCommentVoMyPageData);
    }

    private ResponseResult<Void> doDelete(Long id) {
        String errorMessage;
        // 验证关联Id的数据合法性
        TourTravelNotesComment comment = tourTravelNotesCommentService.getById(id);
        if (comment == null) {
            errorMessage = "数据验证失败，当前评论并不存在，请刷新后重试！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        if (!tourTravelNotesCommentService.remove(id)) {
            errorMessage = "数据操作失败，删除的对象不存在，请刷新后重试！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        // 删除评论后，判断是不是一级评论，如果是，则删除子评论
        if (MyCommonUtil.isBlankOrNull(comment.getParentId())) {
            tourTravelNotesCommentService.deleteChildrenComment(Long.parseLong(comment.getId()));
        }
        return ResponseResult.success();
    }
}
