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

import cd.casic.ci.process.dto.resp.target.TargetVersionResp;
import cd.casic.ci.process.process.converter.TargetVersionConverter;
import cd.casic.ci.process.process.dao.pipeline.TargetVersionDao;
import cd.casic.ci.process.process.dataObject.target.TargetVersion;
import cd.casic.ci.process.process.service.target.TargetVersionService;
import cd.casic.framework.security.dal.user.AdminUserDO;
import cd.casic.framework.tenant.core.service.AdminUserServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

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

/**
 * @author HopeLi
 * @version v1.0
 * @ClassName TargetVersionServiceImpl
 * @Date: 2025/5/17 15:20
 * @Description:
 */
@Service
@Slf4j
public class TargetVersionServiceImpl extends ServiceImpl<TargetVersionDao, TargetVersion> implements TargetVersionService {
    @Resource
    private TargetVersionDao targetVersionDao;

    @Resource
    private AdminUserServiceImpl adminUserService;

    @Override
    public List<TargetVersionResp> selectListByManagerId(String targetId) {
        QueryWrapper<TargetVersion> wrapper = new QueryWrapper<>();
        wrapper.eq("target_id",targetId);
        List<TargetVersion> versionList = targetVersionDao.selectList(wrapper);
        if (CollectionUtils.isEmpty(versionList)){
            return new ArrayList<>(0);
        }
        List<TargetVersionResp> respList = TargetVersionConverter.INSTANCE.toRespList(versionList);
        respList.forEach(this::setUserName);
        return respList;
    }

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

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