package com.cyl.manager.marketing.service.impl;

import cn.felord.payment.wechat.v3.model.busifavor.BusiFavorReceiveConsumeData;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
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.mapper.WechatStockMapper;
import com.cyl.manager.marketing.pojo.SendCouponRequest;
import com.cyl.manager.marketing.service.IWechatMemberCouponService;
import com.cyl.manager.marketing.service.IWechatStockService;
import com.cyl.manager.ums.domain.Member;
import com.cyl.manager.ums.domain.MemberWechat;
import com.cyl.manager.ums.pojo.query.MemberQuery;
import com.cyl.manager.ums.service.MemberService;
import com.cyl.manager.ums.service.MemberWechatService;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.uuid.UUID;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
@Slf4j
public class WechatMemberCouponServiceImpl implements IWechatMemberCouponService {

    @Autowired
    private WechatMemberCouponMapper wechatMemberCouponMapper;

    @Autowired
    private MemberService memberService;

    @Autowired
    private IWechatStockService wechatStockService;

    @Autowired
    private WechatStockMapper wechatStockMapper;

    @Autowired
    private MemberWechatService memberWechatService;

    @Override
    public WechatMemberCoupon selectWechatMemberCouponById(Integer id) {
        return wechatMemberCouponMapper.selectById(id);
    }

    @Override
    public List<WechatMemberCoupon> selectWechatMemberCouponList(WechatMemberCoupon wechatMemberCoupon) {
        return wechatMemberCouponMapper.selectList2(wechatMemberCoupon);
    }

    @Override
    public int insertWechatMemberCoupon(WechatMemberCoupon wechatMemberCoupon) {
        Long userId = SecurityUtils.getUserId();

        wechatMemberCoupon.setCreateBy(userId);
        wechatMemberCoupon.setCreateTime(LocalDateTime.now());
        wechatMemberCoupon.setUpdateBy(userId);
        wechatMemberCoupon.setUpdateTime(LocalDateTime.now());

        return wechatMemberCouponMapper.insert(wechatMemberCoupon);
    }

    @Override
    public int updateWechatMemberCoupon(WechatMemberCoupon wechatMemberCoupon) {
        Long userId = SecurityUtils.getUserId();

        wechatMemberCoupon.setUpdateBy(userId);
        wechatMemberCoupon.setUpdateTime(LocalDateTime.now());
        return wechatMemberCouponMapper.updateWechatMemberCoupon(wechatMemberCoupon);
    }

    @Override
    public int deleteWechatMemberCouponByIds(Integer[] ids) {
        return wechatMemberCouponMapper.deleteByIds(ids);
    }

    @Override
    public int deleteWechatMemberCouponById(Integer id) {
        return wechatMemberCouponMapper.deleteById(id);
    }

    @Override
    public void send(BusiFavorReceiveConsumeData data) {
        WechatMemberCoupon wechatMemberCoupon = new WechatMemberCoupon();

        String openId = data.getOpenid();
        String stockId = data.getStockId();

        MemberWechat memberWechat = memberWechatService.selectByOpenId(openId);
        WechatStock wechatStock = wechatStockService.selectWechatStockByStockId(stockId);

        if (memberWechat == null) {
            log.error("Open id : " + openId + "不存在，查询不到用户");
            return;
        }

        if (wechatStock == null) {
            log.error("Stock id : " + stockId + "不存在，查询不到商家券");
            return;
        }

        Member member = memberService.selectById(memberWechat.getMemberId());

        if (member == null) {
            log.error("User id : " + memberWechat.getMemberId() + "不存在，查询不到用户");
            return;
        }

        wechatMemberCoupon.setCouponCode(data.getCouponCode());
        wechatMemberCoupon.setOpenid(openId);
        wechatMemberCoupon.setStockId(stockId);
        wechatMemberCoupon.setStockType(wechatStock.getStockType());
        wechatMemberCoupon.setStockName(wechatStock.getStockName());

        wechatMemberCoupon.setAvailableStartTime(data.getSendTime().toLocalDateTime());
        wechatMemberCoupon.setExpireTime(data.getSendTime().toLocalDateTime().plusDays(wechatStock.getAvailableDayAfterReceive()));
        wechatMemberCoupon.setReceiveTime(data.getSendTime().toLocalDateTime());

        wechatMemberCoupon.setPhone(memberService.getPhoneDecrypted(member.getPhoneEncrypted()));

        wechatMemberCoupon.setCouponState("SENDED");

        wechatMemberCoupon.setDiscountType(wechatStock.getDiscountType());

        Long userId = 1L;
        wechatMemberCoupon.setCreateBy(userId);
        wechatMemberCoupon.setCreateTime(LocalDateTime.now());
        wechatMemberCoupon.setUpdateBy(userId);
        wechatMemberCoupon.setUpdateTime(LocalDateTime.now());

        log.info("【商家券发放】发送成功：" + wechatMemberCoupon);

        wechatMemberCouponMapper.insert(wechatMemberCoupon);
    }

