package cd.casic.ci.process.process.service.resource.impl;

import cd.casic.ci.process.dto.req.resource.ResourceQueryReq;
import cd.casic.ci.process.dto.req.resource.ResourceReq;
import cd.casic.ci.process.dto.resp.resource.ResourceFindResp;
import cd.casic.ci.process.dto.resp.taskResource.TaskResourceFindResp;
import cd.casic.ci.process.process.converter.ResourceConverter;
import cd.casic.ci.process.process.dao.pipeline.PipResourceCloudDao;
import cd.casic.ci.process.process.dao.pipeline.PipResourceK8SDao;
import cd.casic.ci.process.process.dao.pipeline.PipResourceMachineDao;
import cd.casic.ci.process.process.dao.pipeline.PipResourceManagerDao;
import cd.casic.ci.process.process.dataObject.resource.PipResourceCloud;
import cd.casic.ci.process.process.dataObject.resource.PipResourceK8S;
import cd.casic.ci.process.process.dataObject.resource.PipResourceMachine;
import cd.casic.ci.process.process.dataObject.resource.PipResourceManager;
import cd.casic.ci.process.process.service.resource.ResourceManagerService;
import cd.casic.framework.commons.exception.ServiceException;
import cd.casic.framework.commons.exception.enums.GlobalErrorCodeConstants;
import cd.casic.framework.commons.pojo.PageResult;
import cd.casic.framework.security.dal.user.AdminUserDO;
import cd.casic.framework.tenant.core.service.AdminUserServiceImpl;
import cd.casic.module.execute.docker.dao.DockerEndpointDao;
import cd.casic.module.execute.docker.dataobject.dto.DockerEndpointDo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author HopeLi
 * @version v1.0
 * @ClassName ResourceServiceImpl
 * @Date: 2025/5/13 10:31
 * @Description:
 */
@Service
@Slf4j
public class ResourceManagerServiceImpl extends ServiceImpl<PipResourceManagerDao, PipResourceManager> implements ResourceManagerService {
    @Resource
    private PipResourceManagerDao pipResourceManagerDao;

    @Resource
    private PipResourceMachineDao machineDao;

    @Resource
    private DockerEndpointDao dockerEndpointDao;

    @Resource
    private PipResourceK8SDao k8SDao;

    @Resource
    private PipResourceCloudDao cloudDao;

    @Resource
    private AdminUserServiceImpl adminUserService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public String createResource(ResourceReq resourceReq) {

        PipResourceManager pipResourceManager = ResourceConverter.INSTANCE.toBean(resourceReq);

        //如果资源类型不属于弹性云，则新增，如果属于弹性云，则走申请流程
        if (!ObjectUtils.isEmpty(resourceReq.getResourceMachine())){
            PipResourceMachine resourceMachine = resourceReq.getResourceMachine();
            machineDao.insert(resourceMachine);

            pipResourceManager.setMachineId(resourceMachine.getId());
        }
        if (!ObjectUtils.isEmpty(resourceReq.getPipResourceK8S())) {
            PipResourceK8S pipResourceK8S = resourceReq.getPipResourceK8S();
            k8SDao.insert(pipResourceK8S);

            pipResourceManager.setK8sId(pipResourceK8S.getId());
        }
        if (!ObjectUtils.isEmpty(resourceReq.getDockerEndpoint())) {
            DockerEndpointDo dockerEndpoint = resourceReq.getDockerEndpoint();
            dockerEndpointDao.insert(dockerEndpoint);

            pipResourceManager.setDockerId(dockerEndpoint.getId());
        }

        if (!ObjectUtils.isEmpty(resourceReq.getPipResourceCloud())) {
            PipResourceCloud pipResourceCloud = resourceReq.getPipResourceCloud();
            cloudDao.insert(pipResourceCloud);

            pipResourceManager.setCloudId(pipResourceCloud.getId());
        }

        pipResourceManagerDao.insert(pipResourceManager);
        return pipResourceManager.getId();
    }

