package org.matrix.autotest.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.matrix.database.entity.DynamicVariable;
import org.matrix.database.entity.Environment;
import org.matrix.database.service.IDynamicVariableService;
import org.matrix.database.service.IEnvironmentService;
import org.matrix.database.vo.CommonResult;
import org.matrix.database.vo.CommonResultObj;
import org.matrix.exception.GlobalException;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author mry
 */
@RestController
@RequestMapping("/hints")
@CrossOrigin
@Api(tags = "提示信息")
public class MarkedController {

    private final IEnvironmentService environmentService;

    private final IDynamicVariableService dynamicVariableService;

    public MarkedController(IEnvironmentService environmentService, IDynamicVariableService dynamicVariableService) {
        this.environmentService = environmentService;
        this.dynamicVariableService = dynamicVariableService;
    }

    @ApiOperation(value = "按照主键id查询variable值")
    @GetMapping("/variable/{id}")
    public ResponseEntity<CommonResultObj<Map<String, String>>> findByProjectIdEnvironmentVariable(@PathVariable Integer id) {
        Environment environment = Optional.ofNullable(environmentService.getById(id))
                .orElseThrow(() -> new GlobalException(String.format("没有查到指定的行为,你提供的行为id是%d", id)));
        Map<String, String> variable = environment.getVariable();
        if (environment != null) {
            return CommonResult.success(variable);
        } else {
            return CommonResult.failed("查询失败或无数据");
        }
    }

    /**
     * 根据ProjectId查询,返回值是动态变量名称
     */
    @ApiOperation(value = "根据项目id查询,动态参数名称")
    @GetMapping("/dynamicVariableName/{projectId}")
    public ResponseEntity<CommonResultObj<List<String>>> findByProjectIdDynamicVariableName(@PathVariable Long projectId) {
        List<DynamicVariable> results = Optional.ofNullable(dynamicVariableService.list(Wrappers.lambdaQuery(DynamicVariable.class)
                        .eq(DynamicVariable::getProjectId, projectId)))
                .orElseThrow(() -> new GlobalException(String.format("没有查到指定的行为,你提供的行为id是%d", projectId)));
        List<String> list = new ArrayList<>();
        for (DynamicVariable result : results) {
            list.add(result.getName());
        }
        if (results != null && results.size() != 0) {
            return CommonResult.success(list, "查询成功");
        } else {
            return CommonResult.failed("查询失败或无数据");
        }
    }
}
