package com.usky.data.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.usky.common.core.bean.ApiResult;
import com.usky.common.core.bean.CommonPage;
import com.usky.common.core.exception.BusinessException;
import com.usky.common.mybatis.core.AbstractCrudService;
import com.usky.common.security.utils.SecurityUtils;
import com.usky.data.domain.DataInterface;
import com.usky.data.mapper.DataInterfaceMapper;
import com.usky.data.service.DataInterfaceService;
import com.usky.data.service.util.InterfaceExecutor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 数据中心_数据接口表 服务实现类
 * </p>
 *
 * @author fyc
 * @since 2026-01-24
 */
@Service
@Slf4j
public class DataInterfaceServiceImpl extends AbstractCrudService<DataInterfaceMapper, DataInterface> implements DataInterfaceService {

    @Override
    public CommonPage<DataInterface> getDataInterfaceList(Integer currentPage, Integer pageSize, String keyword, String type, Integer enabledMark, String category) {

        // if (StringUtils.isBlank(category)) {
        //     throw new BusinessException("接口分类不能为空！");
        // }

        IPage<DataInterface> page = new Page<>(currentPage, pageSize);
        LambdaQueryWrapper<DataInterface> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(category), DataInterface::getCategory, category)
                .eq(DataInterface::getTenantId, SecurityUtils.getTenantId())
                .eq(DataInterface::getIsDelete, 0)
                .orderByDesc(DataInterface::getSortCode);
        queryWrapper.eq(StringUtils.isNotBlank(type), DataInterface::getType, type)
                .eq(enabledMark != null, DataInterface::getEnabledMark, enabledMark);
        if (StringUtils.isNotBlank(keyword)) {
            queryWrapper.like(DataInterface::getFullName, keyword)
                    .or()
                    .like(DataInterface::getEnCode, keyword);
        }
        page = baseMapper.selectPage(page, queryWrapper);
        return new CommonPage<>(page.getRecords(), page.getTotal(), page.getCurrent(), page.getSize());
    }

    @Override
    public CommonPage<DataInterface> getWorkflowList(Integer currentPage, Integer pageSize, String keyword, String type, Integer enabledMark) {
        IPage<DataInterface> page = new Page<>(currentPage, pageSize);
        LambdaQueryWrapper<DataInterface> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DataInterface::getTenantId, SecurityUtils.getTenantId())
                .like(StringUtils.isNotBlank(keyword), DataInterface::getFullName, keyword)
                .like(StringUtils.isNotBlank(keyword), DataInterface::getEnCode, keyword)
                .eq(StringUtils.isNotBlank(type), DataInterface::getType, type)
                .eq(enabledMark != null, DataInterface::getEnabledMark, enabledMark)
                .eq(DataInterface::getEnabledMark, 1); // 工作流选择时只显示启用的接口
        page = baseMapper.selectPage(page, queryWrapper);
        return new CommonPage<>(page.getRecords(), page.getTotal(), page.getCurrent(), page.getSize());
    }

    @Override
    public List<DataInterface> getSelectorList() {
        LambdaQueryWrapper<DataInterface> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DataInterface::getTenantId, SecurityUtils.getTenantId())
                .eq(DataInterface::getEnabledMark, 1); // 只返回启用的接口
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public String getInterfaceParameters(String id) {
        DataInterface entity = baseMapper.selectById(id);
        return entity != null ? entity.getParameterJson() : "[]";
    }

    @Override
    public boolean updateInterfaceStatus(String id) {
        DataInterface entity = baseMapper.selectById(id);
        if (entity == null) {
            return false;
        }
        // 切换启用状态
        entity.setEnabledMark(entity.getEnabledMark() == 1 ? 0 : 1);
        return baseMapper.updateById(entity) > 0;
    }

    @Override
    public ApiResult<?> testInterface(String id, Map<String, Object> params) {
        // 根据ID获取接口配置
        DataInterface interfaceEntity = baseMapper.selectById(id);
        if (interfaceEntity == null) {
            return ApiResult.error("接口不存在");
        }

        try {
            // 执行接口逻辑
            Object result = InterfaceExecutor.executeInterface(interfaceEntity, params);
            return ApiResult.success(result);
        } catch (Exception e) {
            return ApiResult.error("接口测试失败: " + e.getMessage());
        }
    }

    @Override
    public ApiResult<?> getInterfaceResponse(String id, Map<String, String> params) {
        // 这里是访问接口GET的实现，实际逻辑需要根据接口类型和配置进行处理
        DataInterface interfaceEntity = baseMapper.selectById(id);
        if (interfaceEntity == null) {
            return ApiResult.error("接口不存在");
        }

        try {
            // 将String类型的Map转换为Object类型的Map
            Map<String, Object> objectParams = new HashMap<>();
            if (params != null) {
                params.forEach((k, v) -> objectParams.put(k, v));
            }

            // 执行接口逻辑
            Object result = InterfaceExecutor.executeInterface(interfaceEntity, objectParams);
            return ApiResult.success(result);
        } catch (Exception e) {
            return ApiResult.error("接口访问失败: " + e.getMessage());
        }
    }

    @Override
    public ApiResult<?> postInterfaceResponse(String id, Map<String, String> params) {
        // 这里是访问接口POST的实现，实际逻辑需要根据接口类型和配置进行处理
        DataInterface interfaceEntity = baseMapper.selectById(id);
        if (interfaceEntity == null) {
            return ApiResult.error("接口不存在");
        }

        try {
            // 将String类型的Map转换为Object类型的Map
            Map<String, Object> objectParams = new HashMap<>();
            if (params != null) {
                params.forEach((k, v) -> objectParams.put(k, v));
            }

            // 执行接口逻辑
            Object result = InterfaceExecutor.executeInterface(interfaceEntity, objectParams);
            return ApiResult.success(result);
        } catch (Exception e) {
            return ApiResult.error("接口访问失败: " + e.getMessage());
        }
    }

    @Override
    public ApiResult<?> getInterfacePageData(String id, Map<String, Object> pageParams) {
        // 这里是获取接口分页数据的实现，实际逻辑需要根据接口类型和配置进行处理
        DataInterface interfaceEntity = baseMapper.selectById(id);
        if (interfaceEntity == null) {
            return ApiResult.error("接口不存在");
        }

        try {
            // 获取接口分页数据
            Map<String, Object> result = InterfaceExecutor.getInterfacePageData(interfaceEntity, pageParams);
            return ApiResult.success(result);
        } catch (Exception e) {
            return ApiResult.error("获取接口分页数据失败: " + e.getMessage());
        }
    }

    @Override
    public ApiResult<List<Map<String, Object>>> getInterfaceDetailData(String id, Map<String, Object> pageParams) {
        // 这里是获取接口详情数据的实现，实际逻辑需要根据接口类型和配置进行处理
        DataInterface interfaceEntity = baseMapper.selectById(id);
        if (interfaceEntity == null) {
            return ApiResult.error("接口不存在");
        }

        try {
            // 执行接口逻辑获取数据
            Object result = InterfaceExecutor.executeInterface(interfaceEntity, pageParams);

            // 转换结果为List<Map<String, Object>>类型
            List<Map<String, Object>> resultList = new ArrayList<>();
            if (result instanceof List) {
                List<?> listResult = (List<?>) result;
                for (Object item : listResult) {
                    if (item instanceof Map) {
                        @SuppressWarnings("unchecked")
                        Map<String, Object> mapItem = (Map<String, Object>) item;
                        resultList.add(mapItem);
                    }
                }
            }

            return ApiResult.success(resultList);
        } catch (Exception e) {
            return ApiResult.error("获取接口详情数据失败: " + e.getMessage());
        }
    }

    @Override
    public ApiResult<List<String>> getInterfaceFields(String id, Map<String, Object> pageParams) {
        // 这里是获取接口字段的实现，实际逻辑需要根据接口类型和配置进行处理
        DataInterface interfaceEntity = baseMapper.selectById(id);
        if (interfaceEntity == null) {
            return ApiResult.error("接口不存在");
        }

        try {
            // 获取接口字段
            List<String> fields = InterfaceExecutor.getInterfaceFields(interfaceEntity, pageParams);
            return ApiResult.success(fields);
        } catch (Exception e) {
            return ApiResult.error("获取接口字段失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Boolean deleteInterface(Long id) {
        LambdaQueryWrapper<DataInterface> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DataInterface::getId, id);
        DataInterface entity = baseMapper.selectOne(queryWrapper);
        String username = SecurityUtils.getUsername();

        if (entity == null) {
            log.warn("尝试删除不存在的接口，ID: {}，操作人{}", id, username);
            throw new BusinessException("接口不存在!");
        }

        entity.setIsDelete(1);
        entity.setDeleteTime(LocalDateTime.now());
        entity.setDeleteBy(username);

        return baseMapper.update(entity, queryWrapper) > 0;
    }


    @Override
    @Transactional
    public Boolean addInterface(DataInterface dataInterface) {
        Integer tenantId = SecurityUtils.getTenantId();
        if (!selectNameAndCode(dataInterface.getFullName(), dataInterface.getEnCode(), tenantId).isEmpty()) {
            throw new BusinessException("接口名称或编码已存在");
        }

        dataInterface.setCreateBy(SecurityUtils.getUsername());
        dataInterface.setCreateTime(LocalDateTime.now());
        dataInterface.setIsDelete(0);
        dataInterface.setEnabledMark(1);
        dataInterface.setTenantId(tenantId);
        return baseMapper.insert(dataInterface) > 0;
    }

    private List<DataInterface> selectNameAndCode(String name, String code, Integer tenantId) {
        LambdaQueryWrapper<DataInterface> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DataInterface::getTenantId, tenantId)
                .and(w -> w.eq(DataInterface::getFullName, name)
                        .or()
                        .eq(DataInterface::getEnCode, code));
        return baseMapper.selectList(queryWrapper);
    }


    @Override
    public Boolean updateInterface(DataInterface dataInterface) {

        if (dataInterface == null || dataInterface.getId() <= 0) {
            throw new BusinessException("接口id为空或不合规");
        }

        if (!selectNameAndCode(dataInterface.getFullName(), dataInterface.getEnCode(), dataInterface.getTenantId()).isEmpty()) {
            throw new BusinessException("接口名称或编码已存在");
        }

        dataInterface.setUpdateBy(SecurityUtils.getUsername());
        dataInterface.setUpdateTime(LocalDateTime.now());
        return baseMapper.updateById(dataInterface) > 0;
    }
}
