package com.ruoyi.aicall.controller;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

import com.ruoyi.aicall.domain.CcLlmKbCat;
import com.ruoyi.aicall.service.ICcLlmKbCatService;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.aicall.domain.CcLlmKb;
import com.ruoyi.aicall.service.ICcLlmKbService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

/**
 * 知识库内容Controller
 * 
 * @author ruoyi
 * @date 2026-01-19
 */
@Controller
@RequestMapping("/aicall/kbcontent")
public class CcLlmKbController extends BaseController
{
    private String prefix = "aicall/kbcontent";

    @Autowired
    private ICcLlmKbService ccLlmKbService;
    @Autowired
    private ICcLlmKbCatService ccLlmKbCatService;

    @RequiresPermissions("aicall:kbcontent:view")
    @GetMapping("/kbcontent")
    public String kbcontent(@RequestParam(value = "id", required = false) Long catId,
                            ModelMap mmap) {
        mmap.put("catId", catId == null ? "" : catId);
        CcLlmKbCat ccLlmKbCat = ccLlmKbCatService.selectCcLlmKbCatById(catId);
        mmap.put("ccLlmKbCat", ccLlmKbCat);
        return prefix + "/kbcontent";
    }

    /**
     * 查询知识库内容列表
     */
    @RequiresPermissions("aicall:kbcontent:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(CcLlmKb ccLlmKb)
    {
        startPage();
        List<CcLlmKb> list = ccLlmKbService.selectCcLlmKbList(ccLlmKb);
        return getDataTable(list);
    }

    /**
     * 新增知识库内容
     */
    @GetMapping("/add")
    public String add(@RequestParam("catId") Long catId, ModelMap mmap)
    {
        CcLlmKb ccLlmKb = new CcLlmKb();
        ccLlmKb.setCatId(catId);
        mmap.put("ccLlmKb", ccLlmKb);
        return prefix + "/add";
    }

    /**
     * 新增保存知识库内容
     */
    @RequiresPermissions("aicall:kbcontent:add")
    @Log(title = "知识库内容", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(CcLlmKb ccLlmKb)
    {

        CcLlmKb checkCcLlmKb = ccLlmKbService.selectCcLlmKbContentByTitle(null, ccLlmKb.getTitle(), ccLlmKb.getCatId());
        if (null != checkCcLlmKb) {
            return AjaxResult.error("知识库内容不能重复，请修改");
        }
        return toAjax(ccLlmKbService.insertCcLlmKb(ccLlmKb));
    }

    /**
     * 修改知识库内容
     */
    @RequiresPermissions("aicall:kbcontent:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        CcLlmKb ccLlmKb = ccLlmKbService.selectCcLlmKbById(id);
        mmap.put("ccLlmKb", ccLlmKb);
        return prefix + "/edit";
    }

    /**
     * 修改保存知识库内容
     */
    @RequiresPermissions("aicall:kbcontent:edit")
    @Log(title = "知识库内容", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(CcLlmKb ccLlmKb)
    {

        CcLlmKb checkCcLlmKb = ccLlmKbService.selectCcLlmKbContentByTitle(ccLlmKb.getId(), ccLlmKb.getTitle(), ccLlmKb.getCatId());
        if (null != checkCcLlmKb ) {
            return AjaxResult.error("知识库内容不能重复，请修改");
        }
        return toAjax(ccLlmKbService.updateCcLlmKb(ccLlmKb));
    }

    /**
     * 删除知识库内容
     */
    @RequiresPermissions("aicall:kbcontent:remove")
    @Log(title = "知识库内容", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(ccLlmKbService.deleteCcLlmKbByIds(ids));
    }

    /* 导出 */
    @GetMapping("/export/{catId}")
    public void export(HttpServletResponse resp, @PathVariable Long catId) throws IOException {
        List<CcLlmKb> list = ccLlmKbService.selectCcLlmKbList(new CcLlmKb().setCatId(catId));
        CcLlmKbCat ccLlmKbCat = ccLlmKbCatService.selectCcLlmKbCatById(catId);
        String filename = "知识库-" + ccLlmKbCat.getCat();
        resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8") + ".xlsx");
        try (SXSSFWorkbook wb = new SXSSFWorkbook(100)) {
            Sheet sheet = wb.createSheet(filename);
            Row head = sheet.createRow(0);
            head.createCell(0).setCellValue("标题");
            head.createCell(1).setCellValue("内容");
            int r = 1;
            for (CcLlmKb e : list) {
                Row row = sheet.createRow(r++);
                row.createCell(0).setCellValue(e.getTitle());
                row.createCell(1).setCellValue(e.getContent());
            }
            wb.write(resp.getOutputStream());
        }
    }

    /* 导入 */
    @PostMapping("/importData/{catId}")
    @ResponseBody
    public AjaxResult importData(MultipartFile file,
                                 @PathVariable Long catId) throws Exception {
        String msg = ccLlmKbService.importData(file, catId);
        return success(msg);
    }

    /* 下载模板（仅两列） */
    @GetMapping("/importTemplate")
    public void importTemplate(HttpServletResponse resp) throws IOException {
        resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("知识库导入模板", "UTF-8") + ".xlsx");
        try (SXSSFWorkbook wb = new SXSSFWorkbook()) {
            Sheet sheet = wb.createSheet("模板");
            Row head = sheet.createRow(0);
            head.createCell(0).setCellValue("标题");
            head.createCell(1).setCellValue("内容");
            wb.write(resp.getOutputStream());
        }
    }

}
