package cn.gov.customs.wxjy.generator.controller;

import cn.gov.customs.cacp.sdks.core.result.CacpResultCodeMessage;
import cn.gov.customs.cacp.sdks.core.result.Result;
import cn.gov.customs.cacp.sdks.core.user.annotation.LogonUser;
import cn.gov.customs.cacp.sdks.core.user.pojo.CacpLogonUser;
import cn.gov.customs.wxjy.common.core.controller.BaseController;
import cn.gov.customs.wxjy.common.core.text.Convert;
import cn.gov.customs.wxjy.common.utils.StringUtils;
import cn.gov.customs.wxjy.generator.pojo.GenTable;
import cn.gov.customs.wxjy.generator.pojo.GenTableColumn;
import cn.gov.customs.wxjy.generator.pojo.GenTableQuery;
import cn.gov.customs.wxjy.generator.service.IGenTableColumnService;
import cn.gov.customs.wxjy.generator.service.IGenTableService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.*;

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

/**
 * 代码生成业务Controller
 *
 * @author xiong
 * @date 2025-12-25
 */
@RestController
@RequestMapping("/gen/GenTable")
@RequiredArgsConstructor
public class GenTableController extends BaseController {

    private final IGenTableService genTableService;

    private final IGenTableColumnService genTableColumnService;

    /**
     * 查询代码生成业务列表
     */
    @PostMapping("/get-list")
    public Result<PageInfo<GenTable>> list(@LogonUser CacpLogonUser user,@RequestBody GenTableQuery query) {
        PageHelper.startPage(query.getPageIndex(), query.getPageSize());
        PageInfo<GenTable> list = genTableService.selectPageList(query);
        return Result.success(list);
    }

    /**
     * 获取代码生成业务详细信息
     */
    @GetMapping(value = "/get-detail")
    public Result<Map<String, Object>> getInfo(@RequestParam String tableId) {
        GenTable table = genTableService.selectByTableId(tableId);
        List<GenTable> tables = genTableService.selectGenTableAll();
        List<GenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(tableId);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("info", table);
        map.put("rows", list);
        map.put("tables", tables);
        return Result.success(map);
    }

    /**
     * 查询数据库列表
     */
    @PostMapping("/db-list")
    public Result<PageInfo<GenTable>> dataList(@RequestBody GenTableQuery query) {
        PageHelper.startPage(query.getPageIndex(), query.getPageSize());
        PageInfo<GenTable> list = genTableService.selectDbTableList(query);
        return Result.success(list);
    }

    /**
     * 查询数据表字段列表
     */
    @PostMapping("/column-list")
    public Result<List<GenTableColumn>> columnList(@RequestBody String tableId) {
        List<GenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(tableId);
        return Result.success(list);
    }

    /**
     * 导入表结构（保存）
     */
    @GetMapping("/importTable")
    public Result<Boolean> importTableSave(@RequestParam String tables)
    {
        if (StringUtils.isEmpty(tables)){
            return Result.fail(CacpResultCodeMessage.WARNING,"获取表名称失败");
        }
        String[] tableNames = tables.split(",");
        // 查询表信息
        List<GenTable> tableList = genTableService.selectDbTableListByNames(tableNames);
        genTableService.importGenTable(tableList, getUsername());
        return Result.success(true);
    }



    /**
     * 新增代码生成业务
     */
    @PostMapping("/insert-genTable")
    public Result<Integer> add(@RequestBody GenTable genTable) {
        return Result.success(genTableService.insert(genTable));
    }

    /**
     * 修改代码生成业务
     */
    @PostMapping("/update-genTable")
    public Result<Integer> edit(@RequestBody GenTable genTable) {
        genTableService.validateEdit(genTable);
        return Result.success(genTableService.update(genTable));
    }

    /**
     * 删除代码生成业务
     */
    @PostMapping("/delete-genTable")
    public Result<Integer> remove(@RequestBody String[] ids) {
        return Result.success(genTableService.deleteByTableIds(ids));
    }

    /**
     * 预览代码
     */
    @GetMapping("/preview-code")
    public Result<Map<String,String>> preview(@RequestParam String tableId) throws IOException
    {
        Map<String, String> dataMap = genTableService.previewCode(tableId);
        return Result.success(dataMap);
    }

    /**
     * 生成代码（下载方式）
     */
    @GetMapping("/download")
    public void download(HttpServletResponse response, @RequestParam String tableName) throws IOException
    {
        byte[] data = genTableService.downloadCode(tableName);
        genCode(response, data);
    }

    /**
     * 生成代码（自定义路径）
     */
    @GetMapping("/genCode-tableName")
    public Result<Boolean> genCode(@RequestParam String tableName)
    {
        genTableService.generatorCode(tableName);
        return Result.success(true);
    }

    /**
     * 同步数据库
     */
    @GetMapping("/synchDb-tableName")
    public Result<Boolean> synchDb(@RequestParam String tableName)
    {
        genTableService.synchDb(tableName);
        return Result.success(true);
    }

    /**
     * 批量生成代码
     */
    @GetMapping("/batchGenCode")
    public void batchGenCode(HttpServletResponse response,@RequestParam String tables) throws IOException
    {
        String[] tableNames = Convert.toStrArray(tables);
        byte[] data = genTableService.downloadCode(tableNames);
        genCode(response, data);
    }

    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=\"rongji.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }
}
