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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xkcoding.http.util.StringUtil;
import jakarta.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.FastJsonUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.adweb.common.constant.NumConstant;
import org.jeecg.modules.adweb.site.constant.WordPressConstants;
import org.jeecg.modules.adweb.site.dto.WordPressConfig;
import org.jeecg.modules.adweb.site.entity.AdwebSite;
import org.jeecg.modules.adweb.site.entity.AdwebUserWpsite;
import org.jeecg.modules.adweb.site.mapper.AdwebSiteMapper;
import org.jeecg.modules.adweb.site.service.IAdwebSiteService;
import org.jeecg.modules.adweb.site.service.IAdwebUserWpsiteService;
import org.jeecg.modules.adweb.site.service.ISiteUserPermissionService;
import org.jeecg.modules.system.mapper.SysUserRoleMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description: adweb站点配置表单
 * @Author: jeecg-boot
 * @Date: 2024-09-29
 * @Version: V1.0
 */
@Service
public class AdwebSiteServiceImpl extends ServiceImpl<AdwebSiteMapper, AdwebSite> implements IAdwebSiteService {


    @Resource
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private IAdwebUserWpsiteService adwebUserWpsiteService;

    @Autowired
    private ISiteUserPermissionService siteUserPermissionService;

    private final RedisUtil redisUtil;

    public AdwebSiteServiceImpl(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    /**
     * 查询wordpress站点配置
     *
     * @param siteCode
     */
    @Override
    public WordPressConfig queryWordPressConfig(String siteCode) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        WordPressConfig config = new WordPressConfig();
        if (StringUtils.isBlank(siteCode)) {
            return config;
        }
        try {
            List<AdwebSite> list = this.list(new LambdaQueryWrapper<AdwebSite>()
                    .eq(AdwebSite::getCode, siteCode));
            if (!list.isEmpty()) {
                AdwebSite adwebSite = list.get(0);
                BeanUtils.copyProperties(adwebSite, config);
                // 开启WP&未上线站点
                if (adwebSite.getStatus() == NumConstant.TWO.intValue() && adwebSite.getWordpressSwitch() == NumConstant.ONE.intValue()) {
                    String domainDev = adwebSite.getDomainDev();
                    domainDev = domainDev.replaceAll("https://", "").replaceAll("http://", "");
                    domainDev = "https://" + domainDev;
                    config.setDomain(domainDev);
                }
                config.setSiteCode(adwebSite.getCode());
                String ssoResKeyName = WordPressConstants.SSO_RES_KEY_NAME + siteCode;
                if (redisUtil.hasKey(ssoResKeyName)) {
                    String ssoResKey = String.valueOf(redisUtil.get(ssoResKeyName));
                    config.setSsoResKey(ssoResKey);
                }

                config.setWordpressName("adweb-user");
                //处理WordPress配置数据
                if (StringUtils.isNotBlank(adwebSite.getWordpressSetting())) {
                    Map<String, Object> wordpressSettingMap = FastJsonUtil.parseObject(adwebSite.getWordpressSetting(), Map.class);
                    int userAccount = 2;

                    if (wordpressSettingMap.get("userAccount") != null) {
                        userAccount = Integer.parseInt(wordpressSettingMap.get("userAccount").toString());
                        if (userAccount == 1) {
                            if (loginUser != null) {
                                List<String> role = sysUserRoleMapper.getRoleByUserName(loginUser.getUsername());
                                if (role.toString().contains("adweb_sub_vip") || role.toString().contains("adweb_vip")) {
                                    List<AdwebUserWpsite> adwebUserWpsites = adwebUserWpsiteService.getSitesByUid(loginUser.getId());
                                    config.setWordpressName(adwebUserWpsites.get(0).getWpUsername());
                                } else if (role.toString().contains("admin") || role.toString().contains("adweb_seo_manager") || role.toString().contains("adweb_site_manager") || role.toString().contains("adweb_oem")) {
                                    List<AdwebUserWpsite> sites = adwebUserWpsiteService.getSitesByUid(adwebSite.getUid());
                                    config.setWordpressName(sites.get(0).getWpUsername());
                                }
                            }
                        }
                    }

                    if (wordpressSettingMap.size() == 1) {
                        config.setProductType(wordpressSettingMap.get("productType").toString());
                    } else {
                        config.setWordpressSetting(wordpressSettingMap.get("setting").toString());
                        List<String> open = FastJsonUtil.parseList(wordpressSettingMap.get("open").toString(), String.class);
                        if (CollectionUtils.isNotEmpty(open)) {
                            config.setOpenSetting(open);
                        }
                        if (wordpressSettingMap.size() > 2) {
                            config.setProductType(wordpressSettingMap.get("productType").toString());
                        }
                    }

                }

            }
        } catch (Exception e) {
            log.error("查询wordpress站点配置失败", e);
        }
        return config;
    }

