package cn.fateverse.query.controller;

import cn.fateverse.common.excel.utils.ExcelUtil;
import cn.fateverse.query.enums.DynamicSourceEnum;
import cn.hutool.core.util.StrUtil;
import cn.fateverse.common.core.exception.CustomException;
import cn.fateverse.query.entity.dto.DataSourceManageDto;
import cn.fateverse.query.entity.query.DataSourceManageQuery;
import cn.fateverse.query.entity.vo.DataSourceManageVo;
import cn.fateverse.query.service.DataSourceManageService;
import cn.fateverse.common.core.result.Result;
import cn.fateverse.common.core.entity.Option;
import cn.fateverse.common.core.result.page.TableDataInfo;
import cn.fateverse.common.core.utils.ObjectUtils;
import cn.fateverse.common.log.annotation.Log;
import cn.fateverse.common.log.enums.BusinessType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 数据源管理 Controller
 *
 * @author clay
 * @date 2023-07-16
 */
@Api(value = "数据源管理管理",tags = "数据源管理管理")
@RestController
@RequestMapping("/datasource")
public class DataSourceManageController {

    private final DataSourceManageService dataSourceManageService;

    public DataSourceManageController(DataSourceManageService dataSourceManageService) {
        this.dataSourceManageService = dataSourceManageService;
    }

    @ApiOperation("获取数据源管理列表")
    @GetMapping
    @PreAuthorize("@ss.hasPermission('query:source:list')")
    public Result<TableDataInfo<DataSourceManageVo>> list(DataSourceManageQuery query) {
        TableDataInfo<DataSourceManageVo> dataInfo = dataSourceManageService.searchList(query);
        return Result.ok(dataInfo);
    }

    @ApiOperation("获取数据源option")
    @GetMapping("/option")
    public Result<List<Option>> option(){
        List<Option> options = dataSourceManageService.searchOptionList();
        return Result.ok(options);
    }

    @ApiOperation("获取数据源类型")
    @GetMapping("/option/type")
    public Result<List<Option>> datasourceType(){
        List<Option> optionList = Arrays.stream(DynamicSourceEnum.values()).map(dynamicSourceEnum -> Option.builder()
                .label(dynamicSourceEnum.getType())
                .value(dynamicSourceEnum)
                .build()).collect(Collectors.toList());
        return Result.ok(optionList);
    }

    @ApiOperation("导出excel数据")
    @GetMapping("/export")
    @PreAuthorize("@ss.hasPermission('query:source:export')")
    public void export(DataSourceManageQuery query){
        List<DataSourceManageVo> list = dataSourceManageService.exportList(query);
        ExcelUtil.exportExcel(list, DataSourceManageVo.class);
    }

    @ApiOperation("获取数据源管理详细信息")
    @GetMapping("/{id}")
    @PreAuthorize("@ss.hasPermission('query:source:info')")
    public Result<DataSourceManageVo> info(@PathVariable Long id) {
        ObjectUtils.checkPk(id);
        DataSourceManageVo dataSourceManageVo = dataSourceManageService.searchById(id);
        return Result.ok(dataSourceManageVo);
    }

    @ApiOperation("新增数据源管理")
    @PostMapping
    @Log(title = "新增数据源管理",businessType = BusinessType.INSERT)
    @PreAuthorize("@ss.hasPermission('query:source:add')")
    public Result<Void> add(@RequestBody @Validated DataSourceManageDto manageDto){
        checkDataSource(manageDto);
        if (StrUtil.isBlank(manageDto.getPassword())){
            return Result.error("数据源密码不能为空!");
        }
        dataSourceManageService.save(manageDto);
        return Result.ok();
    }

    @ApiOperation("修改数据源管理")
    @PutMapping
    @Log(title = "修改数据源管理",businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermission('query:source:edit')")
    public Result<Void> edit(@RequestBody @Validated DataSourceManageDto manageDto){
        ObjectUtils.checkPk(manageDto.getId());
        checkDataSource(manageDto);
        dataSourceManageService.edit(manageDto);
        return Result.ok();
    }

    @ApiOperation("删除数据源管理")
    @DeleteMapping("/{idList}")
    @Log(title = "删除数据源管理",businessType = BusinessType.DELETE)
    @PreAuthorize("@ss.hasPermission('query:source:del')")
    public Result<Void> batchDel(@PathVariable List<Long> idList){
        ObjectUtils.checkPkList(idList);
        dataSourceManageService.removeBatch(idList);
        return Result.ok();
    }

    /**
     * 检查数据源字段的合规性
     * @param dataSource 数据源
     */
    public void checkDataSource(DataSourceManageDto dataSource){
        if (1 == dataSource.getConfigType()){
            if (StrUtil.isEmpty(dataSource.getHost())) {
                throw new CustomException("主机地址不能为空!");
            }
            if (null == dataSource.getPort()) {
                throw new CustomException("主机端口不能为空!");
            }
            if (StrUtil.isEmpty(dataSource.getDbName())) {
                throw new CustomException("数据库名称不能为空!");
            }
        }else {
            if (StrUtil.isEmpty(dataSource.getUrl())) {
                throw new CustomException("数据源接地址不能为空!");
            }
        }
    }

}