package cn.fateverse.query.controller;

import cn.fateverse.common.core.result.Result;
import cn.fateverse.common.core.result.page.TableDataInfo;
import cn.fateverse.common.core.utils.ObjectUtils;
import cn.fateverse.common.decrypt.annotation.Encrypt;
import cn.fateverse.common.decrypt.annotation.EncryptField;
import cn.fateverse.query.entity.vo.CustomQueryResult;
import cn.fateverse.query.entity.dto.SearchInfo;
import cn.fateverse.query.entity.dto.SqlDto;
import cn.fateverse.query.entity.vo.SqlInfoVo;
import cn.fateverse.query.service.SqlSearchService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;


/**
 * @author Clay
 * @date 2023-08-09
 */
@Api(value = "sql万能查询", tags = "sql万能查询")
@RestController
@RequestMapping("/sql/search")
public class SqlSearchController {

    private final SqlSearchService sqlSearchService;


    public SqlSearchController(SqlSearchService sqlSearchService) {
        this.sqlSearchService = sqlSearchService;
    }


    @ApiOperation("获取到sql自定义查询的基础信息")
    @GetMapping("/{queryId}")
    @Encrypt
    public Result<SqlInfoVo> topology(@PathVariable @EncryptField String queryId) {
        SqlInfoVo sqlInfoVo = sqlSearchService.search(Long.parseLong(queryId));
        return Result.ok(sqlInfoVo);
    }


    @ApiOperation("保存sql自定义查询参数")
    @PostMapping
    @Encrypt
    public Result<Void> save(@RequestBody @Validated SqlDto sqlDto) {
        sqlSearchService.saveData(sqlDto);
        return Result.ok();
    }

    @ApiOperation("预览")
    @Encrypt
    @PutMapping("/preview")
    public Result<CustomQueryResult> preview(@RequestBody @Validated SqlDto sqlDto) {
        return sqlSearchService.preview(sqlDto);
    }


    @ApiOperation("发布")
    @Encrypt
    @PostMapping("/publish")
    public Result<Void> publish(@RequestBody @Validated SqlDto sqlDto) {
        if (ObjectUtils.isEmpty(sqlDto.getMenuId())) {
            return Result.error("上级菜单不能为空!");
        }
        sqlSearchService.publish(sqlDto);
        return Result.ok();
    }


    @ApiOperation("撤销")
    @Encrypt
    @PutMapping("/cancel/{queryId}")
    public Result<Void> cancel(@PathVariable @EncryptField String queryId){
        sqlSearchService.cancel(Long.valueOf(queryId));
        return Result.ok();
    }


    @ApiOperation("预览弹窗数据获取")
    @Encrypt
    @PostMapping("/preview/data")
    public Result<TableDataInfo<Map<String, Object>>> previewData(@RequestBody @Validated SearchInfo searchInfo) {
        TableDataInfo<Map<String, Object>> tableDataInfo = sqlSearchService.previewData(searchInfo.getList(), searchInfo.getLongQueryId());
        return Result.ok(tableDataInfo);
    }

}
