package shop.alien.store.service.impl;

import com.aliyun.tea.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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 org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import shop.alien.entity.store.StoreInfo;
import shop.alien.entity.store.StoreMembershipCard;
import shop.alien.entity.store.StoreMembershipCardOrder;
import shop.alien.entity.store.vo.StoreMembershipCardOrderVo;
import shop.alien.entity.store.vo.StoreMembershipCardVo;
import shop.alien.mapper.StoreInfoMapper;
import shop.alien.mapper.StoreMembershipCardMapper;
import shop.alien.mapper.StoreMembershipCardOrderMapper;
import shop.alien.store.service.StoreMembershipCardOrderService;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 商家会员卡订单表 服务实现类
 * </p>
 *
 * @author ssk
 * @since 2025-03-11
 */
@Service
@RequiredArgsConstructor
public class StoreMembershipCardOrderServiceImpl extends ServiceImpl<StoreMembershipCardOrderMapper, StoreMembershipCardOrder> implements StoreMembershipCardOrderService {

    //会员卡状态-进行中
    private final static String MEMBERSHIP_CARD_STATUS_UNDERWAY = "0";
    //会员卡状态-已过期
    private final static String MEMBERSHIP_CARD_STATUS_HAVE_EXPIRED = "1";
    //会员卡状态-暂停
    private final static String MEMBERSHIP_CARD_STATUS_SUSPENT = "2";

    //会员卡类型-黄金会员
    private final static String MEMBERSHIP_CARD_TYPE_GOLD = "0";
    //会员卡类型-白金会员
    private final static String MEMBERSHIP_CARD_TYPE_PLATINUM = "1";

    //会员卡购买类型-月卡
    private final static String MEMBERSHIP_CARD_BYE_TYPE_MONTH = "0";
    //会员卡购买类型-季卡
    private final static String MEMBERSHIP_CARD_BYE_TYPE_QUARTER = "1";
    //会员卡购买类型-半年卡
    private final static String MEMBERSHIP_CARD_BYE_TYPE_HALF_YEAR = "2";
    //会员卡购买类型-年卡
    private final static String MEMBERSHIP_CARD_BYE_TYPE_YEAR = "3";

    private final StoreInfoMapper storeInfoMapper;

    private final StoreMembershipCardMapper storeMembershipCardMapper;

    private final StoreMembershipCardOrderMapper storeMembershipCardOrderMapper;