    /**
     * @param id 站点id
     * @return
     */
    @Override
    public String getSiteCodeById(Integer id) {
        AdwebSite adwebSite = this.getById(id);
        if (adwebSite == null) {
            return null;
        }
        return adwebSite.getCode();
    }

    /**
     * 根据站点id获取主站点的siteCode，如果站点本身就是主站点，则返回自身的code
     *
     * @param siteId 站点id
     * @return 父站点code
     */
    @Override
    public List<Integer> getAllSiteIdBySiteId(Integer siteId) {
        AdwebSite adwebSite = this.getById(siteId);
        if (StringUtil.isEmpty(adwebSite.getParentGroupCode())) {
            return this.getAllSiteIdByParentId(siteId);
        }

        String code = adwebSite.getParentGroupCode();
        QueryWrapper<AdwebSite> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code", code).or().eq("parent_code", code);
        List<AdwebSite> siteList = this.list(queryWrapper);
        List<Integer> siteIds = new ArrayList<>();
        for (AdwebSite site : siteList) {
            siteIds.add(site.getId());
        }
        return siteIds;
    }

    /**
     * 根据父站点id获取站群所有id
     *
     * @param parentId 父站点id
     * @return 父站点id和子站点id
     */
    @Override
    public List<Integer> getAllSiteIdByParentId(Integer parentId) {
        String siteCode = this.getSiteCodeById(parentId);
        QueryWrapper<AdwebSite> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code", siteCode).or().eq("parent_code", siteCode);
        List<AdwebSite> siteList = this.list(queryWrapper);
        List<Integer> siteIds = new ArrayList<>();
        for (AdwebSite site : siteList) {
            siteIds.add(site.getId());
        }
        return siteIds;
    }

    /**
     * 根据siteCode返回站点信息
     *
     * @param siteCode
     * @return
     */
    @Override
    public AdwebSite getSiteByCode(String siteCode) {
        try {
            List<AdwebSite> adwebSites = this.list(new LambdaQueryWrapper<AdwebSite>()
                    .eq(AdwebSite::getCode, siteCode)
                    .ne(AdwebSite::getStatus, 0));
            if (!adwebSites.isEmpty()) {
                return adwebSites.get(0);
            }
        } catch (Exception e) {
            log.error("获取站点失败, code = " + siteCode, e);
        }
        return null;
    }

    /**
     * 根据用户id查询所有未删除的站点
     *
     * @param uid 用户id
     * @return 站点id
     */
    @Override
    public List<Integer> getAllSiteIdByUid(String uid) {
        List<AdwebSite> siteList = null;
        try {
            List<String> codeList = siteUserPermissionService.getSiteCodeList(uid);
            siteList = this.list(new LambdaQueryWrapper<AdwebSite>()
                    .ne(AdwebSite::getStatus, 0).in(AdwebSite::getCode, codeList));
        } catch (Exception e) {
            log.error("查询用户站点失败");
        }

        List<Integer> siteIds = new ArrayList<>();
        for (AdwebSite site : siteList) {
            siteIds.add(site.getId());
        }
        return siteIds;
    }

    /**
     * 查询全部有效的站点code
     */
    @Override
    public List<String> getAllActiveSiteCodes() {
        return this.list(
                        new LambdaQueryWrapper<AdwebSite>()
                                .eq(AdwebSite::getStatus, 1)
                                .eq(AdwebSite::getRunStatus, 1))
                .stream()
                .map(AdwebSite::getCode)
                .toList();
    }
}
