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

import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import com.yhy.module.core.controller.admin.resource.vo.CatalogCreateReqVO;
import com.yhy.module.core.controller.admin.resource.vo.CatalogListReqVO;
import com.yhy.module.core.dal.dataobject.resource.ResourceCatalogDO;
import com.yhy.module.core.dal.mysql.resource.ResourceCatalogMapper;
import com.yhy.module.core.service.resource.ResourceCatalogService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception0;
import static cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants.BAD_REQUEST;

@Service
public class ResourceCatalogServiceImpl implements ResourceCatalogService {

    @Resource
    private ResourceCatalogMapper catalogMapper;

    @Override
    public Long createCatalog(CatalogCreateReqVO reqVO) {
        Long tenantId = TenantContextHolder.getTenantId();
        ResourceCatalogDO exists = catalogMapper.selectOne(new LambdaQueryWrapper<ResourceCatalogDO>()
                .eq(ResourceCatalogDO::getTenantId, tenantId)
                .eq(ResourceCatalogDO::getType, reqVO.getType())
                .eq(ResourceCatalogDO::getVersionNo, reqVO.getVersionNo()));
        if (exists != null) {
            throw exception0(BAD_REQUEST.getCode(), "同租户/类型下版本号已存在");
        }
        ResourceCatalogDO catalog = BeanUtils.toBean(reqVO, ResourceCatalogDO.class);
        catalog.setTenantId(tenantId);
        catalogMapper.insert(catalog);
        return catalog.getId();
    }

    @Override
    public List<ResourceCatalogDO> list(CatalogListReqVO reqVO) {
        LambdaQueryWrapper<ResourceCatalogDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ResourceCatalogDO::getTenantId, TenantContextHolder.getTenantId());
        if (StringUtils.hasText(reqVO.getType())) {
            wrapper.eq(ResourceCatalogDO::getType, reqVO.getType());
        }
        if (StringUtils.hasText(reqVO.getVersionNo())) {
            wrapper.eq(ResourceCatalogDO::getVersionNo, reqVO.getVersionNo());
        }
        wrapper.orderByDesc(ResourceCatalogDO::getCreateTime);
        return catalogMapper.selectList(wrapper);
    }
}
