package com.fs.live.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.fs.common.constant.LiveKeysConstant;
import com.fs.common.core.domain.R;
import com.fs.common.core.redis.RedisUtil;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.StringUtils;
import com.fs.live.domain.*;
import com.fs.live.mapper.LiveMapper;
import com.fs.live.param.CouponPO;
import com.fs.live.service.ILiveCouponIssueService;
import com.fs.live.service.ILiveCouponIssueUserService;
import com.fs.live.service.ILiveCouponUserService;
import com.fs.live.vo.LiveCouponListVo;
import com.fs.store.domain.FsStoreCoupon;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fs.live.mapper.LiveCouponMapper;
import com.fs.live.service.ILiveCouponService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 优惠券Service业务层处理
 *
 * @author fs
 * @date 2025-09-30
 */
@Service
public class LiveCouponServiceImpl implements ILiveCouponService
{
    @Autowired
    private LiveCouponMapper liveCouponMapper;

    @Autowired
    private LiveMapper liveMapper;

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ILiveCouponIssueUserService liveCouponIssueUserService;
    @Autowired
    private ILiveCouponUserService liveCouponUserService;
    @Autowired
    private ILiveCouponIssueService liveCouponIssueService;

    /**
     * 查询优惠券
     *
     * @param couponId 优惠券ID
     * @return 优惠券
     */
    @Override
    public LiveCoupon selectLiveCouponById(Long couponId)
    {
        return liveCouponMapper.selectLiveCouponById(couponId);
    }

    /**
     * 查询优惠券列表
     *
     * @param liveCoupon 优惠券
     * @return 优惠券
     */
    @Override
    public List<LiveCoupon> selectLiveCouponList(LiveCoupon liveCoupon)
    {
        return liveCouponMapper.selectLiveCouponList(liveCoupon);
    }

    /**
     * 新增优惠券
     *
     * @param liveCoupon 优惠券
     * @return 结果
     */
    @Override
    public int insertLiveCoupon(LiveCoupon liveCoupon)
    {
        liveCoupon.setCreateTime(DateUtils.getNowDate());
        return liveCouponMapper.insertLiveCoupon(liveCoupon);
    }

    /**
     * 修改优惠券
     *
     * @param liveCoupon 优惠券
     * @return 结果
     */
    @Override
    public int updateLiveCoupon(LiveCoupon liveCoupon)
    {
        liveCoupon.setUpdateTime(DateUtils.getNowDate());
        return liveCouponMapper.updateLiveCoupon(liveCoupon);
    }

    /**
     * 批量删除优惠券
     *
     * @param couponIds 需要删除的优惠券ID
     * @return 结果
     */
    @Override
    public int deleteLiveCouponByIds(Long[] couponIds)
    {
        return liveCouponMapper.deleteLiveCouponByIds(couponIds);
    }

    /**
     * 删除优惠券信息
     *
     * @param couponId 优惠券ID
     * @return 结果
     */
    @Override
    public int deleteLiveCouponById(Long couponId)
    {
        return liveCouponMapper.deleteLiveCouponById(couponId);
    }

    @Override
    public List<LiveCoupon> selectLiveCouponByIds(String ids) {
        return liveCouponMapper.selectLiveCouponByIds(ids);
    }

    @Override
    public List<LiveCoupon> selectLiveCouponByLiveId(Long liveId) {
        return liveCouponMapper.selectLiveCouponByLiveId(liveId);
    }

    @Override
    public List<LiveCoupon> listCoupon(Long liveId, String couponName) {
        return liveCouponMapper.listCoupon(liveId, couponName);
    }

    @Override
    public int insertLiveCouponEntity(Map<String, Object> payload) {
        Long liveId = Long.valueOf((String) payload.get("liveId"));
        Live live = liveMapper.selectLiveByLiveId(liveId);
        if(live == null) return -1;
        String s = String.valueOf(payload.get("couponIds"));
        if(StringUtils.isEmpty(s)) return -1;
        Set<Long> collect = liveCouponMapper.selectLiveCouponIssueByLiveId(liveId).stream().collect(Collectors.toSet());

        String[] split = s.split(",");
        for (String couponId : split) {
            if(collect.contains(Long.valueOf(couponId))) continue;
            liveCouponMapper.insertLiveCouponEntity(liveId, Long.valueOf(couponId));
        }
        return 1;
    }

