package org.jeecg.modules.adweb.site.service;

import cn.hutool.core.util.RandomUtil;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import jakarta.annotation.Resource;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.jeecg.modules.adweb.common.util.DateUtil;
import org.jeecg.modules.adweb.seo.entity.SeoPlanSubscription;
import org.jeecg.modules.adweb.seo.service.ISeoPlanSubscriptionService;
import org.jeecg.modules.adweb.site.dto.result.SiteBasicInfo;
import org.jeecg.modules.adweb.site.entity.AdwebSite;
import org.jeecg.modules.adweb.site.mapper.AdwebSiteMapper;
import org.jeecg.modules.system.mapper.SysDictMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/** 站点管理服务类 */
@Slf4j
@Service
public class SiteManageService {

    protected Logger logger = LoggerFactory.getLogger(SiteManageService.class);

    @Resource private AdwebSiteMapper adwebSiteMapper;

    @Resource private IAdwebSiteService adwebSiteService;

    @Resource private ISeoPlanSubscriptionService seoPlanSubscriptionService;

    @Resource private SysDictMapper sysDictMapper;

    public String getSiteCode(String siteCode) {
        if (StringUtils.isEmpty(siteCode)) {
            String currDate = DateUtil.formatDate(DateUtil.getDate(), DateUtil.COMPACT_DATE_FORMAT);
            siteCode = currDate + RandomUtil.randomStringUpper(6).toLowerCase();

            LambdaQueryWrapper<AdwebSite> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(AdwebSite::getCode, siteCode);
            List<AdwebSite> list = adwebSiteMapper.selectList(queryWrapper);
            if (!list.isEmpty()) {
                siteCode = getSiteCode(null);
            }
        }
        return siteCode;
    }

    /**
     * 获得网站基础信息
     *
     * @param userFlag
     * @return 网站基础信息
     */
    public SiteBasicInfo getSiteBasicInfo(String userFlag) {
        SiteBasicInfo siteBasicInfo = new SiteBasicInfo();

        AdwebSite adwebSite =
                adwebSiteService.getOne(
                        new LambdaQueryWrapper<AdwebSite>().eq(AdwebSite::getCode, userFlag));
        if (adwebSite == null) {
            return siteBasicInfo;
        }

        // 运行时间
        Date now = new Date();
        Date issueTime = adwebSite.getIssueTime();
        if (issueTime != null && DateUtil.compareDate(issueTime, now) < 0) {
            siteBasicInfo.setRunDays(DateUtil.diffDays(issueTime, now));
        }

        // 运行状态
        siteBasicInfo.setRunStatus(adwebSite.getRunStatus());

        siteBasicInfo.setDeliveryProgress(adwebSite.getSiteCurrentStep());
        if (StringUtils.isEmpty(siteBasicInfo.getDeliveryProgress())) {
            siteBasicInfo.setDeliveryProgress("已发布");
        }

        // 百分比, 老站状态只有为0， 相当于新状态1
        int siteStatus = adwebSite.getSiteFlowStatus() == null ? 0 : adwebSite.getSiteFlowStatus();

        if (siteStatus == 0) {
            siteStatus++;
        }

        siteBasicInfo.setSiteStatus(siteStatus);
        siteBasicInfo.setPercentage(siteStatus * 100 / 6);

        // 获取绑定的套餐信息
        SeoPlanSubscription history =
                seoPlanSubscriptionService.getCurrentSeoAndSiteSubscription(adwebSite.getId());
        String defaultPlanName = sysDictMapper.getDefaultPlanName();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        // 绑定时间(提单时间)
        // 如果没有绑定套餐或绑定的为默认建站套餐
        if (history == null
                || (StringUtils.isNotEmpty(defaultPlanName)
                        && defaultPlanName.equals(history.getPlanName()))) {
            siteBasicInfo.setCreateTime(dateFormat.format(adwebSite.getCreateTime()));
        } else {
            siteBasicInfo.setCreateTime(dateFormat.format(history.getCreateTime()));
        }

        // 套餐名称
        if (history == null || StringUtils.isEmpty(history.getPlanName())) {
            siteBasicInfo.setPlanName("暂无套餐");
        } else {
            siteBasicInfo.setPlanName(history.getPlanName());
        }

        // 预计服务到期时间
        if (history == null || history.getServiceMonth() == null) {
            return siteBasicInfo;
        }

        // 获取到期时间，需要判断到期时间是否是指定时间
        if (history.getServiceStatus() == 0) {
            Integer serverMonth = history.getServiceMonth();
            int remainServerDays = getRemainServerDays(serverMonth, userFlag, history.getId());
            if (remainServerDays > 0) {
                int giveDay = history.getGiveDay();
                int compensateDay = history.getCompensateDay();
                int totalGiveAndCompensateDay = giveDay + compensateDay;
                log.info(
                        "getSiteBasicInfo -- historyId:{},giveDay:{},compensateDay:{},totalGiveAndCompensateDay:{}",
                        history.getId(),
                        giveDay,
                        compensateDay,
                        totalGiveAndCompensateDay);
                Date serveEndTime = DateUtil.addDays(now, remainServerDays);
                log.info(
                        "getSiteBasicInfo -- 原来的serverEndTime:{}",
                        DateUtil.formatDate(serveEndTime, DateUtil.DATE_FORMAT));
                serveEndTime = DateUtil.addDays(serveEndTime, totalGiveAndCompensateDay);
                log.info(
                        "getSiteBasicInfo -- 增加赠、补天数:{},增加赠送天数、补偿天数后的serverEndTime:{}",
                        totalGiveAndCompensateDay,
                        DateUtil.formatDate(serveEndTime, DateUtil.DATE_FORMAT));
                siteBasicInfo.setEndTime(dateFormat.format(serveEndTime));
            } else {
                siteBasicInfo.setEndTime("服务已到期");
            }
        } else {
            Date serveEndTime = history.getServiceEndTime();
            int giveDay = history.getGiveDay();
            int compensateDay = history.getCompensateDay();
            int totalGiveAndCompensateDay = giveDay + compensateDay;
            log.info(
                    "getSiteBasicInfo -- historyId:{},giveDay:{},compensateDay:{},totalGiveAndCompensateDay:{}",
                    history.getId(),
                    giveDay,
                    compensateDay,
                    totalGiveAndCompensateDay);
            log.info(
                    "getSiteBasicInfo -- 原来的serverEndTime:{}",
                    DateUtil.formatDate(serveEndTime, DateUtil.DATE_FORMAT));
            serveEndTime = DateUtil.addDays(serveEndTime, totalGiveAndCompensateDay);
            log.info(
                    "getSiteBasicInfo -- 增加赠、补天数:{},赠送天数、补偿天数后的serverEndTime:{}",
                    totalGiveAndCompensateDay,
                    DateUtil.formatDate(serveEndTime, DateUtil.DATE_FORMAT));
            boolean isExpire = serveEndTime.compareTo(new Date()) <= 0;
            if (isExpire) {
                siteBasicInfo.setEndTime("服务已到期");
            } else {
                siteBasicInfo.setEndTime(dateFormat.format(serveEndTime));
            }
        }

        return siteBasicInfo;
    }

