package shop.alien.store.service.impl;

import com.aliyun.tea.utils.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.stereotype.Service;
import shop.alien.entity.result.R;
import shop.alien.entity.store.LifeDiscountCoupon;
import shop.alien.entity.store.LifeDiscountCouponUser;
import shop.alien.entity.store.dto.LifeDiscountCouponUserDto;
import shop.alien.mapper.LifeDiscountCouponMapper;
import shop.alien.mapper.LifeDiscountCouponUserMapper;
import shop.alien.store.service.LifeDiscountCouponUserService;
import shop.alien.util.common.constant.DiscountCouponEnum;

import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;

/**
 * <p>
 * 优惠券用户表 服务实现类
 * </p>
 *
 * @author ssk
 * @since 2025-02-08
 */
@Service
@RequiredArgsConstructor
public class LifeDiscountCouponUserServiceImpl extends ServiceImpl<LifeDiscountCouponUserMapper, LifeDiscountCouponUser> implements LifeDiscountCouponUserService {

    private final LifeDiscountCouponMapper lifeDiscountCouponMapper;

    private final LifeDiscountCouponUserMapper lifeDiscountCouponUserMapper;

    @Override
    public R<Boolean> receiveCoupon(LifeDiscountCouponUserDto lifeDiscountCouponUserDto) {
        try {
            Integer receiveQuantity = lifeDiscountCouponUserDto.getReceiveQuantity();
            LifeDiscountCoupon lifeDiscountCoupon = lifeDiscountCouponMapper.selectById(lifeDiscountCouponUserDto.getCouponId());
            // 判断是否在领取时间内
            Date now = new Date();
            Instant instant = now.toInstant();
            ZoneId zoneId = ZoneId.systemDefault();
            LocalDate localNow = instant.atZone(zoneId).toLocalDate();
            int startResult = localNow.compareTo(lifeDiscountCoupon.getBeginGetDate());
            if (startResult < 0) {
                return R.fail("该优惠劵活动时间未开始");
            }
            int getStatus = lifeDiscountCoupon.getGetStatus();
            if (getStatus == 0) {
                return R.fail("该优惠劵已经关闭领取");
            }
            String specifiedDay = lifeDiscountCoupon.getSpecifiedDay();

            //判断领取数量
            for (int i = 0; i < receiveQuantity; i++) {
                LifeDiscountCouponUser lifeDiscountCouponUser = new LifeDiscountCouponUser();
                BeanUtils.copyProperties(lifeDiscountCouponUserDto, lifeDiscountCouponUser);
                lifeDiscountCouponUser.setReceiveTime(new Date());

                // 存入过期时间, 领取时间加上specifiedDay
                if(!StringUtils.isEmpty(specifiedDay)){
                    int sDay = Integer.parseInt(specifiedDay);
                    if(sDay > 0 && lifeDiscountCoupon.getBeginGetDate() != null) {
                        Date validDate = addDaysToDateJava8(new Date(), sDay);
                        LocalDate validDateLocalDate = validDate.toInstant()
                                .atZone(ZoneId.systemDefault())
                                .toLocalDate();
                        lifeDiscountCouponUser.setExpirationTime(validDateLocalDate);
                    }
                }

                //存入状态  待使用：0
                lifeDiscountCouponUser.setStatus(Integer.parseInt(DiscountCouponEnum.WAITING_USED.getValue()));
                lifeDiscountCouponUserMapper.insert(lifeDiscountCouponUser);
            }
            //削减该优惠券库存
            lifeDiscountCoupon.setSingleQty(lifeDiscountCoupon.getSingleQty() - receiveQuantity);
            lifeDiscountCouponMapper.updateById(lifeDiscountCoupon);
        } catch (BeansException e) {
            log.error("LifeDiscountCouponController.receiveCoupon ERROR Msg=" + e.getMessage());
            return R.fail("领取失败");
        }
        return R.success("领取成功");
    }

    public static Date addDaysToDateJava8(Date date, int days) {
        // 将Date转换为Instant
        Instant instant = date.toInstant();

        // 转换为LocalDate并加天数
        LocalDate localDate = instant.atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDate newLocalDate = localDate.plusDays(days);

        // 转换回Date
        return Date.from(newLocalDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
    }
}