    @Override
    public StoreMembershipCardVo placeOrder(StoreMembershipCardOrderVo storeMembershipCardOrderVo) {

        StoreMembershipCardVo resultCard = new StoreMembershipCardVo();
        //获取会员卡id
        String cardId = storeMembershipCardOrderVo.getCardId();
        //如果会员卡id为空
        if (StringUtils.isEmpty(cardId)) {
            StoreInfo storeInfo = storeInfoMapper.selectById(storeMembershipCardOrderVo.getStoreId());
            //新生成一个会员卡
            StoreMembershipCard card = new StoreMembershipCard();
            //门店信息
            card.setStoreId(storeInfo.getId());
            card.setStoreName(storeInfo.getStoreName());
            //存入卡片未过期
            card.setMembershipCardStatus(MEMBERSHIP_CARD_STATUS_UNDERWAY);
            //存入会员类型
            card.setMembershipType(storeMembershipCardOrderVo.getOrderType().toString());
            //存入首次开通时间
            card.setFirstOpeningTime(new Date());
            //存入开放时间
            card.setOpeningTime(new Date());
            //存入到期时间
            String purchasePattern = storeMembershipCardOrderVo.getPurchasePattern().toString();
            //如果到期时间是月卡，从现在获取一个月后时间
            // 获取当前日期
            LocalDate currentDate = LocalDate.now();
            // 计算一个月后时间
            if (purchasePattern.toString().equals(MEMBERSHIP_CARD_BYE_TYPE_MONTH)) {
                LocalDate oneMonthLater = currentDate.plusMonths(1);
                Date date = Date.from(oneMonthLater.atStartOfDay(ZoneId.systemDefault()).toInstant());
                card.setExpirationTime(date);
            } else if (purchasePattern.toString().equals(MEMBERSHIP_CARD_BYE_TYPE_QUARTER)) {
                // 计算一个季度后时间（一个季度为 3 个月）
                LocalDate oneQuarterLater = currentDate.plusMonths(3);
                Date date = Date.from(oneQuarterLater.atStartOfDay(ZoneId.systemDefault()).toInstant());
                card.setExpirationTime(date);
            } else if (purchasePattern.toString().equals(MEMBERSHIP_CARD_BYE_TYPE_HALF_YEAR)) {
                // 计算半年后时间（半年为 6 个月）
                LocalDate halfYearLater = currentDate.plusMonths(6);
                Date date = Date.from(halfYearLater.atStartOfDay(ZoneId.systemDefault()).toInstant());
                card.setExpirationTime(date);
            } else if (purchasePattern.toString().equals(MEMBERSHIP_CARD_BYE_TYPE_YEAR)) {
                // 计算一年后时间
                LocalDate oneYearLater = currentDate.plusYears(1);
                Date date = Date.from(oneYearLater.atStartOfDay(ZoneId.systemDefault()).toInstant());
                card.setExpirationTime(date);
            }
            card.setCardType(storeMembershipCardOrderVo.getOrderType());
            storeMembershipCardMapper.insert(card);
            //存入订单
            StoreMembershipCardOrder storeMembershipCardOrder = new StoreMembershipCardOrder();
            storeMembershipCardOrder.setCardId(card.getId());
            storeMembershipCardOrder.setExpirationTime(card.getExpirationTime());
            storeMembershipCardOrder.setOpeningTime(card.getOpeningTime());
            storeMembershipCardOrder.setPaymentAmount(storeMembershipCardOrderVo.getPaymentAmount());
            storeMembershipCardOrder.setPurchasePattern(Integer.parseInt(storeMembershipCardOrderVo.getPurchasePattern().toString()));
            storeMembershipCardOrder.setOrderType(storeMembershipCardOrderVo.getOrderType());
            storeMembershipCardOrder.setOrderStatus(Integer.parseInt(MEMBERSHIP_CARD_STATUS_UNDERWAY));
            // 生成 UUID
            String uuid = UUID.randomUUID().toString().replace("-", "");
            // 截取前 10 位
            storeMembershipCardOrder.setOrderCode(uuid.substring(0, 10).toUpperCase());

            storeMembershipCardOrderMapper.insert(storeMembershipCardOrder);
            //如果是白金卡订单，则判断当前是否存在黄金卡订单
            if (storeMembershipCardOrderVo.getOrderType().toString().equals(MEMBERSHIP_CARD_TYPE_PLATINUM)) {
                StoreMembershipCard cardGold = storeMembershipCardMapper.selectOne(
                        new LambdaQueryWrapper<StoreMembershipCard>()
                                .eq(StoreMembershipCard::getStoreId, storeInfo.getId())
                                .eq(StoreMembershipCard::getCardType, Integer.parseInt(MEMBERSHIP_CARD_TYPE_GOLD))
                                .ne(StoreMembershipCard::getMembershipCardStatus, MEMBERSHIP_CARD_STATUS_HAVE_EXPIRED));
                if (cardGold != null) {
                    //卡片状态为 暂停，重置到期时间和开始时间
                    cardGold.setMembershipCardStatus(MEMBERSHIP_CARD_STATUS_SUSPENT);

                    // 获取当前到期日期
                    Date expirationTime = cardGold.getExpirationTime();
                    LocalDate cardGoldCurrentDate = expirationTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                    // 计算一个月后时间
                    if (purchasePattern.toString().equals(MEMBERSHIP_CARD_BYE_TYPE_MONTH)) {
                        LocalDate oneMonthLater = cardGoldCurrentDate.plusMonths(1);
                        Date date = Date.from(oneMonthLater.atStartOfDay(ZoneId.systemDefault()).toInstant());
                        cardGold.setExpirationTime(date);
                    } else if (purchasePattern.toString().equals(MEMBERSHIP_CARD_BYE_TYPE_QUARTER)) {
                        // 计算一个季度后时间（一个季度为 3 个月）
                        LocalDate oneQuarterLater = cardGoldCurrentDate.plusMonths(3);
                        Date date = Date.from(oneQuarterLater.atStartOfDay(ZoneId.systemDefault()).toInstant());
                        cardGold.setExpirationTime(date);
                    } else if (purchasePattern.toString().equals(MEMBERSHIP_CARD_BYE_TYPE_HALF_YEAR)) {
                        // 计算半年后时间（半年为 6 个月）
                        LocalDate halfYearLater = cardGoldCurrentDate.plusMonths(6);
                        Date date = Date.from(halfYearLater.atStartOfDay(ZoneId.systemDefault()).toInstant());
                        cardGold.setExpirationTime(date);
                    } else if (purchasePattern.toString().equals(MEMBERSHIP_CARD_BYE_TYPE_YEAR)) {
                        // 计算一年后时间
                        LocalDate oneYearLater = cardGoldCurrentDate.plusYears(1);
                        Date date = Date.from(oneYearLater.atStartOfDay(ZoneId.systemDefault()).toInstant());
                        cardGold.setExpirationTime(date);
                    }
                    // 获取开始日期
                    Date openingTime = cardGold.getOpeningTime();
                    LocalDate cardGoldCurrentDateOpening = openingTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                    // 计算一个月后时间
                    if (purchasePattern.toString().equals(MEMBERSHIP_CARD_BYE_TYPE_MONTH)) {
                        LocalDate oneMonthLater = cardGoldCurrentDateOpening.plusMonths(1);
                        Date date = Date.from(oneMonthLater.atStartOfDay(ZoneId.systemDefault()).toInstant());
                        cardGold.setOpeningTime(date);
                    } else if (purchasePattern.toString().equals(MEMBERSHIP_CARD_BYE_TYPE_QUARTER)) {
                        // 计算一个季度后时间（一个季度为 3 个月）
                        LocalDate oneQuarterLater = cardGoldCurrentDateOpening.plusMonths(3);
                        Date date = Date.from(oneQuarterLater.atStartOfDay(ZoneId.systemDefault()).toInstant());
                        cardGold.setOpeningTime(date);
                    } else if (purchasePattern.toString().equals(MEMBERSHIP_CARD_BYE_TYPE_HALF_YEAR)) {
                        // 计算半年后时间（半年为 6 个月）
                        LocalDate halfYearLater = cardGoldCurrentDateOpening.plusMonths(6);
                        Date date = Date.from(halfYearLater.atStartOfDay(ZoneId.systemDefault()).toInstant());
                        cardGold.setOpeningTime(date);
                    } else if (purchasePattern.toString().equals(MEMBERSHIP_CARD_BYE_TYPE_YEAR)) {
                        // 计算一年后时间
                        LocalDate oneYearLater = cardGoldCurrentDateOpening.plusYears(1);
                        Date date = Date.from(oneYearLater.atStartOfDay(ZoneId.systemDefault()).toInstant());
                        cardGold.setOpeningTime(date);
                    }
                    storeMembershipCardMapper.updateById(cardGold);
                }
            }
            BeanUtils.copyProperties(card, resultCard);
        } else {
            StoreMembershipCard card = storeMembershipCardMapper.selectById(cardId);
            //如果现在卡片已过期，则将开始时间重置
            // 获取当前到期日期
            Date expirationTime = null;
            Date orderOpeningTime = null;
            LocalDate orderOpeningDate = null;
            //卡截止时间 + 1为订单续费开始时间
            if (!card.getMembershipCardStatus().equals(MEMBERSHIP_CARD_STATUS_HAVE_EXPIRED)) {
                card.setOpeningTime(new Date());
                expirationTime = card.getExpirationTime();
                orderOpeningTime = card.getExpirationTime();
//                orderOpeningDate = expirationTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
//                LocalDate localDate = orderOpeningDate.plusDays(1);
//                orderOpeningTime = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
//                expirationTime = orderOpeningTime;
            } else {
                orderOpeningTime = new Date();
                expirationTime = new Date();
            }
            //存入到期时间
            String purchasePattern = storeMembershipCardOrderVo.getPurchasePattern().toString();
            //如果到期时间是月卡，从现在获取一个月后时间
            LocalDate currentDate = expirationTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            // 计算一个月后时间
            if (purchasePattern.toString().equals(MEMBERSHIP_CARD_BYE_TYPE_MONTH)) {
                LocalDate oneMonthLater = currentDate.plusMonths(1);
                Date date = Date.from(oneMonthLater.atStartOfDay(ZoneId.systemDefault()).toInstant());
                card.setExpirationTime(date);
            } else if (purchasePattern.toString().equals(MEMBERSHIP_CARD_BYE_TYPE_QUARTER)) {
                // 计算一个季度后时间（一个季度为 3 个月）
                LocalDate oneQuarterLater = currentDate.plusMonths(3);
                Date date = Date.from(oneQuarterLater.atStartOfDay(ZoneId.systemDefault()).toInstant());
                card.setExpirationTime(date);
            } else if (purchasePattern.toString().equals(MEMBERSHIP_CARD_BYE_TYPE_HALF_YEAR)) {
                // 计算半年后时间（半年为 6 个月）
                LocalDate halfYearLater = currentDate.plusMonths(6);
                Date date = Date.from(halfYearLater.atStartOfDay(ZoneId.systemDefault()).toInstant());
                card.setExpirationTime(date);
            } else if (purchasePattern.toString().equals(MEMBERSHIP_CARD_BYE_TYPE_YEAR)) {
                // 计算一年后时间
                LocalDate oneYearLater = currentDate.plusYears(1);
                Date date = Date.from(oneYearLater.atStartOfDay(ZoneId.systemDefault()).toInstant());
                card.setExpirationTime(date);
            }
            card.setMembershipCardStatus(MEMBERSHIP_CARD_STATUS_UNDERWAY);
            card.setCardType(storeMembershipCardOrderVo.getOrderType());
            storeMembershipCardMapper.updateById(card);
            //存入订单
            StoreMembershipCardOrder storeMembershipCardOrder = new StoreMembershipCardOrder();
            storeMembershipCardOrder.setCardId(card.getId());
            storeMembershipCardOrder.setExpirationTime(card.getExpirationTime());
            storeMembershipCardOrder.setOpeningTime(card.getOpeningTime());
            storeMembershipCardOrder.setPaymentAmount(storeMembershipCardOrderVo.getPaymentAmount());
            storeMembershipCardOrder.setPurchasePattern(Integer.parseInt(storeMembershipCardOrderVo.getPurchasePattern().toString()));
            storeMembershipCardOrder.setOrderType(storeMembershipCardOrderVo.getOrderType());
            storeMembershipCardOrder.setOrderStatus(Integer.parseInt(MEMBERSHIP_CARD_STATUS_UNDERWAY));
            // 生成 UUID
            String uuid = UUID.randomUUID().toString().replace("-", "");
            // 截取前 10 位
            storeMembershipCardOrder.setOrderCode(uuid.substring(0, 10).toUpperCase());
            storeMembershipCardOrder.setOpeningTime(orderOpeningTime);
            storeMembershipCardOrderMapper.insert(storeMembershipCardOrder);

            //如果是白金卡订单，则判断当前是否存在黄金卡订单
            if (storeMembershipCardOrderVo.getOrderType().toString().equals(MEMBERSHIP_CARD_TYPE_PLATINUM)) {
                StoreMembershipCard cardGold = storeMembershipCardMapper.selectOne(
                        new LambdaQueryWrapper<StoreMembershipCard>()
                                .eq(StoreMembershipCard::getStoreId, card.getStoreId())
                                .eq(StoreMembershipCard::getCardType, Integer.parseInt(MEMBERSHIP_CARD_TYPE_GOLD))
                                .ne(StoreMembershipCard::getMembershipCardStatus, MEMBERSHIP_CARD_STATUS_HAVE_EXPIRED));
                if (cardGold != null) {
                    //卡片状态为 暂停，重置到期时间和开始时间
                    cardGold.setMembershipCardStatus(MEMBERSHIP_CARD_STATUS_SUSPENT);
                    // 获取当前到期日期
                    Date expirationTimeCardGold = cardGold.getExpirationTime();
                    LocalDate cardGoldCurrentDate = expirationTimeCardGold.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                    // 计算一个月后时间
                    if (purchasePattern.toString().equals(MEMBERSHIP_CARD_BYE_TYPE_MONTH)) {
                        LocalDate oneMonthLater = cardGoldCurrentDate.plusMonths(1);
                        Date date = Date.from(oneMonthLater.atStartOfDay(ZoneId.systemDefault()).toInstant());
                        cardGold.setExpirationTime(date);
                    } else if (purchasePattern.toString().equals(MEMBERSHIP_CARD_BYE_TYPE_QUARTER)) {
                        // 计算一个季度后时间（一个季度为 3 个月）
                        LocalDate oneQuarterLater = cardGoldCurrentDate.plusMonths(3);
                        Date date = Date.from(oneQuarterLater.atStartOfDay(ZoneId.systemDefault()).toInstant());
                        cardGold.setExpirationTime(date);
                    } else if (purchasePattern.toString().equals(MEMBERSHIP_CARD_BYE_TYPE_HALF_YEAR)) {
                        // 计算半年后时间（半年为 6 个月）
                        LocalDate halfYearLater = cardGoldCurrentDate.plusMonths(6);
                        Date date = Date.from(halfYearLater.atStartOfDay(ZoneId.systemDefault()).toInstant());
                        cardGold.setExpirationTime(date);
                    } else if (purchasePattern.toString().equals(MEMBERSHIP_CARD_BYE_TYPE_YEAR)) {
                        // 计算一年后时间
                        LocalDate oneYearLater = cardGoldCurrentDate.plusYears(1);
                        Date date = Date.from(oneYearLater.atStartOfDay(ZoneId.systemDefault()).toInstant());
                        cardGold.setExpirationTime(date);
                    }
                    // 获取开始日期
                    Date openingTime = cardGold.getOpeningTime();
                    LocalDate cardGoldCurrentDateOpening = openingTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                    // 计算一个月后时间
                    if (purchasePattern.toString().equals(MEMBERSHIP_CARD_BYE_TYPE_MONTH)) {
                        LocalDate oneMonthLater = cardGoldCurrentDateOpening.plusMonths(1);
                        Date date = Date.from(oneMonthLater.atStartOfDay(ZoneId.systemDefault()).toInstant());
                        cardGold.setOpeningTime(date);
                    } else if (purchasePattern.toString().equals(MEMBERSHIP_CARD_BYE_TYPE_QUARTER)) {
                        // 计算一个季度后时间（一个季度为 3 个月）
                        LocalDate oneQuarterLater = cardGoldCurrentDateOpening.plusMonths(3);
                        Date date = Date.from(oneQuarterLater.atStartOfDay(ZoneId.systemDefault()).toInstant());
                        cardGold.setOpeningTime(date);
                    } else if (purchasePattern.toString().equals(MEMBERSHIP_CARD_BYE_TYPE_HALF_YEAR)) {
                        // 计算半年后时间（半年为 6 个月）
                        LocalDate halfYearLater = cardGoldCurrentDateOpening.plusMonths(6);
                        Date date = Date.from(halfYearLater.atStartOfDay(ZoneId.systemDefault()).toInstant());
                        cardGold.setOpeningTime(date);
                    } else if (purchasePattern.toString().equals(MEMBERSHIP_CARD_BYE_TYPE_YEAR)) {
                        // 计算一年后时间
                        LocalDate oneYearLater = cardGoldCurrentDateOpening.plusYears(1);
                        Date date = Date.from(oneYearLater.atStartOfDay(ZoneId.systemDefault()).toInstant());
                        cardGold.setOpeningTime(date);
                    }
                    storeMembershipCardMapper.updateById(cardGold);
                }
            }
            BeanUtils.copyProperties(card, resultCard);
        }
        return resultCard;
    }

    @Override
    public List<StoreMembershipCard> getStoreMembershipCard(String storeId) {

        List<StoreMembershipCard> storeMembershipCards =
                storeMembershipCardMapper
                        .selectList(new LambdaQueryWrapper<StoreMembershipCard>().eq(StoreMembershipCard::getStoreId, storeId));
        return storeMembershipCards;
    }

    @Override
    public IPage<StoreMembershipCardOrderVo> getOrderHistory(Integer pageNum, Integer pageSize, Integer storeId, String storeName, String orderCode, String orderStatus, String buyType, String endTime, String vipType) {
        // 查询活动列表
        IPage<StoreMembershipCardOrder> storePage = new Page<>(pageNum, pageSize);
        IPage<StoreMembershipCardOrderVo> storeMembershipCardOrderVoIPage =
                storeMembershipCardOrderMapper.selectCardLIstPage(storePage, storeId, storeName, orderCode, orderStatus, buyType, endTime, vipType);
        return storeMembershipCardOrderVoIPage;
    }

}
