package shop.alien.store.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import shop.alien.entity.store.LifeDiscountCoupon;
import shop.alien.entity.store.LifeDiscountCouponUser;
import shop.alien.entity.store.StorePlatformBenefits;
import shop.alien.entity.store.StoreVirtualCurrency;
import shop.alien.entity.store.vo.StorePlatformBenefitsVo;
import shop.alien.mapper.*;
import shop.alien.store.service.StorePlatformBenefitsService;
import shop.alien.util.common.JwtUtil;
import shop.alien.util.common.constant.DiscountCouponEnum;
import shop.alien.util.coupon.DiscountCouponExpirationUtil;
import shop.alien.util.coupon.LifeDiscountCouponStock;

import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 福利表 服务实现类
 *
 * @author ssk
 * @since 2025-12-18
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class StorePlatformBenefitsServiceImpl extends ServiceImpl<StorePlatformBenefitsMapper, StorePlatformBenefits> implements StorePlatformBenefitsService {

    private final StorePlatformBenefitsMapper benefitsMapper;

    private final StoreVirtualCurrencyMapper virtualCurrencyMapper;

    private final LifeCouponMapper lifeCouponMapper;
    private final LifeDiscountCouponMapper lifeDiscountCouponMapper;
    private final LifeDiscountCouponUserMapper lifeDiscountCouponUserMapper;


    @Override
    public IPage<StorePlatformBenefitsVo> getPage(int page, int size, Integer type, String name) {
        log.info("StorePlatformBenefitsServiceImpl.getPage - page={}, size={}, type={}, name={}", page, size, type, name);

        IPage<StorePlatformBenefitsVo> pageRequest = new Page<>(page, size);
        QueryWrapper<StorePlatformBenefitsVo> queryWrapper = new QueryWrapper<>();

        // 动态查询条件
        if (type != null) {
            queryWrapper.eq("type", type);
        }
        if (name != null && !name.isEmpty()) {
            queryWrapper.eq("name", name);
        }

        // 按创建时间倒序
        queryWrapper.orderByDesc("created_time");

        return benefitsMapper.getPlatformBenefitsPage(pageRequest, queryWrapper);
    }

    @Override
    public StorePlatformBenefits getById(Integer id) {
        log.info("StorePlatformBenefitsServiceImpl.getById - id={}", id);
        return benefitsMapper.selectById(id);
    }

    @Override
    public int add(StorePlatformBenefits benefits) {
        log.info("StorePlatformBenefitsServiceImpl.add - benefits={}", benefits);
        JSONObject data = JwtUtil.getCurrentUserInfo();
        Integer userId = null;
        if (data != null) {
            userId = data.getInteger("userId");
            log.info("获取用户ID：userId={}", userId);
        }
        if (benefits.getType() == 2) {
            StoreVirtualCurrency virtualCurrency = new StoreVirtualCurrency();
            virtualCurrency.setName(benefits.getName());
            virtualCurrency.setStatus(0);
            virtualCurrency.setCreatedTime(new Date());
            virtualCurrency.setCreatedUserId(userId);
            virtualCurrency.setQuantity(benefits.getVirtualCurrencyAmount());
            virtualCurrencyMapper.insert(virtualCurrency);

            benefits.setBusinessId(virtualCurrency.getId().toString());
        }

        benefits.setCreatedTime(new Date());
        benefits.setDeleteFlag(0);
        benefits.setCreatedUserId(userId);
        // 默认待审核
        if (benefits.getStatus() == null) {
            benefits.setStatus(0);
        }
        return benefitsMapper.insert(benefits);
    }

    @Override
    public int update(StorePlatformBenefits benefits) {
        log.info("StorePlatformBenefitsServiceImpl.update - benefits={}", benefits);
        JSONObject data = JwtUtil.getCurrentUserInfo();
        Integer userId = null;
        if (data != null) {
            userId = data.getInteger("userId");
            log.info("获取用户ID：userId={}", userId);
        }

        if (benefits.getType() == 2) {
            StoreVirtualCurrency virtualCurrency = new StoreVirtualCurrency();
            virtualCurrency.setId(benefits.getVirtualCurrencyId());
            virtualCurrency.setName(benefits.getName());
            virtualCurrency.setUpdatedTime(new Date());
            virtualCurrency.setUpdatedUserId(userId);
            virtualCurrency.setQuantity(benefits.getVirtualCurrencyAmount());
            virtualCurrencyMapper.updateById(virtualCurrency);
        }

        benefits.setUpdatedUserId(userId);
        benefits.setUpdatedTime(new Date());
        return benefitsMapper.updateById(benefits);
    }

    @Override
    public int delete(Integer id) {
        log.info("StorePlatformBenefitsServiceImpl.delete - id={}", id);
        StorePlatformBenefits benefits = new StorePlatformBenefits();
        benefits.setId(id);
        benefits.setDeleteFlag(1);
        benefits.setUpdatedTime(new Date());
        UpdateWrapper<StorePlatformBenefits> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id).set("delete_flag", 1).set("updated_time", new Date());
        return benefitsMapper.update(null, updateWrapper);
    }

    @Override
    public int audit(Integer id, Integer status) {
        log.info("StorePlatformBenefitsServiceImpl.audit - id={}, status={}", id, status);
        StorePlatformBenefits benefits = new StorePlatformBenefits();
        benefits.setId(id);
        benefits.setStatus(status);
        benefits.setUpdatedTime(new Date());
        return benefitsMapper.updateById(benefits);
    }

    @Override
    public String receiveBenefits(Integer id, Integer userId) {
        log.info("StorePlatformBenefitsServiceImpl.receiveBenefits - id={},userId={}", id,userId);

        // 获取当前用户信息
        JSONObject data = JwtUtil.getCurrentUserInfo();
        Integer userId1 = null;
        if (data != null) {
            userId1 = data.getInteger("userId");
            log.info("获取用户ID：userId={}", userId1);
        }
        if (userId1 == null) {
            throw new RuntimeException("用户未登录");
        }
        
        // 查询福利信息
        StorePlatformBenefits benefits = benefitsMapper.selectById(id);
        if (benefits == null) {
            throw new RuntimeException("福利不存在");
        }
        
        // 检查福利状态：必须是审核通过（status=2）
//        if (benefits.getStatus() == null || benefits.getStatus() != 2) {
//            throw new RuntimeException("福利未审核通过，无法领取");
//        }
        
        // 检查删除标记
        if (benefits.getDeleteFlag() != null && benefits.getDeleteFlag() == 1) {
            throw new RuntimeException("福利已删除");
        }
        
        // 检查类型并处理
        if (benefits.getType() == null) {
            throw new RuntimeException("福利类型不存在");
        }
        
        if (benefits.getType() == 1) {
            // 类型1：优惠券
            return receiveCoupon(benefits, userId, id);
        } else if (benefits.getType() == 2) {
            // 类型2：U币
            return receiveVirtualCurrency(benefits, userId, id);
        } else {
            throw new RuntimeException("不支持的福利类型");
        }
    }

    @Override
    public List<StorePlatformBenefitsVo> listBenefits(Integer userId) {
        // 查询用户已领取的优惠券记录
        QueryWrapper<LifeDiscountCouponUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        List<LifeDiscountCouponUser> lifeDiscountCouponUsers = lifeDiscountCouponUserMapper.selectList(queryWrapper);
//        List<Integer> couponIdList = lifeDiscountCouponUsers.stream().filter(x -> x.getCouponId() != null).map(LifeDiscountCouponUser::getCouponId).collect(Collectors.toList());
//        List<Integer> ubIdList = lifeDiscountCouponUsers.stream().filter(x -> x.getUbId() != null).map(LifeDiscountCouponUser::getUbId).collect(Collectors.toList());
        List<Integer> welfareIdList = lifeDiscountCouponUsers.stream().filter(x->x.getWelfareId() != null).map(LifeDiscountCouponUser::getWelfareId).collect(Collectors.toList());
        List<StorePlatformBenefitsVo> storePlatformBenefits = benefitsMapper.selectListAndCoupon();
        List<StorePlatformBenefitsVo> result = new ArrayList<>();
        for (StorePlatformBenefitsVo storePlatformBenefit : storePlatformBenefits) {
            StorePlatformBenefitsVo  storePlatformBenefitVo = new StorePlatformBenefitsVo();
            cn.hutool.core.bean.BeanUtil.copyProperties(storePlatformBenefit, storePlatformBenefitVo);
            if (welfareIdList.contains(storePlatformBenefitVo.getId())) {
                storePlatformBenefitVo.setClaimed(true);
            } else {
                storePlatformBenefitVo.setClaimed(false);
            }
            result.add(storePlatformBenefitVo);
        }
        return result;
    }

    /**
     * 领取优惠券
     */
    private String receiveCoupon(StorePlatformBenefits benefits, Integer userId, Integer benefitsId) {
        log.info("StorePlatformBenefitsServiceImpl.receiveCoupon - benefitsId={}, userId={}", benefitsId, userId);
        
        // 通过 business_id 获取优惠券信息
        if (benefits.getBusinessId() == null || benefits.getBusinessId().isEmpty()) {
            throw new RuntimeException("优惠券信息不存在");
        }
        // 查询优惠券信息
        LifeDiscountCoupon lifeDiscountCoupon = lifeDiscountCouponMapper.selectById(benefits.getBusinessId());
        if (lifeDiscountCoupon == null) {
            throw new RuntimeException("优惠券不存在");
        }
        
        // 检查优惠券删除标记
        if (lifeDiscountCoupon.getDeleteFlag() != null && lifeDiscountCoupon.getDeleteFlag() == 1) {
            throw new RuntimeException("优惠券已删除");
        }
        
        // 检查库存
//        if (lifeDiscountCoupon.getSingleQty() == null || lifeDiscountCoupon.getSingleQty() <= 0) {
//            throw new RuntimeException("优惠券库存不足");
//        }
        
        if (!LifeDiscountCouponStock.isUnlimitedQty(lifeDiscountCoupon.getUnlimitedQty())) {
            Integer q = lifeDiscountCoupon.getSingleQty();
            if (q == null || q <= 0) {
                throw new RuntimeException("优惠券库存不足");
            }
            lifeDiscountCoupon.setSingleQty(q - 1);
        }
        lifeDiscountCoupon.setUpdatedTime(new Date());
        int updateResult = lifeDiscountCouponMapper.updateById(lifeDiscountCoupon);

        // 把优惠券记录插入到用户优惠券表中
        LifeDiscountCouponUser lifeDiscountCouponUser = new LifeDiscountCouponUser();
        // 设置该优惠券记录的优惠券 ID
        lifeDiscountCouponUser.setCouponId(lifeDiscountCoupon.getId());
        // 设置该优惠券记录的用户 ID 为当前用户 ID
        lifeDiscountCouponUser.setUserId(userId);
        // 设置该优惠券的领取时间为当前时间
        lifeDiscountCouponUser.setReceiveTime(new Date());
        lifeDiscountCouponUser.setExpirationTime(DiscountCouponExpirationUtil.resolveLifeDiscountCouponExpiration(
                lifeDiscountCouponUser.getReceiveTime(),
                lifeDiscountCoupon.getLongTermValid(),
                lifeDiscountCoupon.getSpecifiedDay(),
                lifeDiscountCoupon.getExpirationDate(),
                lifeDiscountCoupon.getValidDate(),
                lifeDiscountCoupon.getEndDate(),
                ZoneId.systemDefault()));
        // 设置该优惠券的状态为待使用
        lifeDiscountCouponUser.setStatus(Integer.parseInt(DiscountCouponEnum.WAITING_USED.getValue()));
        lifeDiscountCouponUser.setWelfareId(benefitsId);
        lifeDiscountCouponUser.setIssueSource(5); // 5-平台发放（平台福利）
        lifeDiscountCouponUserMapper.insert(lifeDiscountCouponUser);

        if (updateResult > 0) {
            log.info("用户领取优惠券成功 - userId={}, benefitsId={}, couponId={}", userId, benefitsId, benefits.getBusinessId());
            return "领取成功";
        } else {
            throw new RuntimeException("领取失败，请稍后重试");
        }
    }
    
    /**
     * 领取U币
     */
    private String receiveVirtualCurrency(StorePlatformBenefits benefits, Integer userId, Integer benefitsId) {
        log.info("StorePlatformBenefitsServiceImpl.receiveVirtualCurrency - benefitsId={}, userId={}", benefitsId, userId);
        
        // 通过 business_id 获取U币信息
        if (benefits.getBusinessId() == null || benefits.getBusinessId().isEmpty()) {
            throw new RuntimeException("U币信息不存在");
        }
        
        Integer virtualCurrencyId;
        try {
            virtualCurrencyId = Integer.parseInt(benefits.getBusinessId());
        } catch (NumberFormatException e) {
            throw new RuntimeException("U币ID格式错误");
        }
        
        StoreVirtualCurrency virtualCurrency = virtualCurrencyMapper.selectById(virtualCurrencyId);
        if (virtualCurrency == null) {
            throw new RuntimeException("U币不存在");
        }
        
        // 检查U币删除标记
        if (virtualCurrency.getDeleteFlag() != null && virtualCurrency.getDeleteFlag() == 1) {
            throw new RuntimeException("U币已删除");
        }
        
        // 检查U币状态：必须是审核通过（status=2）
        if (virtualCurrency.getStatus() == null || virtualCurrency.getStatus() != 2) {
            throw new RuntimeException("U币未审核通过，无法领取");
        }

        // 插入用户U币记录（假设表名为 store_user_virtual_currency）
        // 把优惠券记录插入到用户优惠券表中
        LifeDiscountCouponUser lifeDiscountCouponUser = new LifeDiscountCouponUser();
        // 设置该优惠券记录的优惠券 ID
        lifeDiscountCouponUser.setWelfareId(benefitsId);
        lifeDiscountCouponUser.setUbId(benefits.getId());
        // 设置该优惠券记录的用户 ID 为当前用户 ID
        lifeDiscountCouponUser.setUserId(userId);
        // 设置该优惠券的领取时间为当前时间
        lifeDiscountCouponUser.setReceiveTime(new Date());
        // 设置该优惠券的过期时间为优惠券本身的结束日期
        // 设置2099年12月31日为过期时间
        java.time.LocalDate expirationTime = java.time.LocalDate.of(2099, 12, 31);
        lifeDiscountCouponUser.setExpirationTime(expirationTime);
        // 设置该优惠券的状态为待使用
        lifeDiscountCouponUser.setStatus(Integer.parseInt(DiscountCouponEnum.WAITING_USED.getValue()));
        lifeDiscountCouponUserMapper.insert(lifeDiscountCouponUser);
        
        // U币领取成功（目前只验证，不创建记录表，后续可根据业务需求添加用户U币记录表）
        log.info("用户领取U币成功 - userId={}, benefitsId={}, virtualCurrencyId={}", userId, benefitsId, virtualCurrencyId);
        return "领取成功";
    }
}

