package com.cool.bang.modules.generate.controller;

import com.cool.bang.common.base.BaseController;
import com.cool.bang.common.constant.ControllerConstant;
import com.cool.bang.common.tools.string.Convert;
import com.cool.bang.common.web.request.PageDomain;
import com.cool.bang.common.web.response.Result;
import com.cool.bang.common.web.response.module.ResultTable;
import com.cool.bang.modules.generate.domain.po.TableInfo;
import com.cool.bang.modules.generate.service.ITableInfoService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * code generate controller
 *
 * @author PeiZhi Guo
 * @version 1.0.0
 * 2021-3-26 11:27
 */
@RestController
@RequestMapping(ControllerConstant.GENERATOR + "v1/")
public class GenerateController extends BaseController {

    private final ITableInfoService generateService;

    @Autowired
    public GenerateController (ITableInfoService generateService) {
        this.generateService = generateService;
    }

    /**
     * 查询数据库表
     */
    @GetMapping("database")
    //  @PreAuthorize("hasPermission('','sys:gen:main')")
    public ResultTable database(PageDomain pageDomain, TableInfo generate) {
        PageInfo<TableInfo> genPageInfo = generateService.dataBaseTablePage(pageDomain, generate);
        return ResultTable.pageTable(genPageInfo.getTotal(), genPageInfo.getList());
    }

    @GetMapping
    //@PreAuthorize("hasPermission('','sys:gen:main')")
    public ResultTable main(PageDomain pageDomain, TableInfo generate) {
        PageInfo<TableInfo> genPageInfo = generateService.page(pageDomain, generate);
        return ResultTable.pageTable(genPageInfo.getTotal(), genPageInfo.getList());
    }

    @GetMapping("{id}")
    //@PreAuthorize("hasPermission('','sys:gen:main')")
    public Result get(@PathVariable Long id) {
        TableInfo table = generateService.queryTableById(id);
        return success(table);
    }

    @PostMapping
    //@PreAuthorize("hasPermission('','sys:gen:add')")
    public Result add(String params) {
        String[] names = Convert.toStrArray(params);
        List<TableInfo> list = generateService.queryByNames(names);
        generateService.importTableStructure(list);
        return success("导入成功");
    }

    @PostMapping("edit")
    //@PreAuthorize("hasPermission('','sys:gen:edit')")
    public Result edit(TableInfo param) {
        return decide(generateService.update(param));
    }

    @PostMapping("generate")
    public Result generate(Long tableId) {
        if (null == tableId) {
            return failure("id is not null");
        }
        StringBuilder str = generateService.generateCode(tableId);
        return success(str);
    }
}
