package com.ruoyi.cms.controller.cms;

import com.ruoyi.cms.domain.SensitiveWordData;
import com.ruoyi.cms.service.SensitiveWordDataService;
import com.ruoyi.cms.util.EasyExcelUtils;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;


/**
 * 敏感词库
 *
 * @author 
 * @email 
 * @date 2025-10-10 10:42:16
 */
@RestController
@RequestMapping("/cms/sensitiveworddata")
@Api(tags = "后台：敏感词库")
@Anonymous
public class SensitiveWordDataController extends BaseController {
    @Autowired
    private SensitiveWordDataService sensitiveWordDataService;

    /**
     * 列表
     */
    @ApiOperation("敏感词库详细信息")
    @GetMapping("/list")
    public TableDataInfo list(SensitiveWordData sensitiveWordData){
        startPage();
        List<SensitiveWordData> list = sensitiveWordDataService.selectSensitiveworddataList(sensitiveWordData);
        return getDataTable(list);
    }

    /**
     * 获取详细信息
     */
    @ApiOperation("获取敏感词库详细信息")
    @GetMapping(value = "/{id}")
    public AjaxResult list(@PathVariable("id") Long id){
        return success(sensitiveWordDataService.selectById(id));
    }


    /**
     * 保存
     */
    @ApiOperation("新增敏感词")
    @Log(title = "敏感词", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult save(@RequestBody SensitiveWordData sensitiveWordData){

        return toAjax(sensitiveWordDataService.insertSensitiveworddata(sensitiveWordData));
    }

    /**
     * 修改
     */
    @ApiOperation("修改敏感词")
    @Log(title = "敏感词", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SensitiveWordData sensitiveWordData){
        return toAjax(sensitiveWordDataService.updateSensitiveworddata(sensitiveWordData));
    }

    /**
     * 删除敏感词
     */
    @ApiOperation("删除敏感词")
    @Log(title = "敏感词", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        if(ids.length==0){
            return AjaxResult.error("请传递参数!");
        }
        return toAjax(sensitiveWordDataService.deleteSensitiveworddataIds(ids));
    }

    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/exoprt")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file) throws Exception
    {
        // 参数校验
        if (file.isEmpty()) {
            return AjaxResult.error("上传文件不能为空");
        }
        String fileName = file.getOriginalFilename();
        //类型验证
        if (fileName == null || !fileName.endsWith(".xlsx") && !fileName.endsWith(".xls")) {
            return AjaxResult.error("请上传Excel格式的文件");
        }
        //名称验证
        if (fileName == null || !"mgc.xlsx".equals(fileName)) {
            return AjaxResult.error("请上传正确的模板文件：mgc.xlsx");
        }

        try
        {
            InputStream inputStream = file.getInputStream();
            EasyExcelUtils.readExcelByBatch(inputStream, SensitiveWordData.class, 100, list -> {
                // 处理逻辑：如批量保存到数据库
                sensitiveWordDataService.batchInsert(list);
            });
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success();
    }

    @PostMapping("/downloadModel")
    public void downloadModel(HttpServletRequest request, HttpServletResponse response)throws Exception{
        String name = "mgc.xlsx";
        String pathFile="/data/downloadmodel/"+name;
        File url = new File(pathFile);

        String resMsg = "";
        try {
            request.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        try {
            name = new String(name.getBytes("gb2312"), "ISO8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.reset();

        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename="+ name);
        response.setHeader("Pragma", "public");
        response.setHeader("Cache-Control", "max-age=0");
        InputStream in = null;
        try {
            in = new FileInputStream(url);
        } catch (FileNotFoundException e1) {
            resMsg = "文件未找到";
            e1.printStackTrace();
            response.getWriter().write(resMsg + ":" + name);
        }
        OutputStream ou = response.getOutputStream();
        byte[] buffer = new byte[1024];
        int i = -1;
        while ((i = in.read(buffer)) != -1) {
            ou.write(buffer, 0, i);
        }
        ou.flush();
        ou.close();
        in.close();
    }
}
