package org.jeecg.modules.adweb.subscription.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import jakarta.annotation.Resource;

import org.apache.commons.collections4.CollectionUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.adweb.subscription.entity.SubscribePlan;
import org.jeecg.modules.adweb.subscription.entity.UserPlanSubscription;
import org.jeecg.modules.adweb.subscription.mapper.UserPlanSubscriptionMapper;
import org.jeecg.modules.adweb.subscription.service.ISubscribePlanService;
import org.jeecg.modules.adweb.subscription.service.IUserPlanSubscriptionService;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Description: AdWeb套餐订购
 * @Author: jeecg-boot
 * @Date: 2024-10-15
 * @Version: V1.0
 */
@Service
public class UserPlanSubscriptionServiceImpl
        extends ServiceImpl<UserPlanSubscriptionMapper, UserPlanSubscription>
        implements IUserPlanSubscriptionService {

    @Resource private ISubscribePlanService subscribePlanService;

    @Override
    public Result<?> addUserPlanSubscription(
            UserPlanSubscription userPlanSubscription, LoginUser sysUser) {
        boolean result = false;

        SubscribePlan subscribePlan =
                subscribePlanService.getById(userPlanSubscription.getPlanId());
        if (subscribePlan == null) {
            return Result.error("此套餐不存在");
        }

        if (sysUser != null) {
            userPlanSubscription.setCreateBy(sysUser.getId());
        } else {
            userPlanSubscription.setCreateBy("system_auto");
        }

        // 如果不是续费客户(就是新客户)的话，直接入库，套餐开启时间即是现在
        if (userPlanSubscription.getIsRenew() == null || userPlanSubscription.getIsRenew() == 0) {
            LambdaQueryWrapper<UserPlanSubscription> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(UserPlanSubscription::getSiteId, userPlanSubscription.getSiteId());
            queryWrapper.eq(UserPlanSubscription::getStatus, 1);
            List<UserPlanSubscription> userPlanSubscriptionList = this.list(queryWrapper);
            if (!CollectionUtils.isEmpty(userPlanSubscriptionList)) {
                return Result.error("站点存在使用中套餐，请到期后绑定！");
            }
            result = this.addNewSubscription(userPlanSubscription, subscribePlan);
        } else { // 续费
            // 判断是否有正在使用的套餐，如果没有，新建status为1的套餐
            LambdaQueryWrapper<UserPlanSubscription> oldQueryWrapper = new LambdaQueryWrapper<>();
            oldQueryWrapper.eq(UserPlanSubscription::getSiteId, userPlanSubscription.getSiteId());
            oldQueryWrapper.eq(UserPlanSubscription::getStatus, 1);
            List<UserPlanSubscription> oldSubscriptionList = this.list(oldQueryWrapper);
            if (CollectionUtils.isEmpty(oldSubscriptionList)) {
                return Result.error("站点不存在使用中套餐，请先新增套餐");
            } else {
                LambdaQueryWrapper<UserPlanSubscription> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(UserPlanSubscription::getSiteId, userPlanSubscription.getSiteId());
                queryWrapper.eq(UserPlanSubscription::getStatus, 2);
                List<UserPlanSubscription> userPlanSubscriptionList = this.list(queryWrapper);
                if (!CollectionUtils.isEmpty(userPlanSubscriptionList)) {
                    return Result.error("同一站点不能同时续费多个相同类型的套餐！");
                }

                if (userPlanSubscription.getIsCustom() == 0) {
                    // ->不是自定义服务开启时间 需找到多个套餐服务结束时间最大的那个
                    // 此站点所有对应的套餐的最大服务结束时间
                    UserPlanSubscription subscription =
                            this.getOne(
                                    new LambdaQueryWrapper<UserPlanSubscription>()
                                            .eq(
                                                    UserPlanSubscription::getSiteId,
                                                    userPlanSubscription.getSiteId())
                                            .and(
                                                    wrapper ->
                                                            wrapper.eq(
                                                                            UserPlanSubscription
                                                                                    ::getStatus,
                                                                            1)
                                                                    .or()
                                                                    .eq(
                                                                            UserPlanSubscription
                                                                                    ::getStatus,
                                                                            2))
                                            .orderByDesc(UserPlanSubscription::getServiceEndTime)
                                            .last("limit 1"));
                    Date maxEndTime = null;
                    if (subscription == null || subscription.getServiceEndTime() == null) {
                        maxEndTime = new Date();
                    } else {
                        maxEndTime = subscription.getServiceEndTime();
                    }
                    userPlanSubscription.setCreateTime(new Date());
                    userPlanSubscription.setPlanStartTime(maxEndTime);
                    userPlanSubscription.setStatus(2);
                    userPlanSubscription.setPlanName(subscribePlan.getPlanName());
                    userPlanSubscription.setPlanCode(subscribePlan.getPlanCode());
                    userPlanSubscription.setPlanPrice(subscribePlan.getPrice());
                    userPlanSubscription.setPlanType(subscribePlan.getPlanType());
                    userPlanSubscription.setServiceMonth(subscribePlan.getServiceTime());
                    result = this.save(userPlanSubscription);
                } else if (userPlanSubscription.getIsCustom() == 1) { // 是自定义套餐开启时间
                    userPlanSubscription.setCreateTime(new Date());
                    userPlanSubscription.setPlanName(subscribePlan.getPlanName());
                    userPlanSubscription.setPlanCode(subscribePlan.getPlanCode());
                    userPlanSubscription.setPlanPrice(subscribePlan.getPrice());
                    userPlanSubscription.setPlanType(subscribePlan.getPlanType());
                    DateTime today = cn.hutool.core.date.DateUtil.date();
                    long betweenTime =
                            cn.hutool.core.date.DateUtil.between(
                                    userPlanSubscription.getPlanStartTime(),
                                    today,
                                    DateUnit.DAY,
                                    false);
                    if (betweenTime > 0) {
                        return Result.error("自定义时间请选择于今天之后！");
                    } else {
                        // 如果有正在使用的套餐，才能设置为2，否则设置为1
                        userPlanSubscription.setStatus(2);
                    }
                    userPlanSubscription.setServiceMonth(subscribePlan.getServiceTime());
                    result = this.save(userPlanSubscription);
                }
            }
        }

        if (result) {

            return Result.OK("添加成功！");
        }

        return Result.error("添加失败！");
    }

    @Override
    public boolean addNewSubscription(
            UserPlanSubscription userPlanSubscription, SubscribePlan subscribePlan) {
        boolean result = false;
        try {
            Date startTime = new Date();
            userPlanSubscription.setCreateTime(startTime);
            userPlanSubscription.setPlanStartTime(startTime);
            userPlanSubscription.setStatus(1); // 使用中
            userPlanSubscription.setPlanName(subscribePlan.getPlanName());
            userPlanSubscription.setPlanCode(subscribePlan.getPlanCode());
            userPlanSubscription.setPlanPrice(subscribePlan.getPrice());
            userPlanSubscription.setPlanType(subscribePlan.getPlanType());
            userPlanSubscription.setServiceMonth(subscribePlan.getServiceTime());
            result = this.save(userPlanSubscription);
        } catch (Exception e) {
            log.error("站点新绑定套餐失败", e);
        }
        return result;
    }

    /** 获取正在使用中的AdWeb套餐，如果没有使用中的SEO和建站套餐，则查询过期的套餐 */
    @Override
    public UserPlanSubscription getCurrentSubscription(Integer siteId) {
        LambdaQueryWrapper<UserPlanSubscription> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserPlanSubscription::getSiteId, siteId);
        queryWrapper.and(
                wrapper ->
                        wrapper.eq(UserPlanSubscription::getPlanType, "SEO")
                                .or()
                                .eq(UserPlanSubscription::getPlanType, "STATIONCONSTRUCTION"));
        queryWrapper.in(UserPlanSubscription::getStatus, Arrays.asList(1, -1));
        queryWrapper.orderByDesc(
                UserPlanSubscription::getStatus, UserPlanSubscription::getCreateTime);
        List<UserPlanSubscription> userPlanSubscriptions = this.list(queryWrapper);
        if (CollectionUtils.isNotEmpty(userPlanSubscriptions)) {
            return userPlanSubscriptions.get(0);
        }
        return null;
    }
}
