package com.cm.common.plugin.controller.apis.dynamic.config;

import com.cm.common.annotation.CheckRequestBodyAnnotation;
import com.cm.common.base.AbstractController;
import com.cm.common.constants.ISystemConstant;
import com.cm.common.exception.ParamsException;
import com.cm.common.exception.SearchException;
import com.cm.common.plugin.pojo.dtos.dynamic.config.DynamicConfigTableDTO;
import com.cm.common.plugin.pojo.vos.dynamic.config.DynamicConfigTableVO;
import com.cm.common.plugin.pojo.vos.dynamic.config.EmptyProjectVO;
import com.cm.common.plugin.service.dynamic.config.IDynamicConfigTableService;
import com.cm.common.pojo.ListPage;
import com.cm.common.result.ErrorResult;
import com.cm.common.result.SuccessResult;
import com.cm.common.result.SuccessResultList;
import com.cm.common.utils.RegexUtil;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * When you feel like quitting. Think about why you started
 * 当你想要放弃的时候，想想当初你为何开始
 *
 * @ClassName: DynamicConfigTableController
 * @Description: 动态配置-表
 * @Author: WangGeng
 * @Date: 2019/12/7 5:59 下午
 * @Version: 1.0
 **/
@RestController
@RequestMapping(ISystemConstant.API_PREFIX + "/dynamicconfigtable")
public class DynamicConfigTableController extends AbstractController {

    @Autowired
    private IDynamicConfigTableService dynamicConfigTableService;

    @ApiOperation(value = "表新增", notes = "表新增接口")
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @PostMapping("savetable")
    @CheckRequestBodyAnnotation
    public SuccessResult saveTable(@RequestBody DynamicConfigTableVO dynamicConfigTableVO) throws Exception {
        return dynamicConfigTableService.saveTable(dynamicConfigTableVO);
    }

    @ApiOperation(value = "建动态表", notes = "建动态表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", paramType = "path")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @PostMapping("savedynamictable/{id}")
    public SuccessResult saveDynamicTable(@PathVariable("id") String id) {
        return dynamicConfigTableService.saveDynamicTable(id);
    }

    @ApiOperation(value = "表删除", notes = "通过id列表批量删除表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "表ID列表，用下划线分隔", paramType = "path", example = "1_2_3")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @DeleteMapping("removetable/{ids}")
    public SuccessResult removeTable(@PathVariable("ids") String ids) {
        return dynamicConfigTableService.removeTable(ids);
    }

    @ApiOperation(value = "表修改", notes = "表修改接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dictionaryId", value = "表ID", paramType = "path")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @PutMapping("updatetable/{id}")
    @CheckRequestBodyAnnotation
    public SuccessResult updateTable(@PathVariable("id") String id, @RequestBody DynamicConfigTableVO dynamicConfigTableVO) throws Exception {
        return dynamicConfigTableService.updateTable(id, dynamicConfigTableVO);
    }

    @ApiOperation(value = "修改动态表", notes = "修改动态表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", paramType = "path")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @PutMapping("updatedynamictable/{id}")
    public SuccessResult updateDynamicTable(@PathVariable("id") String id) throws Exception {
        return dynamicConfigTableService.updateDynamicTable(id);
    }

    @ApiOperation(value = "表详情（ID查询）", notes = "表详情（ID查询）接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dictionaryId", value = "表ID", paramType = "path")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @GetMapping("gettablebyid/{id}")
    public DynamicConfigTableDTO getTableById(@PathVariable("id") String id) {
        return dynamicConfigTableService.getTableById(id);
    }

    @ApiOperation(value = "表全部列表", notes = "表全部列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dictionaryParentId", value = "表上级ID", paramType = "path")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @GetMapping("listtable")
    public List<DynamicConfigTableDTO> listTable() throws SearchException {
        Map<String, Object> params = requestParams();
        return dynamicConfigTableService.listTable(params);
    }

    @ApiOperation(value = "分页表列表", notes = "分页表列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码", paramType = "query", dataType = "int", defaultValue = "1"),
            @ApiImplicitParam(name = "rows", value = "显示数量", paramType = "query", dataType = "int", defaultValue = "20"),
            @ApiImplicitParam(name = "keywords", value = "关键字", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", paramType = "query", dataType = "String")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @GetMapping("listpagetable")
    public SuccessResultList<List<DynamicConfigTableDTO>> listPageTable(ListPage page) {
        Map<String, Object> params = requestParams();
        page.setParams(params);
        return dynamicConfigTableService.listPageTable(page);
    }

    @ApiOperation(value = "下载静态化代码", notes = "下载静态化代码接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", paramType = "path"),
            @ApiImplicitParam(name = "basePackage", value = "基础包", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "context", value = "访问路径", paramType = "query", dataType = "String")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @GetMapping("getgeneratorcode/{id}")
    public void getGeneratorCode(@PathVariable("id") String id,
                                 @RequestParam(name = "basePackage") String basePackage,
                                 @RequestParam(name = "context") String context,
                                 HttpServletResponse response) throws Exception {
        dynamicConfigTableService.getStaticCode(id, basePackage, context, response);
    }

    @ApiOperation(value = "下载空项目", notes = "下载空项目接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "systemUrl", value = "系统地址", paramType = "query"),
            @ApiImplicitParam(name = "systemPort", value = "系统端口", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "systemName", value = "系统名", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "systemSummary", value = "系统说明", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "oauthServerUrl", value = "认证地址", paramType = "query", dataType = "String")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @GetMapping("getemptyproject")
    public void saveEmptyProject(@RequestParam("systemUrl") String systemUrl,
                                 @RequestParam("systemPort") Integer systemPort,
                                 @RequestParam("systemName") String systemName,
                                 @RequestParam("systemSummary") String systemSummary,
                                 @RequestParam("oauthServerUrl") String oauthServerUrl,
                                 HttpServletResponse response) throws Exception {
        if (StringUtils.isBlank(systemUrl) || !RegexUtil.isUrl(systemUrl)) {
            throw new ParamsException("系统地址格式不正确");
        }
        if (systemPort == null || systemPort <= 0 || systemPort > 65535) {
            throw new ParamsException("系统端口不在范围");
        }
        if (StringUtils.isBlank(systemName) || !RegexUtil.isLetter(systemName)) {
            throw new ParamsException("系统名必须全部为字母");
        }
        if (StringUtils.isBlank(systemSummary)) {
            throw new ParamsException("系统说明必须全部为字母");
        }
        if (StringUtils.isBlank(oauthServerUrl) || !RegexUtil.isUrl(oauthServerUrl)) {
            throw new ParamsException("认证地址格式不正确");
        }
        EmptyProjectVO emptyProjectVO = new EmptyProjectVO();
        emptyProjectVO.setSystemUrl(systemUrl);
        emptyProjectVO.setSystemPort(systemPort.toString());
        emptyProjectVO.setSystemName(systemName);
        emptyProjectVO.setSystemSummary(systemSummary);
        emptyProjectVO.setOauthServerUrl(oauthServerUrl);
        dynamicConfigTableService.getEmptyProject(emptyProjectVO, response);
    }

    @ApiOperation(value = "下载空项目", notes = "下载空项目接口")
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @GetMapping("getassetszip")
    public void getAssetsZip(HttpServletResponse response) {
        dynamicConfigTableService.getAssetsZip(response);
    }

}
