package com.qnfhq.modules.c2c.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qnfhq.common.constant.Constant;
import com.qnfhq.common.page.PageData;
import com.qnfhq.common.service.impl.BaseServiceImpl;
import com.qnfhq.common.utils.MessageUtils;
import com.qnfhq.common.utils.Result;
import com.qnfhq.modules.c2c.dao.RatingsReviewsDao;
import com.qnfhq.modules.c2c.entity.RatingsReviewsEntity;
import com.qnfhq.modules.c2c.service.RatingsReviewsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Map;
import java.util.Objects;

/**
 * c2c交易对象评价
 *
 * @author yelz 30262728@qq.com
 * @since 1.0.0 2025-11-29
 */
@Service
public class RatingsReviewsServiceImpl extends BaseServiceImpl<RatingsReviewsDao, RatingsReviewsEntity> implements RatingsReviewsService {

    @Override
    public RatingsReviewsEntity selectByOrderIdInputUserId(Long orderId, Long inputUserId) {
        return baseDao.selectOne(new LambdaQueryWrapper<RatingsReviewsEntity>()
                .eq(RatingsReviewsEntity::getOrderId, orderId)
                .eq(RatingsReviewsEntity::getInputUserId, inputUserId));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result create(RatingsReviewsEntity entity) throws Exception {
        if(baseDao.insert(entity)<0) {
            throw new Exception(MessageUtils.message("c2c.reviews.save.fail"));//评价保存失败
        }
        return new Result();
    }


    @Override
    public PageData<RatingsReviewsEntity> selectPageByUserId(Map<String, Object> params) {
        Long userId = (Long)params.get("userId");
        Integer rating = null;
        if(Objects.nonNull(params.get("rating"))) {
            rating = (Integer) params.get("rating");
        }

        LambdaQueryWrapper<RatingsReviewsEntity> wrapper = new LambdaQueryWrapper<RatingsReviewsEntity>()
                .eq(Objects.nonNull(userId),RatingsReviewsEntity::getUserId, userId)
                .eq(Objects.nonNull(rating),RatingsReviewsEntity::getRating, rating);

        IPage<RatingsReviewsEntity> page = baseDao.selectPage(
                getPage(params, (String)params.get(Constant.ORDER_FIELD), "asc".equals(params.get(Constant.ORDER)) ? true : false),
                wrapper
        );
        return getPageData(page, RatingsReviewsEntity.class);
    }
}