package com.ycwl.basic.service.mobile.impl;

import com.ycwl.basic.mapper.CouponMapper;
import com.ycwl.basic.mapper.CouponRecordMapper;
import com.ycwl.basic.model.pc.coupon.entity.CouponEntity;
import com.ycwl.basic.model.pc.couponRecord.entity.CouponRecordEntity;
import com.ycwl.basic.model.pc.face.entity.FaceEntity;
import com.ycwl.basic.repository.FaceRepository;
import com.ycwl.basic.service.mobile.AppCouponRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
public class AppCouponRecordServiceImpl implements AppCouponRecordService {
    
    @Autowired
    private CouponRecordMapper couponRecordMapper;
    
    @Autowired
    private CouponMapper couponMapper;
    @Autowired
    private FaceRepository faceRepository;

    @Override
    public List<CouponRecordEntity> queryByMemberIdAndFaceId(Long memberId, Long faceId) {
        return couponRecordMapper.queryByMemberIdAndFaceId(memberId, faceId);
    }
    
    @Override
    public CouponRecordEntity queryByMemberIdAndFaceIdAndType(Long memberId, Long faceId, Integer type) {
        return couponRecordMapper.queryByMemberIdAndFaceIdAndType(memberId, faceId, type);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CouponEntity claimCoupon(Long memberId, Long faceId, Integer type) {
        // 检查是否已经领取过该类型的优惠券
        CouponRecordEntity existingRecord = couponRecordMapper.queryByMemberIdAndFaceIdAndType(memberId, faceId, type);
        if (existingRecord != null) {
            throw new RuntimeException("该用户已经领取过此类型的优惠券");
        }
        FaceEntity face = faceRepository.getFace(faceId);
        if (face == null) {
            throw new RuntimeException("人脸数据不存在");
        }
        // 查找可用的优惠券
        Long scenicId = face.getScenicId();
        CouponEntity coupon = couponMapper.selectByScenicIdAndTypeAndStatus(scenicId, type, 1);
        
        if (coupon == null) {
            throw new RuntimeException("未找到可领取的优惠券");
        }
        
        // 创建优惠券记录
        CouponRecordEntity record = new CouponRecordEntity();
        record.setCouponId(coupon.getId());
        record.setMemberId(memberId);
        record.setFaceId(faceId);
        record.setStatus(0); // 有效状态
        record.setCreateTime(new Date());
        
        couponRecordMapper.insert(record);
        return coupon;
    }
}