package org.jeecg.modules.adweb.seo.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.seo.entity.SeoPlanSubscription;
import org.jeecg.modules.adweb.seo.mapper.SeoPlanSubscriptionMapper;
import org.jeecg.modules.adweb.seo.service.ISeoPlanSubscriptionService;
import org.jeecg.modules.adweb.subscribePlan.entity.SubscribePlan;
import org.jeecg.modules.adweb.subscribePlan.service.ISubscribePlanService;
import org.springframework.stereotype.Service;

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

/**
 * @Description: seo套餐订购
 * @Author: jeecg-boot
 * @Date: 2024-10-15
 * @Version: V1.0
 */
@Service
public class SeoPlanSubscriptionServiceImpl
        extends ServiceImpl<SeoPlanSubscriptionMapper, SeoPlanSubscription>
        implements ISeoPlanSubscriptionService {

    @Resource private ISubscribePlanService subscribePlanService;

    @Override
    public Result<?> addSeoPlanSubscription(
            SeoPlanSubscription seoPurchaseHistory, LoginUser sysUser) {
        boolean result = false;

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

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

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

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

        if (result) {

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

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

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

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