package com.ebts.generator.controller;

import com.ebts.common.annotation.Log;
import com.ebts.common.core.controller.BaseController;
import com.ebts.common.core.entity.Result;
import com.ebts.common.core.page.TableDataInfo;
import com.ebts.common.core.text.Convert;
import com.ebts.common.enums.BusinessType;
import com.ebts.generator.entity.GenTable;
import com.ebts.generator.entity.GenTableColumn;
import com.ebts.generator.service.GenTableColumnService;
import com.ebts.generator.service.GenTableService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import java.util.Map;

/**
 * 代码生成 操作处理
 *
 * @author binlin
 */
@RestController
@RequestMapping("/tool/gen")
public class GenController extends BaseController {

    @Autowired
    private GenTableService genTableService;

    @Autowired
    private GenTableColumnService genTableColumnService;

    /**
     * 查询代码生成列表
     */
    @PreAuthorize("@ebts.hasPermi('tool:gen:list')")
    @GetMapping("/list")
    public Serializable genList(GenTable genTable) {
        startPage();
        List<GenTable> list = genTableService.selectGenTableList(genTable);
        return getDataTable(list);
    }

    /**
     * 修改代码生成业务
     */
    @PreAuthorize("@ebts.hasPermi('tool:gen:query')")
    @GetMapping(value = "/{tableId}")
    public Result<Map<String, Object>> getInfo(@PathVariable Long tableId) {
        return genTableService.getInfo(tableId);
    }

    /**
     * 查询数据库列表
     */
    @PreAuthorize("@ebts.hasPermi('tool:gen:list')")
    @GetMapping("/db/list")
    public Serializable dataList(GenTable genTable) {
        startPage();
        Result<List<GenTable>> result = genTableService.selectDbTableList(genTable);
        if (result.isSuccess()) {
            return getDataTable(result.getData());
        } else {
            return result;
        }
    }

    /**
     * 查询数据表字段列表
     */
    @PreAuthorize("@ebts.hasPermi('tool:gen:list')")
    @GetMapping(value = "/column/{talbleId}")
    public Serializable columnList(Long tableId) {
        Result<List<GenTableColumn>> result = genTableColumnService.selectGenTableColumnListByTableId(tableId);
        if (result.isSuccess()) {
            TableDataInfo dataInfo = new TableDataInfo();
            dataInfo.setRows(result.getData());
            dataInfo.setTotal(result.getData().size());
            return dataInfo;
        } else {
            return result;
        }
    }

    /**
     * 导入表结构（保存）
     */
    @PreAuthorize("@ebts.hasPermi('tool:gen:list')")
    @Log(title = "代码生成", businessType = BusinessType.IMPORT)
    @PostMapping("/importTable")
    public Result<Object> importTableSave(String tables) {
        String[] tableNames = Convert.toStrArray(tables);
        // 查询表信息
        List<GenTable> tableList = genTableService.selectDbTableListByNames(tableNames);
        genTableService.importGenTable(tableList);
        return Result.ok();
    }

    /**
     * todo
     * 修改保存代码生成业务
     */
    @PreAuthorize("@ebts.hasPermi('tool:gen:edit')")
    @Log(title = "代码生成", businessType = BusinessType.UPDATE)
    @PutMapping
    public Result<Object> editSave(@Validated @RequestBody GenTable genTable) {
        genTableService.validateEdit(genTable);
        genTableService.updateGenTable(genTable);
        return Result.ok();
    }

    /**
     * 删除代码生成
     */
    @PreAuthorize("@ebts.hasPermi('tool:gen:remove')")
    @Log(title = "代码生成", businessType = BusinessType.DELETE)
    @DeleteMapping("/{tableIds}")
    public Result<Integer> remove(@PathVariable Long[] tableIds) {
        return genTableService.deleteGenTableByIds(tableIds);
    }

    /**
     * 预览代码
     */
    @PreAuthorize("@ebts.hasPermi('tool:gen:preview')")
    @GetMapping("/preview/{tableId}")
    public Result<Map<String, String>> preview(@PathVariable("tableId") Long tableId) throws IOException {
        Map<String, String> dataMap = genTableService.previewCode(tableId);
        return Result.ok(dataMap);
    }

    /**
     * 生成代码（下载方式）
     */
    @PreAuthorize("@ebts.hasPermi('tool:gen:code')")
    @Log(title = "代码生成", businessType = BusinessType.GENCODE)
    @GetMapping("/download/{tableName}")
    public void download(HttpServletResponse response, @PathVariable("tableName") String tableName) throws IOException {
        byte[] data = genTableService.downloadCode(tableName);
        genCode(response, data);
    }

    /**
     * 生成代码（自定义路径）
     */
    @PreAuthorize("@ebts.hasPermi('tool:gen:code')")
    @Log(title = "代码生成", businessType = BusinessType.GENCODE)
    @GetMapping("/genCode/{tableName}")
    public Result genCode(@PathVariable("tableName") String tableName) {
        boolean start = genTableService.generatorCode(tableName);
        if (start) {
            return Result.ok();
        } else {
            return Result.error("渲染模板失败，表名：" + tableName);
        }
    }

    /**
     * 同步数据库
     */
    @PreAuthorize("@ebts.hasPermi('tool:gen:edit')")
    @Log(title = "代码生成", businessType = BusinessType.UPDATE)
    @GetMapping("/synchDb/{tableName}")
    public Result<String> synchDb(@PathVariable("tableName") String tableName) {
        genTableService.synchDb(tableName);
        return Result.ok();
    }

    /**
     * 批量生成代码
     */
    @PreAuthorize("@ebts.hasPermi('tool:gen:code')")
    @Log(title = "代码生成", businessType = BusinessType.GENCODE)
    @GetMapping("/batchGenCode")
    public void batchGenCode(HttpServletResponse response, String tables) throws IOException {
        String[] tableNames = Convert.toStrArray(tables);
        byte[] data = genTableService.downloadCode(tableNames);
        genCode(response, data);
    }

    /**
     * 生成zip文件
     */
    private void genCode(HttpServletResponse response, byte[] data) throws IOException {
        response.reset();
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition", "attachment; filename=\"ebts.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }
}