    @Override
    public void deleteResource(String id) {
        PipResourceManager pipResourceManager = pipResourceManagerDao.selectById(id);
        if (!StringUtils.isEmpty(pipResourceManager.getMachineId())){
            machineDao.deleteById(pipResourceManager.getMachineId());
        }
        if (!StringUtils.isEmpty(pipResourceManager.getK8sId())){
            k8SDao.deleteById(pipResourceManager.getK8sId());
        }
        if (!StringUtils.isEmpty(pipResourceManager.getDockerId())){
            dockerEndpointDao.deleteById(pipResourceManager.getDockerId());
        }
        if (!StringUtils.isEmpty(pipResourceManager.getCloudId())){
            cloudDao.deleteById(pipResourceManager.getCloudId());
        }
        pipResourceManagerDao.deleteById(id);
    }

    @Override
    public void updateResource(ResourceReq resourceReq) {
        PipResourceManager temp = pipResourceManagerDao.selectById(resourceReq.getId());
        temp.setResourceName(resourceReq.getResourceName());

        //先删除旧的资源信息
        if (!StringUtils.isEmpty(temp.getMachineId())){
            machineDao.deleteById(temp.getMachineId());
        }


        if (!StringUtils.isEmpty(temp.getK8sId())){
            k8SDao.deleteById(temp.getK8sId());

        }

        if (!StringUtils.isEmpty(temp.getDockerId())){
            dockerEndpointDao.deleteById(temp.getDockerId());

        }

        if (!StringUtils.isEmpty(temp.getCloudId())){
            cloudDao.deleteById(temp.getCloudId());

        }


        //根据新资源信息新增
        if (!ObjectUtils.isEmpty(resourceReq.getResourceMachine())){
            PipResourceMachine resourceMachine = resourceReq.getResourceMachine();
            machineDao.insert(resourceMachine);

            temp.setMachineId(resourceMachine.getId());
        }
        if (!ObjectUtils.isEmpty(resourceReq.getPipResourceK8S())) {
            PipResourceK8S pipResourceK8S = resourceReq.getPipResourceK8S();
            k8SDao.insert(pipResourceK8S);

            temp.setK8sId(pipResourceK8S.getId());
        }
        if (!ObjectUtils.isEmpty(resourceReq.getDockerEndpoint())) {
            DockerEndpointDo dockerEndpoint = resourceReq.getDockerEndpoint();
            dockerEndpointDao.insert(dockerEndpoint);

            temp.setDockerId(dockerEndpoint.getId());
        }

        if (!ObjectUtils.isEmpty(resourceReq.getPipResourceCloud())) {
            PipResourceCloud pipResourceCloud = resourceReq.getPipResourceCloud();
            cloudDao.insert(pipResourceCloud);

            temp.setCloudId(pipResourceCloud.getId());
        }
        pipResourceManagerDao.updateById(temp);
    }

    @Override
    public ResourceFindResp findResourceById(String id) {
        PipResourceManager pipResourceManager = pipResourceManagerDao.selectById(id);
        if (ObjectUtils.isEmpty(pipResourceManager)){
            throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(),"资源不存在");
        }
        ResourceFindResp resp = ResourceConverter.INSTANCE.toResp(pipResourceManager);

