package com.tourism.webadmin.back.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.page.PageMethod;
import com.tourism.common.core.base.dao.BaseDaoMapper;
import com.tourism.common.core.base.service.BaseService;
import com.tourism.common.core.constant.GlobalDeletedFlag;
import com.tourism.common.core.object.MyRelationParam;
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.sequence.wrapper.IdGeneratorWrapper;
import com.tourism.webadmin.app.website.dto.TravelNotesCommentToWebDto;
import com.tourism.webadmin.back.dao.TourTravelNotesCommentMapper;
import com.tourism.webadmin.back.model.TourTravelNotesComment;
import com.tourism.webadmin.back.model.constant.TravelNotesCommentType;
import com.tourism.webadmin.back.service.TourTravelNotesCommentService;
import com.tourism.webadmin.back.service.TourismProjectTravelNotesWriteService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 游记评论数据操作服务类。
 *
 * @author 吃饭睡觉
 * @date 2024-09-06
 */
@Slf4j
@Service("tourTravelNotesCommentService")
public class TourTravelNotesCommentServiceImpl extends BaseService<TourTravelNotesComment, Long> implements TourTravelNotesCommentService {

    @Autowired
    private IdGeneratorWrapper idGenerator;
    @Autowired
    private TourTravelNotesCommentMapper tourTravelNotesCommentMapper;
    @Autowired
    private TourismProjectTravelNotesWriteService tourismProjectTravelNotesWriteService;

