package com.czg.service.market.service.impl;

import com.czg.PageQueryParam;
import com.czg.account.dto.user.userinfo.UserInfoDTO;
import com.czg.account.service.UserInfoService;
import com.czg.exception.CzgException;
import com.czg.market.dto.PpHelpRecordDTO;
import com.czg.market.entity.PpHelpRecord;
import com.czg.market.service.PpHelpRecordService;
import com.czg.service.market.mapper.PpHelpRecordMapper;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 套餐推广助力记录 服务层实现。
 *
 * @author gyj
 * @since 2025-12-18
 */
@Service
public class PpHelpRecordServiceImpl extends ServiceImpl<PpHelpRecordMapper, PpHelpRecord> implements PpHelpRecordService {

    @DubboReference
    private UserInfoService userInfoService;

    @Override
    public boolean canHelp(Long userId, Long orderId) {
        return !exists(QueryWrapper.create().eq(PpHelpRecord::getUserId, userId).eq(PpHelpRecord::getOrderId, orderId));
    }

    @Override
    public boolean help(Long userId, Long orderId) {
        if (!canHelp(userId, orderId)) {
            return false;
        }
        UserInfoDTO info = userInfoService.getInfo(userId);
        if (info == null) {
            throw new CzgException("用户不存在");
        }
        PpHelpRecord helpRecord = new PpHelpRecord()
                .setOrderId(orderId)
                .setUserId(userId)
                .setUserName(info.getNickName())
                .setUserAvator(info.getHeadImg());
        return save(helpRecord);
    }

    @Override
    @Transactional
    public void removeHelpRecord(Long orderId) {
        remove(QueryWrapper.create().eq(PpHelpRecord::getOrderId, orderId));
    }

    @Override
    public void deleteByOrderIds(List<Long> orderIds) {
        remove(QueryWrapper.create().in(PpHelpRecord::getOrderId, orderIds));
    }

    @Override
    public Page<PpHelpRecordDTO> helpPage(PageQueryParam reqVo) {
        QueryWrapper wrapper = QueryWrapper.create().eq(PpHelpRecord::getOrderId, reqVo.getRecordId());
        return pageAs(new Page<>(reqVo.getPage(), reqVo.getSize()), wrapper, PpHelpRecordDTO.class);
    }
}