        setResource(resp);
        setUserName(resp);
        return resp;
    }



    @Override
    public List<ResourceFindResp> findResourceList(ResourceQueryReq query) {
        QueryWrapper<PipResourceManager> wrapper = new QueryWrapper<>();
        if (!ObjectUtils.isEmpty(query.getId())){
            wrapper.eq("id",query.getId());
        }
        if (!ObjectUtils.isEmpty(query.getIdList())){
            wrapper.in("id",query.getId());
        }
        if (!ObjectUtils.isEmpty(query.getResourceName())){
            wrapper.like("resource_name",query.getResourceName());
        }
        if (!ObjectUtils.isEmpty(query.getMachineId())){
            wrapper.eq("machine_id",query.getMachineId());
        }
        if (!ObjectUtils.isEmpty(query.getK8sId())){
            wrapper.eq("k8s_id",query.getK8sId());
        }
        if (!ObjectUtils.isEmpty(query.getDockerId())){
            wrapper.eq("docker_id",query.getDockerId());
        }
        if (!ObjectUtils.isEmpty(query.getCloudId())){
            wrapper.eq("cloud_id",query.getCloudId());
        }
        if (!ObjectUtils.isEmpty(query.getCreator())){
            wrapper.eq("creator",query.getCreator());
        }
        List<PipResourceManager> pipResourceManagerList = pipResourceManagerDao.selectList(wrapper);

        if (ObjectUtils.isEmpty(pipResourceManagerList)){
            return new ArrayList<>(0);
        }

        List<ResourceFindResp> respList = ResourceConverter.INSTANCE.toRespList(pipResourceManagerList);

        //对资源进行赋值
        respList.forEach(this::setResource);
        respList.forEach(this::setUserName);

        return respList;
    }

    @Override
    public PageResult<ResourceFindResp> findResourcePage(ResourceQueryReq query) {

        QueryWrapper<PipResourceManager> wrapper = new QueryWrapper<>();
        if (!ObjectUtils.isEmpty(query.getId())){
            wrapper.eq("id",query.getId());
        }
        if (!ObjectUtils.isEmpty(query.getIdList())){
            wrapper.in("id",query.getId());
        }
        if (!ObjectUtils.isEmpty(query.getResourceName())){
            wrapper.like("resource_name",query.getResourceName());
        }
        if (!ObjectUtils.isEmpty(query.getMachineId())){
            wrapper.eq("machine_id",query.getMachineId());
        }
        if (!ObjectUtils.isEmpty(query.getK8sId())){
            wrapper.eq("k8s_id",query.getK8sId());
        }
        if (!ObjectUtils.isEmpty(query.getDockerId())){
            wrapper.eq("docker_id",query.getDockerId());
        }
        if (!ObjectUtils.isEmpty(query.getCloudId())){
            wrapper.eq("cloud_id",query.getCloudId());
        }
        if (!ObjectUtils.isEmpty(query.getCreator())){
            wrapper.eq("creator",query.getCreator());
        }
        Page<PipResourceManager> pipResourceTempPage = pipResourceManagerDao.selectPage(new Page<>(query.getPageNo(), query.getPageSize()), wrapper);

        if (ObjectUtils.isEmpty(pipResourceTempPage)){
            return new PageResult<>();
        }

        List<ResourceFindResp> respList = ResourceConverter.INSTANCE.toRespList(pipResourceTempPage.getRecords());

        //对资源进行赋值
        respList.forEach(this::setResource);
        respList.forEach(this::setUserName);

        PageResult<ResourceFindResp> pageResult = new PageResult<>(respList,pipResourceTempPage.getTotal(),pipResourceTempPage.getCurrent(),pipResourceTempPage.getSize());
        return pageResult;
    }

    @Override
    public TaskResourceFindResp findResourceListByType(ResourceQueryReq query) {
        TaskResourceFindResp taskResourceFindResp = new TaskResourceFindResp();

        if (StringUtils.isEmpty(query.getType())){
            throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(),"资源类型不可为空");
        }

        switch (query.getType()) {
            case "docker":
                QueryWrapper<DockerEndpointDo> dockerWrapper = new QueryWrapper<>();
                if (!StringUtils.isEmpty(query.getId())){
                    dockerWrapper.eq("id",query.getId());
                }
                List<DockerEndpointDo> resourceDockerEndpoints = dockerEndpointDao.selectList(dockerWrapper);
                if (!ObjectUtils.isEmpty(resourceDockerEndpoints)){
                    taskResourceFindResp.setDockerEndpointList(resourceDockerEndpoints);
                }
                return taskResourceFindResp;
            case "k8s":
                QueryWrapper<PipResourceK8S> k8sWrapper = new QueryWrapper<>();
                if (!StringUtils.isEmpty(query.getId())){
                    k8sWrapper.eq("id",query.getId());
                }
                List<PipResourceK8S> resourceK8S = k8SDao.selectList(k8sWrapper);
                if (!ObjectUtils.isEmpty(resourceK8S)){
                    taskResourceFindResp.setResourceK8SList(resourceK8S);
                }
                return taskResourceFindResp;
            case "machine":
                QueryWrapper<PipResourceMachine> machineWrapper = new QueryWrapper<>();
                if (!StringUtils.isEmpty(query.getId())){
                    machineWrapper.eq("id",query.getId());
                }
                List<PipResourceMachine> resourceMachines = machineDao.selectList(machineWrapper);
                if (!ObjectUtils.isEmpty(resourceMachines)){
                    taskResourceFindResp.setResourceMachineList(resourceMachines);
                }
                return taskResourceFindResp;
            case "cloud":
                QueryWrapper<PipResourceCloud> cloudWrapper = new QueryWrapper<>();
                if (!StringUtils.isEmpty(query.getId())){
                    cloudWrapper.eq("id",query.getId());
                }
                List<PipResourceCloud> resourceClouds = cloudDao.selectList(cloudWrapper);
                if (!ObjectUtils.isEmpty(resourceClouds)){
                    taskResourceFindResp.setResourceCloudList(resourceClouds);
                }
                return taskResourceFindResp;
            default:
                throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(),"资源类型错误");
        }
    }


    @Override
    public List findResourceListForObjectByType(ResourceQueryReq query) {
        if (StringUtils.isEmpty(query.getType())){
            throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(),"资源类型不可为空");
        }

        switch (query.getType()) {
            case "docker":
                QueryWrapper<DockerEndpointDo> dockerWrapper = new QueryWrapper<>();
                if (!StringUtils.isEmpty(query.getId())){
                    dockerWrapper.eq("id",query.getId());
                }
                return dockerEndpointDao.selectList(dockerWrapper);
            case "k8s":
                QueryWrapper<PipResourceK8S> k8sWrapper = new QueryWrapper<>();
                if (!StringUtils.isEmpty(query.getId())){
                    k8sWrapper.eq("id",query.getId());
                }
                return k8SDao.selectList(k8sWrapper);
            case "machine":
                QueryWrapper<PipResourceMachine> machineWrapper = new QueryWrapper<>();
                if (!StringUtils.isEmpty(query.getId())){
                    machineWrapper.eq("id",query.getId());
                }
                return machineDao.selectList(machineWrapper);
            case "cloud":
                QueryWrapper<PipResourceCloud> cloudWrapper = new QueryWrapper<>();
                if (!StringUtils.isEmpty(query.getId())){
                    cloudWrapper.eq("id",query.getId());
                }
                return cloudDao.selectList(cloudWrapper);
            default:
                throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(),"资源类型错误");
        }
    }

    private void setResource(ResourceFindResp resourceFindResp) {
        if (!StringUtils.isEmpty(resourceFindResp.getMachineId())){
            PipResourceMachine resourceMachine = machineDao.selectById(resourceFindResp.getMachineId());
            resourceFindResp.setResourceMachine(resourceMachine);
        }
        if (!StringUtils.isEmpty(resourceFindResp.getK8sId())) {
            PipResourceK8S pipResourceK8S = k8SDao.selectById(resourceFindResp.getK8sId());
            resourceFindResp.setPipResourceK8S(pipResourceK8S);
        }
        if (!StringUtils.isEmpty(resourceFindResp.getDockerId())) {
            DockerEndpointDo dockerEndpoint = dockerEndpointDao.selectById(resourceFindResp.getDockerId());
            resourceFindResp.setDockerEndpoint(dockerEndpoint);
        }
        if (!StringUtils.isEmpty(resourceFindResp.getCloudId())) {
            PipResourceCloud resourceCloud = cloudDao.selectById(resourceFindResp.getCloudId());
            resourceFindResp.setPipResourceCloud(resourceCloud);
        }
    }


    private void setUserName(ResourceFindResp resp) {
        if (!StringUtils.isEmpty(resp.getCreator())){
            AdminUserDO user = adminUserService.getUser(Long.valueOf(resp.getCreator()));
            if (!ObjectUtils.isEmpty(user)){
                resp.setCreatorName(user.getUsername());
            }
        }

        if (!StringUtils.isEmpty(resp.getUpdater())){
            AdminUserDO user = adminUserService.getUser(Long.valueOf(resp.getUpdater()));
            if (!ObjectUtils.isEmpty(user)){
                resp.setUpdaterName(user.getUsername());
            }
        }
    }
}
