package com.friday.distributor.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.friday.blank.api.dto.taskType.TaskTypeDetailDto;
import com.friday.blank.api.dto.taskType.TaskTypeProcessDto;
import com.friday.distributor.exception.DistributorRuntimeException;
import com.friday.distributor.mapper.BizConfigMapper;
import com.friday.base.common.response.DubboResult;
import com.friday.distributor.po.BizConfigPo;
import com.friday.operation.api.distributor.dto.BizConfigDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Author YaoYao
 * @Date Created In 14:34 2023/3/7
 * @Description 运行配置相关服务
 * @Modified By
 */
@Service
@Slf4j
public class TaskExecConfigService {
    @Autowired
    private PlatformInteractionService platformInteractionService;
    @Autowired
    private BizConfigMapper bizConfigMapper;

    private Map<String, TaskTypeDetailDto> generalConfigMap = new HashMap<>();

    public void setGeneralConfig(TaskTypeDetailDto detail){
        generalConfigMap.put(detail.getSchedule().getEmpId() + detail.getSchedule().getTaskType(), detail);
    }

    public DubboResult initGeneralConfig(){
        List<BizConfigPo> configPos = bizConfigMapper.selectAllConfig();
        int success = 0;
        int fail = 0;
        if (CollectionUtils.isNotEmpty(configPos)) {
            for (BizConfigPo configPo : configPos) {
                try {
                    String config = configPo.getDefaultConfig();
                    if (StringUtils.isNotEmpty(config)) {
                        TaskTypeDetailDto detail = JSON.parseObject(config, TaskTypeDetailDto.class);
                        this.setGeneralConfig(detail);
                        success++;
                    }
                } catch (Exception e) {
                    log.error("初始化配置异常！", e);
                    fail++;
                }
            }
            return DubboResult.newSuccess("总共"+configPos.size() + "个配置，成功：" + success + "，失败：" + fail);
        }
        return DubboResult.newSuccess("没有配置需要刷新");
    }

    public void deleteGeneralConfig(String taieTenant, String taskType){
        generalConfigMap.remove(taieTenant + taskType);
    }

    public TaskTypeDetailDto getTaskExecConfig(String taieTenant, String taskType){
        if(Objects.nonNull(generalConfigMap.get(taieTenant + taskType))){
            log.info("预制的管理端运行配置:{}-{}", taieTenant, taskType);
            return generalConfigMap.get(taieTenant + taskType);
        }
        TaskTypeDetailDto detail = platformInteractionService.getTaskExecConfig(taieTenant, taskType);
        if(Objects.isNull(detail.getRelatedProcess())){
            TaskTypeProcessDto defaultRelatedProcess = TaskTypeProcessDto.builder()
                    .processName("DefaultHandler")
                    .version("1.0.0")
                    .businessType("PROGRAM")
                    .build();
            detail.setRelatedProcess(defaultRelatedProcess);
        }
        return detail;
    }

    public DubboResult createBizConfig(BizConfigDto bizConfig){
        if(StringUtils.isAnyEmpty(bizConfig.getTaieTenant(), bizConfig.getTaskType(), bizConfig.getQueueKey())){
            return DubboResult.newFailure(DubboResult.CLIENT_EXCEPTION, "创建业务类运行配置缺少参数");
        }
        if(StringUtils.isAnyEmpty(bizConfig.getModule(), bizConfig.getHandler())){
            bizConfig.setModule("DefaultModule");
            bizConfig.setHandler("DefaultHandler");
        }
        BizConfigPo bizConfigPo = BizConfigPo.builder()
                .taieTenant(bizConfig.getTaieTenant())
                .taskType(bizConfig.getTaskType())
                .module(bizConfig.getModule())
                .handler(bizConfig.getHandler())
                .queueKey(bizConfig.getQueueKey())
                .build();
        BizConfigPo config = bizConfigMapper.selectConfig(bizConfig.getTaieTenant(), bizConfig.getTaskType());
        if(Objects.nonNull(config)){
            bizConfigPo.setId(config.getId());
            bizConfigMapper.updateBizConfig(bizConfigPo);
            return DubboResult.newSuccess();
        }
        bizConfigMapper.insertBizConfig(bizConfigPo);
        return DubboResult.newSuccess();
    }

    public BizConfigDto getBizConfig(String taieTenant, String taskType){
        BizConfigPo bizConfigPo = bizConfigMapper.selectConfig(taieTenant, taskType);
        if(Objects.isNull(bizConfigPo)){
            throw new DistributorRuntimeException("查询运行侧运行配置信息为空：", taieTenant, taskType);
        }
        return bizConfigPo.transferToDto();
    }

}
