package com.cyl.h5.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyl.manager.marketing.domain.WechatStock;
import com.cyl.manager.marketing.mapper.WechatStockMapper;
import com.cyl.manager.marketing.pojo.SendCouponRequest;
import com.cyl.manager.marketing.service.IWechatMemberCouponService;
import com.cyl.manager.ums.domain.Member;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Transactional
public class H5CouponService {

    @Autowired
    private WechatStockMapper wechatStockMapper;

    @Autowired
    private IWechatMemberCouponService wechatMemberCouponService;

    public List<WechatStock> selectWechatStockList(WechatStock wechatStock) {
        return wechatStockMapper.selectList2(wechatStock);
    }

    /**
     * 小程序查询待领取的优惠券列表
     * @param member
     * @return
     */
    public List<WechatStock> selectWechatStocktForGet(Member member) {
        QueryWrapper<WechatStock> qw = new QueryWrapper<>();
        qw.eq("send_type", "MANUAL");
        qw.ge("available_end_time", LocalDateTime.now());
        qw.le("available_begin_time", LocalDateTime.now());
        qw.lambda().orderByDesc(WechatStock::getCreateTime);
        return wechatStockMapper.selectList(qw);
    }

    public WechatStock selectWechatStockByName(String name) {
        QueryWrapper<WechatStock> dd = new QueryWrapper<>();
//        dd.eq("del_flag",0);
        dd.eq("stock_name",name);

        return wechatStockMapper.selectOne(dd);
    }

    public int sendCoupon(SendCouponRequest sendCouponRequest) {
        return wechatMemberCouponService.sendCoupon(sendCouponRequest);
    }

    public WechatStock getNewUserCoupon() {
        List<WechatStock> wechatStocks = wechatStockMapper.selectList(Wrappers.<WechatStock>lambdaQuery()
                .eq(WechatStock::getSendType, "newUser")
                .ge(WechatStock::getAvailableEndTime, LocalDateTime.now())
                .le(WechatStock::getAvailableBeginTime, LocalDateTime.now())
        );
        if (wechatStocks.size() > 0){
            return wechatStocks.get(0);
        }
        return null;
    }
}
