package net.northking.cctp.scriptcase.pub.variable;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.northking.cctp.common.http.ResultWrapper;
import net.northking.cctp.scriptcase.api.atuscriptrecord.service.AtuGlobalVariableApiService;
import net.northking.cctp.scriptcase.db.entity.AtuGlobalVariable;
import net.northking.cctp.scriptcase.pub.variable.dto.VariableDto;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
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;

@Api(tags = "变量查询-公共（pub）")
@RequestMapping("/pub/variable")
@RestController
public class VariablePubCtrl {

    /**
     * 日志
     */
    private final static Logger logger = LoggerFactory.getLogger(VariablePubCtrl.class);

    @Autowired
    private AtuGlobalVariableApiService variableApiService;


    @ApiOperation(value = "变量查询")
    @PostMapping(value = "/query",
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE,
            consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public VariableDto globalVariable(@RequestBody VariableDto query) {
        AtuGlobalVariable queryVar = new AtuGlobalVariable();
        BeanUtils.copyProperties(query, queryVar);
        AtuGlobalVariable variable = variableApiService.queryVariable(queryVar);
        if (null == variable) {
            query.setExist(false);
        } else {
            query.setValue(variable.getDefaultValue());
            query.setDataType(variable.getDataType());
        }
        return query;
    }

    @ApiOperation(value = "全局参数更新")
    @PostMapping(value = "/update",
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE,
            consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResultWrapper<Integer> updateGlobal(@RequestBody VariableDto update) {
        ResultWrapper<Integer> wrapper = new ResultWrapper<>();
        int result = 0;
        if (StringUtils.isNotBlank(update.getProjectId()) && StringUtils.isNotBlank(update.getName())) {
            result = variableApiService.updateGlobal(update);
        }
        if (result > 0) {
            wrapper.setSuccess(true);
        }
        wrapper.setData(result);
        return wrapper;
    }

}
