package com.ylx.web.controller.common;

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

import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSON;
import com.ylx.massage.domain.TbFile;
import com.ylx.massage.service.impl.VideoThumbnailService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.ylx.common.config.RuoYiConfig;
import com.ylx.common.constant.Constants;
import com.ylx.common.core.domain.AjaxResult;
import com.ylx.common.utils.StringUtils;
import com.ylx.common.utils.file.FileUploadUtils;
import com.ylx.common.utils.file.FileUtils;
import com.ylx.framework.config.ServerConfig;
import com.ylx.massage.service.TbFileService;
import com.ylx.massage.service.SensitiveWordService;

/**
 * 通用请求处理
 *
 * @author ylx
 */
@RestController
@RequestMapping("/common")
@Api(tags = {"通用接口"})
public class CommonController {
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private TbFileService fileService;

    @Autowired
    private SensitiveWordService sensitiveWordService;


    @Autowired
    private VideoThumbnailService videoThumbnailService;

    private static final String FILE_DELIMETER = ",";

    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete   是否删除
     */
    @GetMapping("/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
        try {
            if (!FileUtils.checkAllowDownload(fileName)) {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = RuoYiConfig.getDownloadPath() + fileName;
            log.info("下载文件路径：{}", filePath);

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete) {
                FileUtils.deleteFile(filePath);
            }
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }


    /**
     * 通用上传请求（单个）
     *
     * @param file 上传的文件
     * @return AjaxResult 结果
     */
    @ApiOperation("通用上传请求（单个）")
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception {
        try {
            return fileService.uploadFile(file);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 通用上传视频请求（单个）
     *
     * @param file 上传的视频文件
     * @return AjaxResult
     */
    @ApiOperation("通用上传视频请求（单个）")
    @PostMapping("/uploadVi")
    public AjaxResult uploadFileVi(MultipartFile file) throws Exception {
        try {
            return fileService.uploadVideoFile(file);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }


    /**
     * 上传视频并生成封面
     *
     * @param file 视频文件
     * @return 响应结果，包含封面图片路径
     */
    @PostMapping("/uploadVideo")
    public AjaxResult uploadVideo(@RequestParam("file") MultipartFile file) {
        Map<String, Object> response = new HashMap<>();
        try {
            log.info("开始处理视频上传，文件名: {}, 大小: {} bytes", file.getOriginalFilename(), file.getSize());
            // 截取视频封面
            String thumbnailPath = videoThumbnailService.extractThumbnail(file);
            // 返回成功响应
            response.put("success", true);
            response.put("message", "视频上传成功");
            response.put("thumbnailPath", thumbnailPath);
            response.put("originalFilename", file.getOriginalFilename());
            return AjaxResult.success(response);
        } catch (VideoThumbnailService.VideoProcessException e) {
            log.error("视频处理失败", e);
            response.put("success", false);
            response.put("message", e.getMessage());
            return AjaxResult.error(response.toString());
        } catch (Exception e) {
            log.error("系统错误", e);
            response.put("success", false);
            response.put("message", "系统错误，请稍后重试");
            return AjaxResult.error(response.toString());
        }
    }

    /**
     * 通用上传请求（多个）
     *
     * @param files 上传的文件列表
     * @return AjaxResult
     */
    @ApiOperation("通用上传请求（多个）")
    @PostMapping("/uploads")
    public AjaxResult uploadFiles(List<MultipartFile> file) throws Exception {
        try {
            log.info("上传文件数量：{}", file.size());
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            log.info("上传文件路径：{}", filePath);

            List<String> urls = new ArrayList<String>();
            List<String> fileNames = new ArrayList<String>();
            List<String> newFileNames = new ArrayList<String>();
            List<String> originalFilenames = new ArrayList<String>();
            for (MultipartFile fileItem : file) {
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, fileItem);
                //String url = serverConfig.getUrl() + fileName;
                urls.add(fileName);
                fileNames.add(fileName);
                newFileNames.add(FileUtils.getName(fileName));
                originalFilenames.add(fileItem.getOriginalFilename());
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", StringUtils.join(urls, FILE_DELIMETER));
            ajax.put("fileName", StringUtils.join(fileNames, FILE_DELIMETER));
            ajax.put("newFileName", StringUtils.join(newFileNames, FILE_DELIMETER));
            ajax.put("originalFilename", StringUtils.join(originalFilenames, FILE_DELIMETER));
            return ajax;
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 本地资源通用下载
     */
    @GetMapping("/download/resource")
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        try {
            if (!FileUtils.checkAllowDownload(resource)) {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = RuoYiConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 上传Excel文件并导入敏感词数据到数据库
     * <p>
     * 上传Excel文件并导入敏感词数据到数据库。
     * 支持的文件格式：.xls, .xlsx
     * Excel文件格式要求：
     * - 第一行：表头（敏感词、分类、等级、状态、备注）
     * - 第二行起：数据行
     * </p>
     *
     * @param file Excel文件
     * @return AjaxResult 导入结果，包含导入统计信息
     */
    @ApiOperation("上传Excel文件并导入敏感词数据到数据库")
    @PostMapping("/importSensitiveWords")
    public AjaxResult importSensitiveWords(MultipartFile file) {
        try {
            // 上传文件
            AjaxResult ajaxResult = fileService.uploadFile(file);
            log.info("上传文件结果：{}", JSON.toJSONString(ajaxResult));
            int code = (int) ajaxResult.get("code");
            // 检查上传是否成功
            if (code != 200) {
                return ajaxResult;
            }

            log.info("开始导入敏感词Excel文件，文件名：{}", file.getOriginalFilename());

            // 调用服务层导入数据
            String result = sensitiveWordService.importFromExcel(file);
            log.info("敏感词Excel文件导入完成：{}", result);
            return AjaxResult.success(result);
        } catch (Exception e) {
            log.error("导入敏感词Excel文件失败", e);
            return AjaxResult.error("导入失败：" + e.getMessage());
        }
    }

    /**
     * 导出敏感词数据到Excel文件
     * <p>
     * 从数据库查询所有敏感词数据，生成Excel文件并下载。
     * 文件格式：.xls
     * 文件命名：全量敏感词库_当前日期时间.xls（如：全量敏感词库_20240106153045.xls）
     * </p>
     *
     * @param response HTTP响应对象
     */
    @ApiOperation("导出敏感词数据到Excel文件")
    @GetMapping("/exportSensitiveWords")
    public void exportSensitiveWords(HttpServletResponse response) {
        try {
            log.info("开始导出敏感词Excel文件");

            // 调用服务层导出数据
            sensitiveWordService.exportToExcel(response);

            log.info("敏感词Excel文件导出成功");
        } catch (Exception e) {
            log.error("导出敏感词Excel文件失败", e);
            // 设置错误响应
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            try {
                response.getWriter().write("{\"code\":500,\"msg\":\"导出失败：" + e.getMessage() + "\"}");
            } catch (IOException ex) {
                log.error("写入错误响应失败", ex);
            }
        }
    }


    /**
     * 删除文件
     *
     * @param fileName 文件名称
     * @param delete   是否删除
     */
    @GetMapping("/delete")
    public void filedelete(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
        try {
            if (!FileUtils.checkAllowDownload(fileName)) {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            // 本地资源路径
            String localPath = RuoYiConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(fileName, Constants.RESOURCE_PREFIX);
            if (delete) {
                FileUtils.deleteFile(downloadPath);
            }
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }
}
