package cn.ibizlab.api.rest.extensions;

import cn.ibizlab.api.dto.DstAPIDTO;
import cn.ibizlab.core.lite.domain.DstAPI;
import cn.ibizlab.core.lite.domain.DstComponent;
import cn.ibizlab.core.lite.domain.MetaEntity;
import cn.ibizlab.core.lite.extensions.domain.EntityModel;
import cn.ibizlab.core.lite.extensions.service.LiteModelService;
import cn.ibizlab.core.lite.service.IDstComponentService;
import cn.ibizlab.util.errors.BadRequestAlertException;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@Api(tags = {"接口" })
@RestController("api-litecore")
@RequestMapping("")
public class LiteCoreResource {

    @Autowired
    private LiteModelService liteModelService;

    @Autowired
    private IDstComponentService dstComponentService;

    @RequestMapping(method = RequestMethod.GET, value = "/lite/{system}/entitys/{entity}")
    public ResponseEntity<EntityModel> getEntityModel(@PathVariable("system") String system,@PathVariable("entity") String entity) {
        return ResponseEntity.status(HttpStatus.OK).body(liteModelService.getEntityModel(system,entity));
    }

    @RequestMapping(method = RequestMethod.GET, value = "/lite/{app}/components/{component}")
    public ResponseEntity<JSON> getComponent(@PathVariable("app") String app, @PathVariable("component") String component) {

        DstComponent dstComponent = dstComponentService.getOne(Wrappers.<DstComponent>lambdaQuery().eq(DstComponent::getAppId,app).and(
                wrapper ->
                        wrapper.eq(DstComponent::getCodeName,component).or().eq(DstComponent::getName,component)),
                true);

        if(StringUtils.isEmpty(dstComponent.getConfig()))
            throw new BadRequestAlertException("未找到配置","DstComponent",component);

        return ResponseEntity.status(HttpStatus.OK).body(JSON.parseObject(dstComponent.getConfig()));
    }

}
