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

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

import jakarta.annotation.Resource;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.FastJsonUtil;
import org.jeecg.modules.adweb.common.constant.AdwebConstant;
import org.jeecg.modules.adweb.common.util.DateUtil;
import org.jeecg.modules.adweb.enquiry.constant.EnquiryDistributeTypeConstant;
import org.jeecg.modules.adweb.site.entity.AdwebSite;
import org.jeecg.modules.adweb.subscription.entity.SubscribePlan;
import org.jeecg.modules.adweb.subscription.entity.UserPlanSubscription;
import org.jeecg.modules.adweb.subscription.service.ISubscribePlanService;
import org.jeecg.modules.adweb.subscription.service.IUserPlanSubscriptionService;
import org.jeecg.modules.adweb.theme.entity.AdwebTheme;
import org.jeecg.modules.adweb.theme.service.IAdwebThemeService;
import org.jeecg.modules.system.service.ISysUserTenantService;
import org.jeecg.modules.system.vo.SysUserTenantVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.transaction.Transactional;

@Service
@Slf4j
public class SelfWebSiteServiceCommon {

    @Value("${AdwebSiteConnect.tempDomain}")
    private String tempDomain;

    @Value("${serverIp.test}")
    private String newServerIp;

    @Resource private ISiteUserPermissionService siteUserPermissionService;

    @Resource private IAdwebSiteService adwebSiteService;

    @Resource private SiteManageService siteManageService;

    @Resource private IAdwebSiteService siteService;

    @Resource private IAdwebThemeService adwebThemeService;

    @Resource private IUserPlanSubscriptionService userPlanSubscriptionService;

    @Resource private ISubscribePlanService subscribePlanService;

    @Resource private ISysUserTenantService relationService;

    @Transactional
    public AdwebSite saveNewSiteInfo(
            Long tempId,
            String uid,
            String name,
            String planId,
            LoginUser sysUser,
            Integer giveDay,
            Integer compensateDay) {
        AdwebTheme adwebTheme = adwebThemeService.getById(tempId);
        if (adwebTheme == null) {
            log.error("未查询到模板数据退出执行，模板ID={}", tempId);
            return null;
        }
        // 站点CODE
        String siteCode = siteManageService.getSiteCode(null); // 自动生成临时站点code
        String domain = siteCode + "." + tempDomain;
        // 站点对象
        AdwebSite adwebSite = new AdwebSite();
        // 有效期  默认当前时间加1年
        Date endTime = DateUtil.addYear(DateUtil.getDate(), 1);

        adwebSite.setUid(uid);
        // 站点名称改为创建站点时必填字段

        adwebSite.setEtime(endTime);

        adwebSite.setRunStatus(1);
        adwebSite.setParentCode(adwebTheme.getCode());
        adwebSite.setTemplateDomain(adwebTheme.getDomain());
        adwebSite.setCreateType("wp");
        adwebSite.setName(name);
        // 域名
        adwebSite.setDomain("https://" + domain);
        adwebSite.setDomainDev(domain);
        // 站点code，此处保存
        adwebSite.setCode(siteCode);
        adwebSite.setInCode(adwebTheme.getCode());
        adwebSite.setIsDomain(0);
        adwebSite.setCtime(new Date());
        adwebSite.setStatus(3); // 临时站点正在创建
        adwebSite.setEnquiryDistributeType(EnquiryDistributeTypeConstant.MASTER);
        adwebSite.setDevServerIp(newServerIp);
        adwebSite.setEnquirySendEmailType("ALL");

        // wordpress 嵌入站默认配置
        adwebSite.setWordpressSetting(
                "{\"userAccount\":2,\"open\":\"\",\"productType\":\"adwebpro\",\"setting\":\"all\"}");
        adwebSite.setWordpressName("adweb-user");

        // 设置seo_job_status默认值为1（可见）
        adwebSite.setSeoJobStatus(1);

        // 租户状态，用户id,租户用户关系状态
        // 查询用户的租户ids
        List<String> tenantStatus = new ArrayList<>();
        tenantStatus.add("1");

        try {
            List<SysUserTenantVo> sysTenant =
                    relationService.getTenantListByUserId(uid, tenantStatus);
            if (sysTenant != null && !sysTenant.isEmpty()) {
                // 渠道商信息入库
                SysUserTenantVo firstTenant = sysTenant.get(0);
                adwebSite.setChannelProviderId(firstTenant.getTenantUserId());
                adwebSite.setChannelProviderName(firstTenant.getName());
            } else {
                log.warn("No tenant information found for user ID: {}", uid);
            }
        } catch (Exception e) {
            log.error("Error retrieving tenant list for user ID: {}", uid, e);
            // 可以根据业务需求决定是否抛出异常或进行其他处理
        }

        siteService.save(adwebSite);

        log.info("===================绑定套餐，套餐id：{}==========================", planId);
        log.info(FastJsonUtil.toJSONString(adwebSite));
        if (StringUtils.isNotBlank(planId)) {
            SubscribePlan subscribePlan = subscribePlanService.getById(planId);
            if (!"SEO".equals(subscribePlan.getPlanType())) {
                giveDay = 0;
                compensateDay = 0;
            }
            UserPlanSubscription subscription = new UserPlanSubscription();
            subscription.setPlanId(planId);
            subscription.setSiteId(adwebSite.getId() + "");
            subscription.setIsRenew(0);

            if (giveDay != null) {
                subscription.setGiveDay(giveDay);
            } else {
                subscription.setGiveDay(0);
            }
            if (compensateDay != null) {
                subscription.setCompensateDay(compensateDay);
            } else {
                subscription.setCompensateDay(0);
            }
            userPlanSubscriptionService.addUserPlanSubscription(subscription, sysUser);
        }

        log.info("================新站点授权===============");

        String siteName = "";
        LambdaQueryWrapper<AdwebSite> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdwebSite::getCode, siteCode);
        queryWrapper.ne(AdwebSite::getStatus, AdwebConstant.SITE_DEL);
        List<AdwebSite> list = adwebSiteService.list(queryWrapper);
        if (CollectionUtils.isNotEmpty(list)) {
            siteName = list.get(0).getName();
            siteUserPermissionService.insertSiteUserPermission(
                    adwebSite.getUid(), adwebSite.getCode(), siteName);
        } else {
            log.error("更新站点权限失败，该站点不存在，站点code为 {}", siteCode);
        }

        return adwebSite;
    }
}
