package com.cyl.h5.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyl.h5.config.SecurityUtil;
import com.cyl.h5.pojo.request.H5MemberCouponGetRequest;
import com.cyl.h5.pojo.request.H5MemberCouponRequest;
import com.cyl.h5.pojo.response.WechatMemberCouponResponse;
import com.cyl.h5.service.H5CouponService;
import com.cyl.h5.service.H5MemberCouponService;
import com.cyl.manager.marketing.domain.WechatMemberCoupon;
import com.cyl.manager.marketing.domain.WechatStock;
import com.cyl.manager.marketing.mapper.WechatMemberCouponMapper;
import com.cyl.manager.marketing.pojo.SendCouponRequest;
import com.cyl.manager.oms.domain.OmsOrderService;
import com.cyl.manager.oms.domain.Order;
import com.cyl.manager.oms.mapper.OmsOrderServiceMapper;
import com.cyl.manager.oms.mapper.OrderMapper;
import com.cyl.manager.ums.domain.Member;
import com.cyl.manager.ums.service.MemberService;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 商家券
 * 
 * @author daixiande
 * @date 2024-05-06
 */
//@Api("商家券")
@RestController
@RequestMapping("/h5/coupon")
@Slf4j
public class H5CouponController extends BaseController
{
    @Autowired
    private H5CouponService h5CouponService;

    @Autowired
    private H5MemberCouponService h5MemberCouponService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private WechatMemberCouponMapper wechatMemberCouponMapper;

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 查询商家券列表
     */
//    @ApiOperation("查询商家券列表")
    @GetMapping("/list")
    public AjaxResult list()
    {
        startPage();
        WechatStock ws = new WechatStock();

        Member member = null;
        try {
            member = SecurityUtil.getLocalMember();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("【优惠券领取】当前用户未登录");
        }

        List<WechatStock> list = h5CouponService.selectWechatStocktForGet(member);

        // TODO 判断当前用户是否是新人，如果是就查询新人优惠劵
        Integer integer = orderMapper.selectCount(Wrappers.
                <Order>lambdaQuery()
                .eq(Order::getMemberId, member.getId()));
//        if (integer == 0){
            //新用户
            WechatStock newUserCoupon = h5CouponService.getNewUserCoupon();
            if (newUserCoupon != null){
                list.add(0, newUserCoupon);
            }
//        }

        for (WechatStock stock : list) {
            stock.setAlreadyReceived(wechatMemberCouponMapper.selectCount(
                    Wrappers.<WechatMemberCoupon>lambdaQuery()
                            .eq(WechatMemberCoupon::getMemberId, member.getId())
                            .eq(WechatMemberCoupon::getStockId, stock.getStockId())
            ));
        }


        //过滤掉没有领取机会的卷
        list = list.stream().filter(n -> n.getMaxCouponsPerUser() > n.getAlreadyReceived()).collect(Collectors.toList());

        return AjaxResult.success(list);
    }

    /**
     * 查询会员券列表
     */
//    @ApiOperation("查询会员券列表")
    @PostMapping("/listMemberCoupon")
    public TableDataInfo listMemberCoupon(@RequestBody H5MemberCouponRequest h5MemberCouponRequest, Pageable page)
    {
        Member member = SecurityUtil.getLocalMember();
        h5MemberCouponRequest.setMemberId(member.getId());
        PageHelper.startPage(1, 100,"create_time desc");

        List<WechatMemberCoupon> list = h5MemberCouponService.selectMemberCouponList(h5MemberCouponRequest);

        return getDataTable(list);
    }

    /**
     * 查询会员券列表
     */
//    @ApiOperation("查询会员券列表")
    @GetMapping("/listMemberCouponForOrder")
    public TableDataInfo listMemberCoupon2()
    {
        Member member = SecurityUtil.getLocalMember();

        List<WechatMemberCouponResponse> list = h5MemberCouponService.selectMemberCouponListForOrder(member.getId());

        return getDataTable(list);
    }

//    @ApiOperation("领取优惠券")
    @PostMapping("/get")
    public AjaxResult get(@RequestBody H5MemberCouponGetRequest h5MemberCouponRequest)
    {
        Member member = SecurityUtil.getLocalMember();

        String phone = memberService.getPhoneDecrypted(member.getPhoneEncrypted());

        SendCouponRequest sendCouponRequest = new SendCouponRequest();
        sendCouponRequest.setPhone(phone);
        sendCouponRequest.setStockId(h5MemberCouponRequest.getStockId());

        int result = h5CouponService.sendCoupon(sendCouponRequest);

        if (result == 1) {
            return AjaxResult.success();
        }

        return AjaxResult.error();
    }

}
