package com.docus.server.service.impl;

import com.docus.core.util.Func;
import com.docus.core.util.ListUtils;
import com.docus.core.util.json.JSON;
import com.docus.core.util.property.Setters;
import com.docus.infrastructure.redis.service.IdService;
import com.docus.infrastructure.web.exception.ApiException;
import com.docus.infrastructure.web.exception.ExceptionCode;
import com.docus.infrastructure.web.request.SearchDTO;
import com.docus.infrastructure.web.response.PageResult;
import com.docus.server.common.MsgConstants;
import com.docus.server.convert.SchCollectorConfigConvert;
import com.docus.server.dto.scheduling.management.schcollectorconfig.AddSchCollectorConfigDTO;
import com.docus.server.dto.scheduling.management.schcollectorconfig.DeleteSchCollectorConfigDTO;
import com.docus.server.dto.scheduling.management.schcollectorconfig.EditSchCollectorConfigDTO;
import com.docus.server.dto.scheduling.management.schterminator.CommMsgDTO;
import com.docus.server.entity.scheduling.management.SchCollectorConfig;
import com.docus.server.entity.scheduling.management.SchSystemParams;
import com.docus.server.enums.ConfigTypeEnum;
import com.docus.server.infrastructure.dao.ISchCollectorConfigDao;
import com.docus.server.infrastructure.dao.ISchSystemParamsDao;
import com.docus.server.service.ICommMsgService;
import com.docus.server.service.ISchCollectorConfigService;
import com.docus.server.vo.scheduling.management.schcollectorconfig.SchCollectorConfigVO;
import com.docus.server.vo.scheduling.management.schcollectorconfig.TcpSchCollectorConfigContentVO;
import com.docus.server.vo.scheduling.management.schcollectorconfig.TcpSchCollectorConfigVO;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 采集器配置 服务实现类
 *
 * @author AutoGenerator
 * @since 2023-07-15
 */
@Service
public class SchCollectorConfigServiceImpl implements ISchCollectorConfigService {
    @Resource
    private ISchCollectorConfigDao iSchCollectorConfigDao;
    @Resource
    private ISchSystemParamsDao iSchSystemParamsDao;
    @Resource
    private IdService idService;
    @Resource
    private ICommMsgService iCommMsgService;

    /**
     * 按主键查询
     *
     * @param id 主键Id
     * @return 实体
     */
    @Override
    public SchCollectorConfigVO findById(String id) {
        return SchCollectorConfigConvert.INSTANCE.convertVO(iSchCollectorConfigDao.findById(id));
    }

    @Override
    public List<SchCollectorConfigVO> findAll() {
        return SchCollectorConfigConvert.INSTANCE.convertVO(iSchCollectorConfigDao.findAll());
    }

    /**
     * 关键字搜索
     *
     * @param searchDTO 搜索参数
     * @return 分页列表
     */
    @Override
    public PageResult<SchCollectorConfigVO> search(SearchDTO searchDTO) {

        PageResult<SchCollectorConfigVO> result = SchCollectorConfigConvert.INSTANCE.convertVO(iSchCollectorConfigDao.search(searchDTO));
        if (CollectionUtils.isEmpty(result.getList())) {
            return new PageResult<>();
        }

        List<SchSystemParams> schSystemParams = iSchSystemParamsDao.findBy("paramValue", ListUtils.distinctSelect(result.getList(), SchCollectorConfigVO::getCollectorId));
        Map<String, SchSystemParams> taskConfigRetryLogMap = ListUtils.toMap(schSystemParams, SchSystemParams::getParamValue);

        Setters.<SchCollectorConfigVO>instance().list(result.getList()).cycleSetProperties(p -> {
            String collectorId = String.valueOf(p.getCollectorId());
            if (taskConfigRetryLogMap.containsKey(collectorId)) {
                p.setCollectorName(taskConfigRetryLogMap.get(collectorId).getParamName());
            } else {
                p.setCollectorName("公共");
            }
        });

        return result;
    }

    /**
     * 新增
     *
     * @param addSchCollectorConfigDTO 编辑参数
     * @return 成功或失败
     */
    @Override
    public boolean add(AddSchCollectorConfigDTO addSchCollectorConfigDTO) {

        Long collectorId = addSchCollectorConfigDTO.getCollectorId();

        SchCollectorConfig schCollectorConfigDO = iSchCollectorConfigDao.findOneBy("collectorId", collectorId);

        if (Func.notNull(schCollectorConfigDO)) {
            throw new ApiException(ExceptionCode.ParamIllegal.getCode(), "采集器类型已经存在");
        }

        SchCollectorConfig schCollectorConfig = SchCollectorConfigConvert.INSTANCE.convertDO(addSchCollectorConfigDTO);
        schCollectorConfig.setId(idService.getDateSeq());
        if (addSchCollectorConfigDTO.getConfigType().equals(ConfigTypeEnum.PUBLIC_CONFIG)) {
            schCollectorConfig.setCollectorId(0L); //共有类型
        }

        return iSchCollectorConfigDao.add(schCollectorConfig);

    }

    /**
     * 编辑
     *
     * @param editSchCollectorConfigDTO 编辑参数
     * @return 成功或失败
     */
    @Override
    public boolean edit(EditSchCollectorConfigDTO editSchCollectorConfigDTO) {
        SchCollectorConfig schCollectorConfig = iSchCollectorConfigDao.findById(editSchCollectorConfigDTO.getId());
        schCollectorConfig.setConfigJson(editSchCollectorConfigDTO.getConfigJson());
        return iSchCollectorConfigDao.edit(schCollectorConfig);
    }

    /**
     * 批量删除
     *
     * @param deleteSchCollectorConfigDTO 删除参数
     * @return 成功或失败
     */
    @Override
    public int delete(DeleteSchCollectorConfigDTO deleteSchCollectorConfigDTO) {
        return iSchCollectorConfigDao.delete(deleteSchCollectorConfigDTO.getIds());
    }

    /**
     * 更新采集器配置文件
     */
    @Override
    public void updateCollectorConfig() {
        List<SchCollectorConfig> publicConfig = iSchCollectorConfigDao.findBy("configType", ConfigTypeEnum.PUBLIC_CONFIG);
        List<SchCollectorConfig> privateConfig = iSchCollectorConfigDao.findBy("configType", ConfigTypeEnum.PRIVATE_CONFIG);

        List<TcpSchCollectorConfigVO> publicConfigVO = SchCollectorConfigConvert.INSTANCE.convertTcpVOList(publicConfig);
        List<TcpSchCollectorConfigVO> privateConfigVO = SchCollectorConfigConvert.INSTANCE.convertTcpVOList(privateConfig);

        TcpSchCollectorConfigContentVO tcpSchCollectorConfigVO = TcpSchCollectorConfigContentVO.builder()
            .publicConfigList(publicConfigVO)
            .privateConfigList(privateConfigVO)
            .build();

        CommMsgDTO commMsgDTO = CommMsgDTO.builder()
            .content(JSON.toJSON(tcpSchCollectorConfigVO))
            .messageType(MsgConstants.UPDATE_COLLECTOR_CONFIG)
            .build();

        iCommMsgService.clientsCommand(commMsgDTO);
    }
}

