package shop.alien.job.store;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import shop.alien.entity.result.R;
import shop.alien.entity.store.StoreMembershipCard;
import shop.alien.entity.store.StoreMembershipCardOrder;
import shop.alien.entity.store.vo.AccountLogoutCompleteResultVo;
import shop.alien.job.feign.AlienStoreFeign;
import shop.alien.mapper.StoreMembershipCardMapper;
import shop.alien.mapper.StoreMembershipCardOrderMapper;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Slf4j
@Component
@RequiredArgsConstructor
public class StoreMembershipCardJob {

    //会员卡状态-进行中
    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 StoreMembershipCardMapper storeMembershipCardMapper;

    private final StoreMembershipCardOrderMapper storeMembershipCardOrderMapper;

    private final AlienStoreFeign alienStoreFeign;

    /**
     * 会员卡状态及会员卡订单状态变更任务
     */
    @XxlJob("storeMembershipCardStatusJob")
    public void storeMembershipCardStatusJob() {
        log.info("会员卡状态及会员卡订单状态变更任务执行: " + new Date());

        // 获取当前时间的 Calendar 实例
        Calendar calendar = Calendar.getInstance();
        // 将小时、分钟、秒和毫秒设置为 0
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        // 获取设置后的 Date 对象
        Date midnightDate = calendar.getTime();

        //查询会员卡暂停的卡片，判断是否到该变更回进行中
        List<StoreMembershipCard> storeMembershipSuspentCards =
                storeMembershipCardMapper.selectList(
                        new LambdaQueryWrapper<StoreMembershipCard>()
                                .eq(StoreMembershipCard::getMembershipCardStatus, MEMBERSHIP_CARD_STATUS_SUSPENT));
        //判断开始时间是否等于今日
        for (StoreMembershipCard storeMembershipCard : storeMembershipSuspentCards) {
            if (storeMembershipCard.getOpeningTime().getTime() == midnightDate.getTime()) {
                storeMembershipCard.setMembershipCardStatus(MEMBERSHIP_CARD_STATUS_UNDERWAY);
                storeMembershipCardMapper.updateById(storeMembershipCard);
            }
        }

        //查询会员卡进行中的卡片，判断是否过期
        List<StoreMembershipCard> storeMembershipUnderwayCards =
                storeMembershipCardMapper.selectList(
                        new LambdaQueryWrapper<StoreMembershipCard>()
                                .eq(StoreMembershipCard::getMembershipCardStatus, MEMBERSHIP_CARD_STATUS_UNDERWAY));
        //判断结束时间是否等于今日
        for (StoreMembershipCard storeMembershipCard : storeMembershipUnderwayCards) {
            if (storeMembershipCard.getExpirationTime().getTime() == midnightDate.getTime()) {
                storeMembershipCard.setMembershipCardStatus(MEMBERSHIP_CARD_STATUS_HAVE_EXPIRED);
                storeMembershipCardMapper.updateById(storeMembershipCard);
            }
        }

        //查询订单未过期的信息
        List<StoreMembershipCardOrder> storeMembershipCardOrders =
                storeMembershipCardOrderMapper.selectList(
                        new LambdaQueryWrapper<StoreMembershipCardOrder>()
                                .eq(StoreMembershipCardOrder::getOrderStatus, MEMBERSHIP_CARD_STATUS_UNDERWAY));
        //判断一下过期日期是否是今天
        for (StoreMembershipCardOrder storeMembershipCardOrder : storeMembershipCardOrders) {
            if (storeMembershipCardOrder.getExpirationTime().getTime() == midnightDate.getTime()) {
                storeMembershipCardOrder.setOrderStatus(Integer.parseInt(MEMBERSHIP_CARD_STATUS_HAVE_EXPIRED));
                storeMembershipCardOrderMapper.updateById(storeMembershipCardOrder);
            }
        }
    }

    /**
     * 定时清理已申请注销超过7天的商家、用户与律师
     */
    @XxlJob("cancellationOfBusinessJob")
    public void cancellationOfBusinessJob() {
        log.info("处理已申请注销超过7天的商家、用户与律师: {}", new Date());
        try {
            R<AccountLogoutCompleteResultVo> result = alienStoreFeign.completeAccountLogoutCooling();
            if (result != null && result.getData() != null) {
                AccountLogoutCompleteResultVo data = result.getData();
                log.info("注销冷静期到期处理完成: success={}, fail={}, skipped={}, details={}",
                        data.getSuccessCount(), data.getFailCount(), data.getSkippedCount(), data.getDetails());
            } else {
                log.warn("注销冷静期到期处理返回为空: {}", result);
            }
        } catch (Exception e) {
            log.error("注销冷静期到期处理失败", e);
            throw e;
        }
    }
}