    /**
     * 返回当前Service的主表Mapper对象。
     *
     * @return 主表Mapper对象。
     */
    @Override
    protected BaseDaoMapper<TourTravelNotesComment> mapper() {
        return tourTravelNotesCommentMapper;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public TourTravelNotesComment saveNew(TourTravelNotesComment tourTravelNotesComment) {
        tourTravelNotesCommentMapper.insert(this.buildDefaultValue(tourTravelNotesComment));
        return tourTravelNotesComment;
    }

    @Override
    public TourTravelNotesComment saveNewComment(TourTravelNotesComment tourTravelNotesComment) {
        // 判断有没有父节点id
        // 验证父Id的数据合法性
        TourTravelNotesComment parentTourTravelNotesComment;
        // 如果是没有回复ID，那么肯定是一级评论，什么都不用改，直接保存即可
        // 但是回复ID如果不是空的，那么这里肯定是第二级评论
        if (MyCommonUtil.isNotBlankOrNull(tourTravelNotesComment.getReplyCommentId())) {
            // 查看回复的评论在不在，如果不在，报错
            parentTourTravelNotesComment = this.getById(tourTravelNotesComment.getReplyCommentId());
            if(parentTourTravelNotesComment == null){
                throw new RuntimeException("回复的评论不存在!");
            }
            // 回复的评论信息，如果parent_id为空，则是第一条评论,把回复的评论ID作为parent_id，
            // 如果parent_id不是空，就拿他的parent_id
            if(MyCommonUtil.isNotBlankOrNull(parentTourTravelNotesComment.getParentId())){
                tourTravelNotesComment.setParentId(parentTourTravelNotesComment.getParentId());
            }else{
                tourTravelNotesComment.setParentId(parentTourTravelNotesComment.getId());
            }
            tourTravelNotesComment.setReplyUserId(parentTourTravelNotesComment.getCreateUserId());
        }
        tourTravelNotesComment.setCommentUserId(TokenData.takeFromRequest().getUserId());
        parentTourTravelNotesComment = this.saveNew(tourTravelNotesComment);
        return parentTourTravelNotesComment;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveNewBatch(List<TourTravelNotesComment> tourTravelNotesCommentList) {
        if (CollUtil.isNotEmpty(tourTravelNotesCommentList)) {
            tourTravelNotesCommentList.forEach(this::buildDefaultValue);
            tourTravelNotesCommentMapper.insertList(tourTravelNotesCommentList);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean update(TourTravelNotesComment tourTravelNotesComment, TourTravelNotesComment originalTourTravelNotesComment) {
        MyModelUtil.fillCommonsForUpdate(tourTravelNotesComment, originalTourTravelNotesComment);
        // 这里重点提示，在执行主表数据更新之前，如果有哪些字段不支持修改操作，请用原有数据对象字段替换当前数据字段。
        UpdateWrapper<TourTravelNotesComment> uw = this.createUpdateQueryForNullValue(tourTravelNotesComment, Long.parseLong(tourTravelNotesComment.getId()));
        return tourTravelNotesCommentMapper.update(tourTravelNotesComment, uw) == 1;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean remove(Long id) {
        return tourTravelNotesCommentMapper.deleteById(id) == 1;
    }

    @Override
    public List<TourTravelNotesComment> getTourTravelNotesCommentList(TourTravelNotesComment filter, String orderBy) {
        return tourTravelNotesCommentMapper.getTourTravelNotesCommentList(filter, orderBy);
    }

    @Override
    public List<TourTravelNotesComment> getTourTravelNotesCommentListWithRelation(TourTravelNotesComment filter, String orderBy) {
        List<TourTravelNotesComment> resultList = tourTravelNotesCommentMapper.getTourTravelNotesCommentList(filter, orderBy);
        // 在缺省生成的代码中，如果查询结果resultList不是Page对象，说明没有分页，那么就很可能是数据导出接口调用了当前方法。
        // 为了避免一次性的大量数据关联，规避因此而造成的系统运行性能冲击，这里手动进行了分批次读取，开发者可按需修改该值。
        int batchSize = resultList instanceof Page ? 0 : 1000;
        this.buildRelationForDataList(resultList, MyRelationParam.normal(), batchSize);
        return resultList;
    }

    @Override
    public boolean hasChildren(Long id) {
        TourTravelNotesComment filter = new TourTravelNotesComment();
        filter.setParentId(String.valueOf(id));
        return getCountByFilter(filter) > 0;
    }

    @Override
    public boolean deleteChildrenComment(Long id) {
        return tourTravelNotesCommentMapper.deleteChildrenComment(id);
    }

    private TourTravelNotesComment buildDefaultValue(TourTravelNotesComment tourTravelNotesComment) {
        if (tourTravelNotesComment.getId() == null) {
            tourTravelNotesComment.setId(idGenerator.nextStringId());
        }
        MyModelUtil.fillCommonsForInsert(tourTravelNotesComment);
        tourTravelNotesComment.setDataState(GlobalDeletedFlag.NORMAL);
        return tourTravelNotesComment;
    }

    @Override
    public List<TourTravelNotesComment> getMyTravelNoteComments(TravelNotesCommentToWebDto dto) {
        // 构建IPage分页参数
//        IPage<TourTravelNotesComment> page = new IPage<TourTravelNotesComment>(dto.getPageNum(), dto.getPageSize());
//
//        Page<TourTravelNotesComment> page = new Page<>(dto.getPageNum(), dto.getPageSize());

        // 获取当前登录用户id
        TokenData tokenData = TokenData.takeFromRequest();
        Long userId = tokenData.getUserId();
        // 查询我的游记id（List<Long>）
        List<Long> myTravelNoteIds = tourismProjectTravelNotesWriteService.getMyTravelNoteIds(userId);

        LambdaQueryWrapper<TourTravelNotesComment> queryWrapper = new LambdaQueryWrapper<>();
        Long[] noteIds = myTravelNoteIds.toArray(new Long[myTravelNoteIds.size()]);
        // 如果没有写过游记，随便给个值应付一下，因为这里如果到表达式里去处理太麻烦了，且不易懂
        if(noteIds == null || noteIds.length == 0) {
            noteIds = new Long[]{0L};
        }
        Long[] finalNoteIds = noteIds;
        // 查询收到的评论，我的游记评论和直接回复我的评论
        // 查询发出的评论，create_user = userId
        if(dto.getCommentType() == TravelNotesCommentType.ALL_COMMENTS){
            queryWrapper.and(
                    i->i
                            .or(j->j.in(TourTravelNotesComment::getTravelNoteId, finalNoteIds))
                            .or(j->j.eq(TourTravelNotesComment::getReplyUserId, userId))
                            .or(j->j.eq(TourTravelNotesComment::getCreateUserId, userId))
            );
        }else if(dto.getCommentType() == TravelNotesCommentType.COMMENTS_POSTED){
            queryWrapper.eq(TourTravelNotesComment::getCreateUserId, userId);
        }else if(dto.getCommentType() == TravelNotesCommentType.RECEIVED_COMMENTS){
            queryWrapper.and(
                    i->i
                            .or(j->j.in(TourTravelNotesComment::getTravelNoteId, finalNoteIds))
                            .or(j->j.eq(TourTravelNotesComment::getReplyUserId, userId))
            );
            queryWrapper.ne(TourTravelNotesComment::getCreateUserId, userId);
        }
        queryWrapper.orderByDesc(TourTravelNotesComment::getUpdateTime);

        PageMethod.startPage(dto.getPageNum(), dto.getPageSize(), true);
        List<TourTravelNotesComment> resultList = tourTravelNotesCommentMapper.selectList(queryWrapper);
        int batchSize = resultList instanceof Page ? 0 : 1000;
        this.buildRelationForDataList(resultList, MyRelationParam.normal(), batchSize);
        return resultList;
    }
}
