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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.seo.entity.SeoPlanSubscription;
import org.jeecg.modules.adweb.seo.service.ISeoPlanSubscriptionService;
import org.jeecg.modules.adweb.site.entity.AdwebSite;
import org.jeecg.modules.adweb.subscribePlan.entity.SubscribePlan;
import org.jeecg.modules.adweb.subscribePlan.service.ISubscribePlanService;
import org.jeecg.modules.adweb.theme.entity.AdwebTheme;
import org.jeecg.modules.adweb.theme.service.IAdwebThemeService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class SelfWebSiteServiceCommon {

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

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

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

    @Resource
    private ISiteUserPermissionService siteUserPermissionService;

    @Resource
    private ISysUserService sysUserService;

    @Resource
    private IAdwebSiteService adwebSiteService;

    @Resource
    private SiteManageService siteManageService;

    @Resource
    private IAdwebSiteService siteService;

    @Resource
    private IAdwebThemeService adwebThemeService;

    @Resource
    private ISeoPlanSubscriptionService seoPlanSubscriptionService;

    @Resource
    private ISubscribePlanService subscribePlanService;

    @Transactional
    public AdwebSite saveNewSiteInfo(Long tempId, String uid, String name, String planId, LoginUser sysUser, Integer giveDay, Integer compensateDay) {
        AdwebSite adwebTemplate = siteService.getById(tempId);
        AdwebTheme adwebTheme = adwebThemeService.getById(tempId);
        if (adwebTemplate == 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);
        //TODO 改为NLB  cName
        adwebSite.setCname(tempCname);
        adwebSite.setUid(uid);
        //站点名称改为创建站点时必填字段
        adwebSite.setSiteType(AdwebConstant.SITE);
        adwebSite.setEtime(endTime);
        adwebSite.setManageUrl("https://" + domain + "/adweb-admin/");
        adwebSite.setRunStatus(1);
        adwebSite.setParentCode(adwebTheme.getCode());
        adwebSite.setCreateType("wp");
        adwebSite.setName(name);
        //域名
        adwebSite.setDomain("https://" + domain);
        adwebSite.setDomainDev(domain);
        //站点code，此处保存
        adwebSite.setCode(siteCode);
        adwebSite.setInCode(adwebTemplate.getInCode());
        adwebSite.setIsDomain(0);
        adwebSite.setCtime(new Date());
        adwebSite.setStatus(2);
        adwebSite.setEnquiryDistributeType(EnquiryDistributeTypeConstant.MASTER);
        adwebSite.setDevServerIp(newServerIp);
        adwebSite.setEnquirySendEmailType("ALL");

        //设置seo_job_status默认值为1（可见）
        adwebSite.setSeoJobStatus(1);
        SysUser user = sysUserService.getById(uid);
        String oemCode = user.getOemCode();
        if (StringUtils.isNotBlank(oemCode)) {
            adwebSite.setChannelProviderId(oemCode);//渠道商信息入库
            SysUser sUser = sysUserService.getOne(new QueryWrapper<SysUser>().eq("work_no", oemCode));
            if (sUser != null) {
                adwebSite.setChannelProviderName(sUser.getUsername());
            }
        }
        siteService.save(adwebSite);

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

            if (giveDay != null) {
                history.setGiveDay(giveDay);
            } else {
                history.setGiveDay(0);
            }
            if (compensateDay != null) {
                history.setCompensateDay(compensateDay);
            } else {
                history.setCompensateDay(0);
            }
            seoPlanSubscriptionService.addSeoPlanSubscription(history, sysUser);
        }

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

        String siteName = "";
        QueryWrapper<AdwebSite> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code", siteCode);
        queryWrapper.ne("status", 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;
    }

}