    /**
     * 获取站点剩下的服务天数
     *
     * @param serverMonth 套餐的服务天数
     * @param siteCode 站点的code
     * @return
     */
    public int getRemainServerDays(int serverMonth, String siteCode, String historyId) {
        int serverDay = (serverMonth * 30) + (serverMonth / 2);
        int reachStandardDays = this.getReachStandardDays(siteCode, historyId);
        return serverDay - reachStandardDays;
    }

    /**
     * 查询关键词达标天数
     *
     * @param siteCode 站点code
     * @param historyId 绑定的套餐
     * @return 关键词达标天数
     */
    public int getReachStandardDays(String siteCode, String historyId) {
        // 查询关键词达标天数
        //        int specifyKeywordNum = 0;
        //        int longTailKeywordNum = 0;
        //        QueryWrapper<SeoKpiStatistics> statisticsQueryWrapper = new QueryWrapper<>();
        //        statisticsQueryWrapper.eq("host_code", siteCode);
        //        statisticsQueryWrapper.eq("history_id", historyId);
        //        statisticsQueryWrapper.eq("del_flag", 0);
        //        statisticsQueryWrapper.eq("type", 1);
        //        List<SeoKpiStatistics> seoKpiStatisticsList =
        // seoKpiStatisticsService.list(statisticsQueryWrapper);
        //        if (ListUtil.notEmpty(seoKpiStatisticsList)) {
        //            for (SeoKpiStatistics kpiStatistics : seoKpiStatisticsList) {
        //                if ("APPOINT_KEYWORDS".equals(kpiStatistics.getKpiCode())) {
        //                    specifyKeywordNum = kpiStatistics.getKpiTarget() != null ?
        // kpiStatistics.getKpiTarget() : 0;
        //                } else if ("LONG_TAIL_KEYWORDS".equals(kpiStatistics.getKpiCode())) {
        //                    longTailKeywordNum = kpiStatistics.getKpiTarget() != null ?
        // kpiStatistics.getKpiTarget() : 0;
        //                }
        //            }
        //        }
        //        return commonMapper.getReachStandardDayNum(historyId,
        // commonMapper.getKeywordStandard(siteCode), specifyKeywordNum, longTailKeywordNum);
        return 0;
    }

    /**
     * 检测网站域名是否存在
     *
     * @param domain
     * @return
     */
    public List<AdwebSite> checkSiteDomainIsExists(String domain) {
        LambdaQueryWrapper<AdwebSite> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(AdwebSite::getDomain, domain);
        queryWrapper.ne(AdwebSite::getStatus, 0);
        return adwebSiteMapper.selectList(queryWrapper);
    }
}
