package com.xueyi.system.resource.service.impl;

import com.alibaba.cloud.nacos.NacosConfigManager;
import com.alibaba.nacos.api.exception.NacosException;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.xueyi.common.core.constant.nacos.NacosConstants;
import com.xueyi.system.api.digitalmans.domain.dto.DmManDeviceDto;
import com.xueyi.system.digitalmans.domain.query.DmManDeviceQuery;
import com.xueyi.system.digitalmans.service.IDmManDeviceService;
import com.xueyi.system.resource.domain.dto.DmH5ConfigDto;
import com.xueyi.system.resource.domain.query.DmH5ConfigQuery;
import com.xueyi.system.resource.manager.impl.DmH5ConfigManager;
import com.xueyi.system.resource.service.IDmH5ConfigService;
import com.xueyi.system.resource.manager.IDmH5ConfigManager;
import com.xueyi.common.web.entity.service.impl.BaseServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * H5配置表管理 服务层处理
 *
 * @author xueyi
 */
@Service
public class DmH5ConfigServiceImpl extends BaseServiceImpl<DmH5ConfigQuery, DmH5ConfigDto, IDmH5ConfigManager> implements IDmH5ConfigService {


    private static final Logger log = LoggerFactory.getLogger(DmH5ConfigManager.class);
    @Autowired
    NacosConfigManager nacosConfigManager;

    @Autowired
    IDmManDeviceService dmManDeviceService;



    /**
     * 查询H5配置表对象列表 | 数据权限
     *
     * @param h5Config H5配置表对象
     * @return H5配置表对象集合
     */
    @Override
    //@DataScope(userAlias = "createBy", mapperScope = {"DmH5ConfigMapper"})
    public List<DmH5ConfigDto> selectListScope(DmH5ConfigQuery h5Config) {
        List<DmH5ConfigDto> list = baseManager.selectList(h5Config);
        list.forEach(item-> {
            DmManDeviceQuery query = new DmManDeviceQuery();
            query.setTId(item.getEnterpriseId());
            DmManDeviceDto manDeviceDto = dmManDeviceService.selectList(query).stream().filter(device -> device.getTId().equals(item.getEnterpriseId())).findFirst().get();
            if (manDeviceDto != null) {
                item.setTenantName(manDeviceDto.getTenantName());
            }
        });
        return list;
    }

    @Override
    public int insert(DmH5ConfigDto dto) {
        // 获取基础配置文件
        try {
            String property = nacosConfigManager.getConfigService().getConfig(NacosConstants.DEFAULT_CONFIG_PATH, NacosConstants.DEFAULT_GROUP, 5000);
            // 设置新增配置文件名
            String[] strs = NacosConstants.DEFAULT_CONFIG_PATH.split("\\.");
            dto.setName(strs[0] + "_" + dto.getEnterpriseId() + "." + strs[1]);
            // 新增配置文件
            nacosConfigManager.getConfigService().publishConfig(dto.getName(), NacosConstants.DEFAULT_GROUP,property);
        } catch (NacosException ne) {
            log.error("H5配置表上传nacos-新增配置文件失败：{}", ne.getMessage());
        }

        return super.insert(dto);
    }

    @Override
    public int update(DmH5ConfigDto dto) {
        try {
            // 获取文件名
            nacosConfigManager.getConfigService().publishConfig(dto.getName(), NacosConstants.DEFAULT_GROUP,dto.getProperty());
        } catch (NacosException ne) {
            log.error("H5配置表上传nacos-修改配置文件失败：{}", ne.getMessage());
        }
        return super.update(dto);
    }

    @Override
    public DmH5ConfigDto selectById(Serializable id) {
        DmH5ConfigDto dto = super.selectById(id);
        try {
            dto.setProperty(nacosConfigManager.getConfigService().getConfig(dto.getName(), NacosConstants.DEFAULT_GROUP, 5000));
        } catch (NacosException ne) {
            log.error("H5配置表nacos-获取配置文件失败：{}", ne.getMessage());
        }
        return dto;
    }

    @Override
    public String syncH5Config(Long tId) {
        log.info("tenant_id:{}",tId);
        if (tId == null) {
            try {
                return nacosConfigManager.getConfigService().getConfig(NacosConstants.DEFAULT_CONFIG_PATH, NacosConstants.DEFAULT_GROUP, 5000);
            } catch (NacosException e) {
                log.error("H5同步-获取默认配置文件失败：{}", e.getMessage());
            }
        }
        DmH5ConfigQuery query = new DmH5ConfigQuery();
        query.setEnterpriseId(tId);
        List<DmH5ConfigDto> list = baseManager.selectList(query).stream().filter(item -> item.getEnterpriseId().equals(tId)).collect(Collectors.toList());
        if (list != null && list.size() > 0) {
            DmH5ConfigDto dto = list.get(0);
            if (dto != null) {
                try {
                    return nacosConfigManager.getConfigService().getConfig(dto.getName(), NacosConstants.DEFAULT_GROUP, 5000);
                } catch (NacosException ne) {
                    log.error("H5同步-获取配置文件失败：{}", ne.getMessage());
                    try {
                        return nacosConfigManager.getConfigService().getConfig(NacosConstants.DEFAULT_CONFIG_PATH, NacosConstants.DEFAULT_GROUP, 5000);
                    } catch (NacosException e) {
                        log.error("H5同步-获取默认配置文件失败：{}", e.getMessage());
                    }
                }
            }
        } else {
            try {
                return nacosConfigManager.getConfigService().getConfig(NacosConstants.DEFAULT_CONFIG_PATH, NacosConstants.DEFAULT_GROUP, 5000);
            } catch (NacosException e) {
                log.error("H5同步-获取默认配置文件失败：{}", e.getMessage());
            }
        }
        return "";
    }
}