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.config.redis.BaseRedisService;
import shop.alien.entity.store.*;
import shop.alien.job.feign.AlienStoreFeign;
import shop.alien.mapper.*;

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 static Integer LOGOUT_FLAY = 1;

    private final StoreMembershipCardMapper storeMembershipCardMapper;

    private final StoreMembershipCardOrderMapper storeMembershipCardOrderMapper;

    private final StoreUserMapper storeUserMapper;

    private final StoreInfoMapper storeInfoMapper;

    private final BaseRedisService baseRedisService;

    private final LifeUserMapper lifeUserMapper;

    private final LifeFansMapper lifeFansMapper;

    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());

        // 获取全部申请注销的商家
        List<StoreUser> storeUsers = storeUserMapper.selectList(new LambdaQueryWrapper<StoreUser>().eq(StoreUser::getLogoutFlag, LOGOUT_FLAY));
        for (StoreUser storeUser : storeUsers) {
            if (null != storeUser.getLogoutTime()) {
                // 获取申请注销时间
                Date logoutTime = storeUser.getLogoutTime();
                // 获取申请注销 8 天后的时间
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(logoutTime);
                calendar.add(Calendar.DAY_OF_YEAR, 8);
                Date sevenDay = calendar.getTime();
                // 获取当前时间
                Date date = new Date();
                if (date.compareTo(sevenDay) >= 0) {
                    // 删除已过注销时间的商家
                    storeUserMapper.deleteById(storeUser.getId());
                    alienStoreFeign.delMer(Boolean.TRUE, storeUser.getId().toString());
                    //删除用户redis中的token
                    baseRedisService.delete("store_" + storeUser.getPhone());
                }
            }
        }
        List<StoreInfo> storeInfos = storeInfoMapper.selectList(new LambdaQueryWrapper<StoreInfo>().eq(StoreInfo::getLogoutFlag, LOGOUT_FLAY));
        for (StoreInfo storeInfo : storeInfos) {
            if (null != storeInfo.getLogoutTime()) {
                // 获取申请注销时间
                Date logoutTime = storeInfo.getLogoutTime();
                // 获取申请注销 8 天后的时间
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(logoutTime);
                calendar.add(Calendar.DAY_OF_YEAR, 8);
                Date sevenDay = calendar.getTime();
                // 获取当前时间
                Date date = new Date();
                if (date.compareTo(sevenDay) >= 0) {
                    //删除该账号的店铺
                    storeInfoMapper.deleteById(storeInfo.getId());
                    StoreUser storeUser = storeUserMapper.selectOne(new LambdaQueryWrapper<StoreUser>().eq(StoreUser::getStoreId, storeInfo.getId()));
                    if (storeUser != null) {
                        storeUser.setStoreId(null);
                        storeUserMapper.updateById(storeUser);
                        LambdaQueryWrapper<LifeFans> queryWrapper = new LambdaQueryWrapper<LifeFans>().eq(LifeFans::getFollowedId, "store_" + storeUser.getPhone())
                                .or().eq(LifeFans::getFansId, "store_" + storeUser.getPhone());
                        lifeFansMapper.delete(queryWrapper);
                    }
                }
            }
        }

        // 获取全部申请注销的用户
        List<LifeUser> lifeUsers = lifeUserMapper.selectList(new LambdaQueryWrapper<LifeUser>().eq(LifeUser::getLogoutFlag, LOGOUT_FLAY));
        for (LifeUser lifeUser : lifeUsers) {
            if (null != lifeUser.getLogoutTime()) {
                // 获取申请注销时间
                Date logoutTime = lifeUser.getLogoutTime();
                // 获取申请注销 7 天后的时间
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(logoutTime);
                calendar.add(Calendar.DAY_OF_YEAR, 7);
                Date sevenDay = calendar.getTime();
                // 获取当前时间
                Date date = new Date();
                if (date.compareTo(sevenDay) >= 0) {
                    // 删除已过注销时间的用户
                    lifeUserMapper.deleteById(lifeUser.getId());
                    // 清理粉丝
                    LambdaQueryWrapper<LifeFans> queryWrapper = new LambdaQueryWrapper<LifeFans>().eq(LifeFans::getFollowedId, "user_" + lifeUser.getUserPhone())
                            .or().eq(LifeFans::getFansId, "user_" + lifeUser.getUserPhone());
                    lifeFansMapper.delete(queryWrapper);
                }
            }
        }
    }
}