    @Override
    public int sendCoupon(SendCouponRequest sendCouponRequest) {
        MemberQuery memberQuery = new MemberQuery();
        memberQuery.setPhone(sendCouponRequest.getPhone());

        //1、查询会员信息
        List<Member> memberList = memberService.selectList(memberQuery, null);

        if (CollectionUtil.isEmpty(memberList)) {
            throw new ServiceException("[发送优惠券]会员手机号不存在：" + sendCouponRequest.getPhone());
        }

        //2、查询会员
        Member member = memberList.get(0);
        MemberWechat memberWechat = memberWechatService.selectByMemberId(member.getId());

        //3、查询优惠券信息
        WechatStock wechatStock = wechatStockService.selectWechatStockById(sendCouponRequest.getStockId());

        if ( wechatStock == null) {
            throw new ServiceException("[发送优惠券]优惠券不存在：" + sendCouponRequest.getStockId());
        }

        if (wechatStock.getAvailableEndTime().isBefore(LocalDateTime.now())) {
            throw new ServiceException("[发送优惠券]该优惠券已过期：" + sendCouponRequest.getStockId());
        }

        if (wechatStock.getGiveNum() >= wechatStock.getMaxCoupons()) {
            throw new ServiceException("[发送优惠券]该优惠券被抢光啦：" + sendCouponRequest.getStockId());
        }

        //3.5 验证该用户是否已经领取该优惠券
        QueryWrapper<WechatMemberCoupon> qw = new QueryWrapper<>();
        qw.eq("member_id", member.getId());
        qw.eq("stock_id", wechatStock.getStockId());
        List<WechatMemberCoupon> wechatMemberCouponList = wechatMemberCouponMapper.selectList(qw);
        if (wechatMemberCouponList.size() >= wechatStock.getMaxCouponsPerUser()) {
            throw new ServiceException("[发送优惠券]已超过优惠券领取次数，请勿重复领取");
        }

        //4、发送优惠券
        WechatMemberCoupon wechatMemberCoupon = new WechatMemberCoupon();
        Long userId = 1L;
        wechatMemberCoupon.setMemberId(member.getId());
        wechatMemberCoupon.setCreateBy(userId);
        wechatMemberCoupon.setCreateTime(LocalDateTime.now());
        wechatMemberCoupon.setUpdateBy(userId);
        wechatMemberCoupon.setUpdateTime(LocalDateTime.now());

        wechatMemberCoupon.setCouponCode(UUID.randomUUID().toString());
        wechatMemberCoupon.setOpenid(memberWechat.getRoutineOpenid());
        wechatMemberCoupon.setStockId(wechatStock.getStockId());
        wechatMemberCoupon.setStockType(wechatStock.getStockType());
        wechatMemberCoupon.setStockName(wechatStock.getStockName());

        wechatMemberCoupon.setAvailableStartTime(LocalDateTime.now());
        wechatMemberCoupon.setExpireTime(LocalDateTime.now().plusDays(wechatStock.getAvailableDayAfterReceive()));
        wechatMemberCoupon.setReceiveTime(LocalDateTime.now());

        wechatMemberCoupon.setPhone(sendCouponRequest.getPhone());
        wechatMemberCoupon.setCouponState("SENDED");
        wechatMemberCoupon.setDiscountType(wechatStock.getDiscountType());



        wechatStock.setGiveNum(wechatStock.getGiveNum() + 1);
        wechatStockMapper.updateById(wechatStock);

        log.info("【平台券发放】发送成功：" + wechatMemberCoupon);
        //TODO 短信提醒

        return wechatMemberCouponMapper.insert(wechatMemberCoupon);
    }

    /**
     * 优惠券核销
     * @param id
     * @return
     */
    @Override
    public boolean use(Integer id, Long orderId) {
        WechatMemberCoupon wechatMemberCoupon = wechatMemberCouponMapper.selectById(id);

        LocalDateTime now = LocalDateTime.now();
//        LocalDateTime availableStartTime = wechatMemberCoupon.getAvailableStartTime();
        LocalDateTime expireTime = wechatMemberCoupon.getExpireTime();

        /** 商家券状态
         枚举值：
         SENDED：可用
         USED：已核销
         EXPIRED：已过期
         DEACTIVATED：已失效 */

        String couponState = wechatMemberCoupon.getCouponState();

        if (couponState.equals("USED")) {
            throw new ServiceException("优惠券已经被使用");
        }
        if (couponState.equals("EXPIRED")) {
            throw new ServiceException("优惠券已经过期");
        }
        if (couponState.equals("DEACTIVATED")) {
            throw new ServiceException("优惠券已经失效");
        }

//        if (availableStartTime.isAfter(now)) {
//            throw new ServiceException("优惠券还未生效");
//        }

        if (now.isAfter(expireTime)) {
            throw new ServiceException("优惠券已过期");
        }

        LocalDateTime optDate = LocalDateTime.now();
        UpdateWrapper<WechatMemberCoupon> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id);
        updateWrapper.set("coupon_state", "USED");
        updateWrapper.set("use_time", optDate);
        updateWrapper.set("use_request_no", orderId);
        updateWrapper.set("update_time", optDate);
        int rows = wechatMemberCouponMapper.update(null, updateWrapper);
        if (rows < 1){
            throw new RuntimeException("更新优惠券状态失败");
        }

        return true;
    }
}
