package cn.axzo.msg.center.message.xxl;

import cn.axzo.msg.center.dal.MessageRouterConfigDao;
import cn.axzo.msg.center.domain.entity.MessageRouterConfig;
import cn.axzo.msg.center.service.enums.TerminalTypeEnum;
import com.xxl.job.core.biz.model.ReturnT;
import cn.axzo.infra.xxl220to250.IJobHandler;
import com.xxl.job.core.handler.annotation.XxlJob;
import cn.axzo.infra.xxl220to250.XxlJobLogger;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * @author yanglin
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class AppendWorkspaceTypeJob extends IJobHandler {

    private final MessageRouterConfigDao messageRouterConfigDao;

    @Override
    @Transactional
    @XxlJob("appendWorkspaceTypeJob")
    public ReturnT<String> execute(String param) throws Exception {
        List<MessageRouterConfig> configs = messageRouterConfigDao.lambdaQuery()
                .in(MessageRouterConfig::getTerminalType, Arrays.asList(
                        TerminalTypeEnum.ANDROID, TerminalTypeEnum.IOS,
                        TerminalTypeEnum.MINI_PROGRAM, TerminalTypeEnum.WEB_VIEW))
                .list();
        for (MessageRouterConfig config : configs) {
            maybeAppendWorkspaceType(config);
        }
        return ReturnT.SUCCESS;
    }

    private void maybeAppendWorkspaceType(MessageRouterConfig config) throws Exception {
        if (StringUtils.isBlank(config.getUrl()))
            return;
        String url = config.getUrl();
        if (!url.contains("workspaceId="))
            return;
        int idx1 = url.indexOf("?");
        int idx2 = url.indexOf("workspaceType=");
        if (idx1 > -1 && idx2 > idx1) return;
        if (idx1 > -1) {
            if (url.endsWith("&")) {
                url += "workspaceType=2";
            } else {
                if (idx1 == url.length() - 1) {
                    url += "workspaceType=2";
                } else {
                    url += "&workspaceType=2";
                }
            }
        } else {
            if (url.endsWith("?")) {
                url += "workspaceType=2";
            } else {
                url += "?workspaceType=2";
            }
        }
        messageRouterConfigDao.lambdaUpdate()
                .eq(MessageRouterConfig::getId, config.getId())
                .set(MessageRouterConfig::getUrl, url)
                .update();
        XxlJobLogger.log("append workspaceType success, id: {}, routerCode: {}, url: {}",
                config.getId(), config.getRouterCode(), url);
    }

}