    @Override
    public R handleIsShowChange(Map<String, Object> payload) {
        Long liveId = Long.valueOf((String) payload.get("liveId"));
        Live live = liveMapper.selectLiveByLiveId(liveId);
        if(live == null) return R.error("直播间不存在");
        boolean isShow = Boolean.parseBoolean(payload.get("isShow").toString());
        if (isShow) {
            int i = liveCouponMapper.selectShowByLiveId(liveId);
            if (i > 0) return R.error("直播间已存在优惠券");
        }
        Long couponId = Long.valueOf(payload.get("couponId").toString());
        LiveCouponIssueRelation liveCouponIssueRelation = liveCouponMapper.selectRelation(liveId,couponId);
        if(ObjectUtil.isEmpty(liveCouponIssueRelation.getGoodsId())) return R.error("未绑定商品，无法发布！");
        liveCouponMapper.updateShow(liveId, couponId, isShow ? 1 : 0);
        return R.ok("操作成功");
    }

    @Override
    public R handleDeleteSelectedAdmin(LiveCouponListVo listVo) {
        liveCouponMapper.handleDeleteSelectedAdmin(listVo);
        return R.ok();
    }

    @Override
    public int delLiveCoupon(LiveCouponListVo vo) {
        liveCouponMapper.handleDeleteSelectedAdmin(vo);
        return 1;
    }

    @Override
    public R updateLiveCouponBind(LiveCouponListVo listVo) {
        Live live = liveMapper.selectLiveByLiveId(Long.valueOf(listVo.getLiveId()));
        if(live == null) return R.error("直播间不存在");
        int i = liveCouponMapper.updateLiveCouponBind(listVo);
        if(i > 0) return R.ok("操作成功");
        return R.error("操作失败");
    }

    @Override
    @Transactional
    public R claimCoupon(CouponPO coupon) {
        Object o = redisUtil.hashGet(String.format(LiveKeysConstant.LIVE_HOME_PAGE_CONFIG_COUPON, coupon.getLiveId(), coupon.getCouponIssueId()), String.valueOf(coupon.getUserId()));
        if (ObjectUtil.isNotEmpty(o)) {
            return R.error("您已经领取过优惠券了！");
        }
        LiveCouponIssue issue = liveCouponMapper.selectLiveCouponIssueByLiveIdAndCouponId(coupon.getLiveId(), coupon.getCouponIssueId());
        if (coupon == null || issue.getStatus() != 1) {
            return R.error("优惠券不存在或者已下架！");
        }
        Long decrement = redisUtil.decrement(String.format(LiveKeysConstant.LIVE_COUPON_NUM , coupon.getCouponIssueId()));

        LiveCoupon liveCoupon = liveCouponMapper.selectLiveCouponById(issue.getCouponId());


        if (decrement < 0L) {
            issue.setStatus(-1);
            issue.setRemainCount(0L);
            redisUtil.delete(String.valueOf(issue.getId()));
            liveCouponIssueService.updateLiveCouponIssue(issue);
            return R.error("此优惠券已领完");
        }
        Date now = DateUtils.getNowDate();
        LiveCouponIssueUser record = new LiveCouponIssueUser();
        record.setUserId(coupon.getUserId());
        record.setIssueId(issue.getId());
        record.setCreateTime(now);
        record.setUpdateTime(now);
        record.setIsDel(0);
        record.setGoodsId(coupon.getGoodsId());


        LiveCouponUser userRecord = new LiveCouponUser();
        userRecord.setCouponId(liveCoupon.getCouponId());
        userRecord.setUserId(Math.toIntExact(coupon.getUserId()));
        userRecord.setCouponTitle(liveCoupon.getTitle());
        userRecord.setCouponPrice(liveCoupon.getCouponPrice());
        userRecord.setUseMinPrice(liveCoupon.getUseMinPrice());
        userRecord.setCreateTime(now);
        userRecord.setUpdateTime(now);
        userRecord.setStatus(0);
        userRecord.setLimitTime(DateUtils.addDays(now, Math.toIntExact(liveCoupon.getCouponTime())));
        userRecord.setIsFail(1);
        userRecord.setIsDel(0);
        userRecord.setIsDel(0);
        userRecord.setGoodsId(coupon.getGoodsId());
        userRecord.setType("live-"+coupon.getLiveId());
        liveCouponUserService.insertLiveCouponUser(userRecord);
        liveCouponIssueUserService.insertLiveCouponIssueUser(record);
        redisUtil.hashPut(String.format(LiveKeysConstant.LIVE_HOME_PAGE_CONFIG_COUPON, coupon.getLiveId(), coupon.getCouponIssueId()), String.valueOf(coupon.getUserId()), JSONUtil.toJsonStr(record));
        return R.ok("恭喜您抢到优惠券");
    }

    @Override
    public R userCouponList(CouponPO coupon) {
        List<LiveCouponUser> list = liveCouponUserService.selectLiveCouponUserByCouponPO(coupon);
        return R.ok().put("data", list);
    }

    @Override
    public R curCoupon(CouponPO coupon) {
        List<LiveCouponUser> list = liveCouponUserService.curCoupon(coupon);
        return R.ok().put("data", list);
    }


}
