/**
 *
 */
package org.springblade.etl.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.log.annotation.ApiLog;
import org.springblade.core.tool.api.R;
import org.springblade.etl.dto.SqlScriptBrowserReqDto;
import org.springblade.etl.dto.SqlScriptBrowserResultDto;
import org.springblade.etl.entity.SqlJobScript;
import org.springblade.etl.entity.bi.ReportDatasource;
import org.springblade.etl.enums.SqlScriptType;
import org.springblade.etl.service.QueryWrapperService;
import org.springblade.etl.service.SqlJobScriptService;
import org.springblade.etl.service.bi.ReportDatasourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * SQL任务脚本 操作处理
 *
 * @author aokunsang
 * @date 2023-12-03
 */
@Slf4j
@RestController
@RequestMapping("/sqljob-script")
@Api(value = "SQL任务脚本相关接口", tags = "SQL任务脚本接口")
public class SqlJobScriptController extends BladeController {

    @Autowired
    private SqlJobScriptService sqlJobScriptService;

    @Autowired
    private ReportDatasourceService reportDatasourceService;

    @Autowired
    private QueryWrapperService queryWrapperService;

    /**
     * 修改数据接口
     *
     * @param sqlJobScript
     * @return
     */
    @ApiLog("SQL任务脚本")
    @PostMapping("/run/{datasourceId}")
    @ApiOperation(value = "执行SQL脚本", httpMethod = "POST")
    public R<List<SqlScriptBrowserResultDto>> runScript(@Validated @RequestBody SqlJobScript sqlJobScript,
                                                        @PathVariable Integer datasourceId) {
        ReportDatasource reportDatasource = reportDatasourceService.getById(datasourceId);
        if (reportDatasource == null) {
            return R.fail("数据源不存在");
        }
        //判断sql是否有注入
        if (SqlScriptType.checkSqlInject(sqlJobScript.getSqlScript())) {
            return R.fail("该SQL脚本注入风险，请检查。");
        }
        String errMsg = null;
        List<SqlScriptBrowserResultDto> dataList = null;
        try {
            dataList = sqlJobScriptService.runScript(reportDatasource, sqlJobScript.getSqlScript(), false);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            errMsg = e.getMessage();
        }
        R<List<SqlScriptBrowserResultDto>> ret = R.success("执行成功");
        if (StrUtil.isNotBlank(errMsg)) {
            ret.setSuccess(false);
            ret.setMsg(errMsg);
        } else {
            ret.setSuccess(true);
        }
        ret.setData(dataList);
        return ret;
    }

    @PostMapping("/data-browser")
    @ApiOperation(value = "浏览数据", notes = "支持自定义分页")
    public R<IPage<Map<String, Object>>> dataBrowser(@RequestBody SqlScriptBrowserReqDto sqlScriptBrowserReq) {
        ReportDatasource reportDatasource = reportDatasourceService.getById(sqlScriptBrowserReq.getDatasourceId());
        if (reportDatasource == null) {
            return R.fail("数据源不存在");
        }
        return R.data(queryWrapperService.tempSelectPageList(new Page<>(sqlScriptBrowserReq.getPage(), sqlScriptBrowserReq.getSize()),
                reportDatasource, sqlScriptBrowserReq.getSelectSql()));
    }
}