/*
 * Copyright (c) 2018-2999 广州亚米信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.coupon.comment.service.impl;

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

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.yami.shop.coupon.comment.dao.CouponUseRecordMapper;
import com.yami.shop.coupon.comment.dao.CouponUserMapper;
import com.yami.shop.coupon.comment.model.CouponUseRecord;
import com.yami.shop.coupon.comment.model.CouponUser;
import com.yami.shop.coupon.comment.service.CouponUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


/**
 * @author lgh on 2018/12/27.
 */
@Service
public class CouponUserServiceImpl extends ServiceImpl<CouponUserMapper, CouponUser> implements CouponUserService {

    @Autowired
    private CouponUserMapper couponUserMapper;

    @Autowired
    private CouponUseRecordMapper couponUseRecordMapper;

//    @Override
//    public List<CouponUser> getCouponAndCouponUserByCouponUserIds(List<Long> couponUserIds) {
//        if (CollectionUtil.isEmpty(couponUserIds)) {
//            return Collections.emptyList();
//        }
//        return couponUserMapper.getCouponAndCouponUserByCouponUserIds(couponUserIds);
//    }

    @Override
    public void deleteUnValidTimeCoupons(Date date) {
        couponUserMapper.deleteUnValidTimeCoupons(date);
    }

    @Override
    public void updateStatusByTime(Date now) {
        couponUserMapper.updateStatusByTime(now);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelOrder(String userId, String orderNumber) {

        //查询订单所使用的优惠券列表
        List<CouponUseRecord> couponUseRecordList = couponUseRecordMapper.selectList(new LambdaQueryWrapper<CouponUseRecord>()
                .eq(CouponUseRecord::getUserId, userId)
                .eq(CouponUseRecord::getOrderNumber, orderNumber));
        if (CollectionUtils.isEmpty(couponUseRecordList)) {
            return;
        }
        List<Long> couponUseRecordIdList = Lists.newArrayList();
        List<Long> couponUserIds = Lists.newArrayList();
        for (CouponUseRecord couponUseRecord : couponUseRecordList) {
            couponUseRecordIdList.add(couponUseRecord.getCouponUseRecordId());
            couponUserIds.add(couponUseRecord.getCouponUserId());
        }

        //删除优惠券使用记录
        couponUseRecordMapper.deleteBatchIds(couponUseRecordIdList);

        //修改用户优惠券状态为可用状态
        couponUserMapper.batchUpdateUserCouponStatus(1, couponUserIds);
    }

}
