package com.yhy.module.core.service.workbench.impl;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.yhy.module.core.enums.ErrorCodeConstants.WB_COMPILE_TREE_NOT_EXISTS;
import static com.yhy.module.core.enums.ErrorCodeConstants.WB_ITEM_INFO_NODE_NOT_ITEM;

import cn.hutool.core.collection.CollUtil;
import com.yhy.module.core.controller.admin.workbench.vo.WbItemInfoRespVO;
import com.yhy.module.core.controller.admin.workbench.vo.WbItemInfoSaveReqVO;
import com.yhy.module.core.convert.workbench.WbItemInfoConvert;
import com.yhy.module.core.dal.dataobject.config.ConfigProjectInfoDO;
import com.yhy.module.core.dal.dataobject.workbench.WbCompileTreeDO;
import com.yhy.module.core.dal.dataobject.workbench.WbItemInfoDO;
import com.yhy.module.core.dal.dataobject.workbench.WbProjectTreeDO;
import com.yhy.module.core.dal.mysql.config.ConfigProjectInfoMapper;
import com.yhy.module.core.dal.mysql.workbench.WbCompileTreeMapper;
import com.yhy.module.core.dal.mysql.workbench.WbItemInfoMapper;
import com.yhy.module.core.dal.mysql.workbench.WbProjectTreeMapper;
import com.yhy.module.core.service.workbench.WbItemInfoService;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

/**
 * 单项基本信息 Service 实现类
 *
 * @author yhy
 */
@Service
@Validated
@Slf4j
public class WbItemInfoServiceImpl implements WbItemInfoService {

    @Resource
    private WbItemInfoMapper wbItemInfoMapper;

    @Resource
    private WbCompileTreeMapper wbCompileTreeMapper;

    @Resource
    private WbProjectTreeMapper wbProjectTreeMapper;

    @Resource
    private ConfigProjectInfoMapper configProjectInfoMapper;

    @Override
    public WbItemInfoRespVO getByCompileTreeId(Long compileTreeId) {
        // 1. 校验节点存在且是单项节点
        validateItemNode(compileTreeId);

        // 2. 查询单项基本信息
        WbItemInfoDO itemInfo = wbItemInfoMapper.selectByCompileTreeId(compileTreeId);
        if (itemInfo == null) {
            return null;
        }

        return WbItemInfoConvert.INSTANCE.convert(itemInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long save(WbItemInfoSaveReqVO saveReqVO) {
        // 1. 校验节点存在且是单项节点
        validateItemNode(saveReqVO.getCompileTreeId());

        // 2. 查询是否已存在
        WbItemInfoDO existInfo = wbItemInfoMapper.selectByCompileTreeId(saveReqVO.getCompileTreeId());

        if (existInfo != null) {
            // 更新
            existInfo.setInfoData(saveReqVO.getInfoData());
            wbItemInfoMapper.updateById(existInfo);
            return existInfo.getId();
        } else {
            // 新增
            WbItemInfoDO itemInfo = WbItemInfoConvert.INSTANCE.convert(saveReqVO);
            wbItemInfoMapper.insert(itemInfo);
            return itemInfo.getId();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void refreshConfigSnapshot(Long compileTreeId) {
        // 1. 校验节点存在且是单项节点
        WbCompileTreeDO node = validateItemNode(compileTreeId);

        // 2. 获取项目信息
        WbProjectTreeDO project = wbProjectTreeMapper.selectById(node.getProjectId());
        if (project == null) {
            return;
        }

        // 3. 获取项目的行业ID
        Long industryId = project.getIndustryId();
        if (industryId == null) {
            return;
        }

        // 4. 查询行业下的配置信息
        List<ConfigProjectInfoDO> configList = configProjectInfoMapper.selectListByConfigTreeId(industryId);

        // 5. 构建配置快照
        Map<String, Object> configSnapshot = buildConfigSnapshot(configList);

        // 6. 查询或创建单项基本信息
        WbItemInfoDO itemInfo = wbItemInfoMapper.selectByCompileTreeId(compileTreeId);
        if (itemInfo == null) {
            itemInfo = WbItemInfoDO.builder()
                    .compileTreeId(compileTreeId)
                    .configSnapshot(configSnapshot)
                    .infoData(new HashMap<>())
                    .build();
            wbItemInfoMapper.insert(itemInfo);
        } else {
            itemInfo.setConfigSnapshot(configSnapshot);
            wbItemInfoMapper.updateById(itemInfo);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByCompileTreeId(Long compileTreeId) {
        wbItemInfoMapper.deleteByCompileTreeId(compileTreeId);
    }

    /**
     * 校验节点存在且是单项节点
     */
    private WbCompileTreeDO validateItemNode(Long compileTreeId) {
        WbCompileTreeDO node = wbCompileTreeMapper.selectById(compileTreeId);
        if (node == null) {
            throw exception(WB_COMPILE_TREE_NOT_EXISTS);
        }
        if (!WbCompileTreeDO.NODE_TYPE_ITEM.equals(node.getNodeType())) {
            throw exception(WB_ITEM_INFO_NODE_NOT_ITEM);
        }
        return node;
    }

    /**
     * 构建配置快照
     */
    private Map<String, Object> buildConfigSnapshot(List<ConfigProjectInfoDO> configList) {
        Map<String, Object> snapshot = new HashMap<>();
        snapshot.put("snapshotTime", System.currentTimeMillis());

        if (CollUtil.isEmpty(configList)) {
            snapshot.put("configs", new ArrayList<>());
            return snapshot;
        }

        // 将配置列表转换为快照格式
        List<Map<String, Object>> configs = new ArrayList<>();
        for (ConfigProjectInfoDO config : configList) {
            Map<String, Object> configItem = new HashMap<>();
            configItem.put("id", config.getId());
            configItem.put("code", config.getCode());
            configItem.put("name", config.getName());
            configItem.put("content", config.getContent());
            configItem.put("parentId", config.getParentId());
            configItem.put("sortOrder", config.getSortOrder());
            configs.add(configItem);
        }
        snapshot.put("configs", configs);

        return snapshot;
    }
}
