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

import com.alibaba.cloud.nacos.NacosConfigManager;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.exception.NacosException;
import com.aliyun.tea.utils.StringUtils;
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.dto.DmDigitalmanDto;
import com.xueyi.system.digitalmans.domain.dto.DmDigitalmanExtDto;
import com.xueyi.system.digitalmans.domain.query.DmDigitalmanExtQuery;
import com.xueyi.system.digitalmans.domain.query.DmManDeviceQuery;
import com.xueyi.system.digitalmans.manager.IDmDigitalmanExtManager;
import com.xueyi.system.digitalmans.manager.IDmManDeviceManager;
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.ArrayList;
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;

    @Autowired
    IDmManDeviceManager dmManDeviceManager;


    /**
     * 查询H5配置表对象列表 | 数据权限
     *
     * @param h5Config H5配置表对象
     * @return H5配置表对象集合
     */
    @Override
    //@DataScope(userAlias = "createBy", mapperScope = {"DmH5ConfigMapper"})
    public List<DmH5ConfigDto> selectListScope(DmH5ConfigQuery h5Config) {
        List<DmH5ConfigDto> resultlist = new ArrayList<>();
        List<DmH5ConfigDto> list = baseManager.selectList(h5Config);
        list.forEach(item -> {
            DmManDeviceQuery query = new DmManDeviceQuery();
            query.setTId(item.getEnterpriseId());
            List<DmManDeviceDto> manDeviceDtos = dmManDeviceService.selectList(query).stream().filter(device -> device.getTId().equals(item.getEnterpriseId())).collect(Collectors.toList());
            if (!manDeviceDtos.isEmpty()) {
                for (int i = 0; i < manDeviceDtos.size(); i++) {
                    DmManDeviceDto items = manDeviceDtos.get(i);
                    String streamUrl = items.getStreamUrl();
                    if (!StringUtils.isEmpty(streamUrl)) {
                        DmH5ConfigDto temp = new DmH5ConfigDto();
                        temp.setTenantName(items.getTenantName());
                        temp.setManCode(items.getManCode());
                        try {
                            String property = nacosConfigManager.getConfigService().getConfig(item.getName(), NacosConstants.DEFAULT_GROUP, 5000);
                            JSONObject jo = JSON.parseObject(property);
                            if (jo.containsKey("system")) {
                                JSONObject sys = jo.getJSONObject("system");
                                if (sys.containsKey("H5")) {
                                    JSONObject H5 = sys.getJSONObject("H5");
                                    H5.put("streamUrl", streamUrl);
                                }
                            }
                            temp.setProperty(jo.toString());
                        } catch (NacosException ne) {
                            log.error("H5配置表上传nacos-获取配置文件失败：{}", ne.getMessage());
                        }
                        temp.setEnterpriseId(item.getEnterpriseId());
                        temp.setName(item.getName());
                        temp.setId(item.getId());
                        temp.setRemark(item.getRemark());
                        temp.setStatus(item.getStatus());
                        temp.setVersion(item.getVersion());
                        temp.setCreateBy(item.getCreateBy());
                        temp.setCreateTime(item.getCreateTime());
                        temp.setUpdateBy(item.getUpdateBy());
                        temp.setUpdateName(item.getUpdateName());
                        temp.setUpdateTime(item.getUpdateTime());
                        temp.setSourceName(item.getSourceName());
                        temp.setSort(item.getSort());
                        temp.setDelFlag(item.getDelFlag());
                        temp.setParams(item.getParams());
                        temp.setOperate(item.getOperate());
                        temp.setCreateName(item.getCreateName());
                        resultlist.add(temp);
                    }
                }
            }
        });
        return resultlist;
    }

    @Override
    public int insert(DmH5ConfigDto dto) {
        int row = 1;
        // 设置新增配置文件名
        String[] strs = NacosConstants.DEFAULT_CONFIG_PATH.split("\\.");
        dto.setName(strs[0] + "_" + dto.getEnterpriseId() + "." + strs[1]);
        // 获取基础配置文件
        try {
            DmH5ConfigQuery query = new DmH5ConfigQuery();
            query.setEnterpriseId(dto.getEnterpriseId());
            List<DmH5ConfigDto> result = baseManager.selectList(query);
            if (result.isEmpty()) {
                String property = nacosConfigManager.getConfigService().getConfig(NacosConstants.DEFAULT_CONFIG_PATH, NacosConstants.DEFAULT_GROUP, 5000);
                // 新增配置文件
                nacosConfigManager.getConfigService().publishConfig(dto.getName(), NacosConstants.DEFAULT_GROUP, property);
                row = super.insert(dto);
            }
        } catch (NacosException ne) {
            log.error("H5配置表上传nacos-新增配置文件失败：{}", ne.getMessage());
        }
        strs = NacosConstants.DEFAULT_CONFIG_PATH.split("\\.");
        dto.setName(strs[0] + "_" + dto.getEnterpriseId() + "." + strs[1]);
        DmManDeviceQuery query = new DmManDeviceQuery();
        query.setManCode(dto.getManCode());
        List<DmManDeviceDto> mdList = dmManDeviceManager.selectList(query);
        if (mdList != null && mdList.size() > 0) {
            DmManDeviceDto target = mdList.get(0);
            try {
                String property = nacosConfigManager.getConfigService().getConfig(dto.getName(), NacosConstants.DEFAULT_GROUP, 5000);
                JSONObject jo = JSON.parseObject(property);
                if (jo.containsKey("system")) {
                    JSONObject sys = jo.getJSONObject("system");
                    if (sys.containsKey("H5")) {
                        JSONObject H5 = sys.getJSONObject("H5");
                        String streamUrl = H5.getString("streamUrl");
                        target.setStreamUrl(streamUrl);
                        dmManDeviceManager.update(target);
                    }
                }
            } catch (NacosException ne) {
                log.error("H5配置表上传nacos-新增配置文件失败：{}", ne.getMessage());
            }
        }
        return row;
    }

    @Override
    public int update(DmH5ConfigDto dto) {
        String[] strs = NacosConstants.DEFAULT_CONFIG_PATH.split("\\.");
        dto.setName(strs[0] + "_" + dto.getEnterpriseId() + "." + strs[1]);
        try {
            // 获取文件名
            nacosConfigManager.getConfigService().publishConfig(dto.getName(), NacosConstants.DEFAULT_GROUP, dto.getProperty());
        } catch (NacosException ne) {
            log.error("H5配置表上传nacos-修改配置文件失败：{}", ne.getMessage());
        }
        if (StringUtils.isEmpty(dto.getManCode())) {
            return super.update(dto);
        }
        DmManDeviceQuery query = new DmManDeviceQuery();
        query.setManCode(dto.getManCode());
        List<DmManDeviceDto> mdList = dmManDeviceManager.selectList(query);
        if (mdList != null && mdList.size() > 0) {
            DmManDeviceDto target = mdList.get(0);
            try {
                String property = nacosConfigManager.getConfigService().getConfig(dto.getName(), NacosConstants.DEFAULT_GROUP, 5000);
                JSONObject jo = JSON.parseObject(property);
                if (jo.containsKey("system")) {
                    JSONObject sys = jo.getJSONObject("system");
                    if (sys.containsKey("H5")) {
                        JSONObject H5 = sys.getJSONObject("H5");
                        String streamUrl = H5.getString("streamUrl");
                        target.setStreamUrl(streamUrl);
                        dmManDeviceManager.update(target);
                    }
                }
            } 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;
    }

    public DmH5ConfigDto selectbyIdCode(Serializable id, String manCode) {
        DmH5ConfigDto dto = super.selectById(id);
        dto.setManCode(manCode);
        String result = null;
        try {
            result = nacosConfigManager.getConfigService().getConfig(dto.getName(), NacosConstants.DEFAULT_GROUP, 5000);
        } catch (NacosException ne) {
            log.error("H5配置表nacos-获取配置文件失败：{}", ne.getMessage());
        }
        DmManDeviceQuery query = new DmManDeviceQuery();
        query.setManCode(manCode);
        List<DmManDeviceDto> mdList = dmManDeviceManager.selectList(query);
        if (mdList != null && mdList.size() > 0) {
            String streamUrl = mdList.get(0).getStreamUrl();
            if (StringUtils.isEmpty(streamUrl)) {
                return null;
            }
            JSONObject jo = JSON.parseObject(result);
            if (jo.containsKey("system")) {
                JSONObject sys = jo.getJSONObject("system");
                if (sys.containsKey("H5")) {
                    JSONObject H5 = sys.getJSONObject("H5");
                    H5.put("streamUrl", streamUrl);
                }
            }
            result = jo.toString();
            dto.setProperty(result);
        }
        return dto;
    }

    @Override
    public String syncH5Config(Long tId, String manCode) {
        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 {
                    String result = "";
                    result = nacosConfigManager.getConfigService().getConfig(dto.getName(), NacosConstants.DEFAULT_GROUP, 5000);
                    if (StringUtils.isEmpty(manCode)) {
                        return result;
                    } else {
                        DmManDeviceQuery query2 = new DmManDeviceQuery();
                        query2.setManCode(manCode);
                        List<DmManDeviceDto> extList = dmManDeviceManager.selectList(query2);
                        if (extList != null && extList.size() > 0) {
                            String streamUrl = extList.get(0).getStreamUrl();
                            if (!StringUtils.isEmpty(streamUrl)) {
                                JSONObject jo = JSON.parseObject(result);
                                if (jo.containsKey("system")) {
                                    JSONObject sys = jo.getJSONObject("system");
                                    if (sys.containsKey("H5")) {
                                        JSONObject H5 = sys.getJSONObject("H5");
                                        H5.put("streamUrl", streamUrl);
                                    }
                                }
                                result = jo.toString();
                                return result;
                            } else {
                                return result;
                            }
                        }
                    }
                } 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 "";
    }

    public int deleteByIdCode(Serializable id, String manCode) {
        DmH5ConfigDto dto = super.selectById(id);
        if (dto != null) {
            try {
                String result = nacosConfigManager.getConfigService().getConfig(dto.getName(), NacosConstants.DEFAULT_GROUP, 5000);
            } catch (NacosException ne) {
                log.error("H5配置表nacos-删除配置文件失败：{}", ne.getMessage());
            }
        }
        DmManDeviceQuery query = new DmManDeviceQuery();
        query.setManCode(manCode);
        List<DmManDeviceDto> mdList = dmManDeviceManager.selectList(query);
        if (mdList != null && mdList.size() > 0) {
            DmManDeviceDto target = mdList.get(0);
            target.setStreamUrl("");
            dmManDeviceManager.update(target);
        }
        return 1;
    }
}