package org.dromara.mall.trade.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.mall.trade.domain.MallOrderEvaluate;
import org.dromara.mall.trade.domain.bo.MallOrderEvaluateBo;
import org.dromara.mall.trade.domain.vo.MallOrderEvaluateVo;
import org.dromara.mall.trade.mapper.MallOrderEvaluateMapper;
import org.dromara.mall.trade.service.MallOrderEvaluateService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * 订单评价Service业务层处理
 *
 * @author pengles
 */
@RequiredArgsConstructor
@Service
public class MallOrderEvaluateServiceImpl implements MallOrderEvaluateService {

    private final MallOrderEvaluateMapper baseMapper;

    /**
     * 查询订单评价
     */
    @Override
    public MallOrderEvaluateVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询订单评价列表
     */
    @Override
    public TableDataInfo<MallOrderEvaluateVo> queryPageList(MallOrderEvaluateBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<MallOrderEvaluate> lqw = buildQueryWrapper(bo);
        Page<MallOrderEvaluateVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询订单评价列表
     */
    @Override
    public List<MallOrderEvaluateVo> queryList(MallOrderEvaluateBo bo) {
        LambdaQueryWrapper<MallOrderEvaluate> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<MallOrderEvaluate> buildQueryWrapper(MallOrderEvaluateBo bo) {
        LambdaQueryWrapper<MallOrderEvaluate> lqw = new LambdaQueryWrapper<>();
        lqw.eq(bo.getOrderId() != null, MallOrderEvaluate::getOrderId, bo.getOrderId());
        lqw.eq(StringUtils.isNotBlank(bo.getOrderNo()), MallOrderEvaluate::getOrderNo, bo.getOrderNo());
        lqw.eq(bo.getOrderItemId() != null, MallOrderEvaluate::getOrderItemId, bo.getOrderItemId());
        lqw.eq(bo.getProductId() != null, MallOrderEvaluate::getProductId, bo.getProductId());
        lqw.eq(bo.getSkuId() != null, MallOrderEvaluate::getSkuId, bo.getSkuId());
        lqw.eq(bo.getUserId() != null, MallOrderEvaluate::getUserId, bo.getUserId());
        lqw.eq(bo.getScore() != null, MallOrderEvaluate::getScore, bo.getScore());
        lqw.eq(bo.getStatus() != null, MallOrderEvaluate::getStatus, bo.getStatus());
        lqw.orderByDesc(MallOrderEvaluate::getCreateTime);
        return lqw;
    }

    /**
     * 新增订单评价
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(MallOrderEvaluateBo bo) {
        MallOrderEvaluate add = MapstructUtils.convert(bo, MallOrderEvaluate.class);
        validEntityBeforeSave(add);

        // 设置用户ID（移动端用户）
        if (add.getUserId() == null) {
            add.setUserId(LoginHelper.getUserId());
        }

        // 设置默认状态为待审核
        if (add.getStatus() == null) {
            add.setStatus(0);
        }

        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改订单评价
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(MallOrderEvaluateBo bo) {
        MallOrderEvaluate update = MapstructUtils.convert(bo, MallOrderEvaluate.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(MallOrderEvaluate entity) {
        // 可以添加业务校验逻辑
    }

    /**
     * 批量删除订单评价
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // 可以添加业务校验逻辑
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 审核评价（通过/驳回）
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean audit(Long id, Integer status) {
        MallOrderEvaluate evaluate = baseMapper.selectById(id);
        if (evaluate == null) {
            throw new ServiceException("评价不存在");
        }
        if (evaluate.getStatus() != 0) {
            throw new ServiceException("评价已审核，不能重复审核");
        }
        if (status == null || (status != 1 && status != 2)) {
            throw new ServiceException("审核状态不正确");
        }

        evaluate.setStatus(status);
        return baseMapper.updateById(evaluate) > 0;
    }

    /**
     * 回复评价（商家回复）
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean reply(Long id, String replyContent) {
        MallOrderEvaluate evaluate = baseMapper.selectById(id);
        if (evaluate == null) {
            throw new ServiceException("评价不存在");
        }
        if (evaluate.getStatus() != 1) {
            throw new ServiceException("只有已通过审核的评价才能回复");
        }

        evaluate.setReplyContent(replyContent);
        evaluate.setReplyTime(new Date());
        return baseMapper.updateById(evaluate) > 0;
    }

}
