package com.tofly.feesapi.common;

import com.tofly.feesapi.common.core.ResultRespone;
import com.tofly.feesapi.common.api.ISqlStatementService;
import com.tofly.feesapi.common.exception.FeesException;
import com.tofly.feesapi.common.model.PageLink;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import java.util.LinkedHashMap;

import static com.tofly.feesapi.common.ControllerConstants.*;

@RestController
@RequestMapping("/api/common/sqlStatement")
@Api(tags = "公共-通用SQL语句操作")
public class SqlStatementController extends BaseController {

    @Autowired
    private ISqlStatementService sqlStatementService;

    @PostMapping("/execute")
    @ApiOperation(value = "执行SQL语句")
    public ResultRespone execute(@ApiParam(value = SQL_FILE_DESCRIPTION, required = true)
                                 @RequestParam String sqlFile,
                                 @ApiParam(value = OPERATION_DESCRIPTION, required = true, allowableValues = OPERATION_PROPERTY_ALLOWABLE_VALUES)
                                 @RequestParam String operation,
                                 @ApiParam(value = PAGE_SIZE_DESCRIPTION)
                                 @RequestParam(required = false, value = PAGE_SIZE_PARA_NAME) Integer pageSize,
                                 @ApiParam(value = PAGE_NUMBER_DESCRIPTION)
                                 @RequestParam(required = false, value = PAGE_NUMBER_PARA_NAME) Integer page,
                                 @ApiIgnore @RequestParam LinkedHashMap<String, Object> executeParams) throws FeesException {
        executeParams.remove("sqlFile");
        executeParams.remove("operation");
        executeParams.remove(PAGE_SIZE_PARA_NAME);
        executeParams.remove(PAGE_NUMBER_PARA_NAME);
        PageLink pageLink = null;

        if ("queryPage".equals(operation)) {
            page = page == null ? 1 : page;
            pageSize = pageSize == null ? 10 : pageSize;
            pageLink = createPageLink(pageSize, page);
        }

        return ResultRespone.success(sqlStatementService.execute2(sqlFile, operation, executeParams, pageLink));
    }

}
