package net.northking.cctp.platform.pub;

import com.hzbank.testteam.autotest.dependencies.baseDefineDependency.constants.BaseDefineDependencyConstants;
import com.hzbank.testteam.autotest.dependencies.baseDefineDependency.entity.Environment;
import com.hzbank.testteam.autotest.dependencies.baseDefineDependency.exception.InvalidException;
import com.hzbank.testteam.autotest.dependencies.baseDefineDependency.vo.ResponseVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.northking.cctp.common.feign.ApiAtsEnviromentFeign;
import net.northking.cctp.common.http.ResultWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Api(tags = "环境信息--外部查询")
@RequestMapping("/pub")
@RestController
@Slf4j
public class PubEnvCtrl {

    @Autowired
    private ApiAtsEnviromentFeign apiAtsEnviromentFeign;

    @ApiOperation(value = "根据id查询环境名称")
    @PostMapping(value = "/findEnvName",
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE,
            consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResultWrapper<Map<String, Environment>> findEnvName(@RequestBody List<String> ids) {
        ResultWrapper<Map<String, Environment>> wrapper = new ResultWrapper<>();
        List<Long> envIds = new ArrayList<>();
        for (String id : ids) {
            Long envId = null;
            try {
                envId = Long.valueOf(id);
            } catch (NumberFormatException e) {
                log.error("环境Id类型转化异常");
                throw new InvalidException("环境Id类型转化异常");
            }
            envIds.add(envId);
        }
        ResponseVO<List<Environment>> responseVo = apiAtsEnviromentFeign.getEnvInfoById(envIds);
        if (responseVo == null || !responseVo.getCode().equals(BaseDefineDependencyConstants.SYSTEM_RESPONSE_CODE_SUCCESS)) {
            throw new InvalidException("服务间调用获取环境信息失败");
        }
        Map<String, Environment> result = responseVo.getData().stream().collect(Collectors.toMap(e -> e.getId().toString(), e -> e, (e1, e2) -> e1));
        return wrapper.success(result);
    }
}
