/**
 * 20241029 ©WANGKANG 1686617586@qq.com
 */

package com.taais.biz.controller;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import com.taais.biz.domain.bo.Video2imageBo;
import com.taais.biz.domain.vo.Video2imageVo;
import com.taais.biz.service.IVideo2imageService;
import com.taais.common.core.core.page.PageResult;
import com.taais.common.core.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.taais.common.core.core.domain.CommonResult;
import com.taais.common.excel.utils.ExcelUtil;
import com.taais.common.log.annotation.Log;
import com.taais.common.log.enums.BusinessType;
import com.taais.common.web.annotation.RepeatSubmit;
import com.taais.common.web.core.BaseController;
import jakarta.annotation.Resource;
import org.springframework.web.multipart.MultipartFile;


import static com.taais.biz.constant.BizConstant.UPLOAD_DIR;
import static com.taais.biz.constant.BizConstant.VideoStatus.NOT_START;

/**
 * 视频转图片Controller
 *
 * @author km
 * 2024-08-16
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/demo/video2image")
public class Video2imageController extends BaseController {

    @Resource
    private IVideo2imageService video2imageService;

    /**
     * 查询视频转图片列表
     */
    @SaCheckPermission("demo:video2image:list")
    @GetMapping("/list")
    public CommonResult<PageResult<Video2imageVo>> list(Video2imageBo video2imageBo) {
        return CommonResult.success(video2imageService.selectPage(video2imageBo));
    }

    /**
     * 导出视频转图片列表
     */
    @SaCheckPermission("demo:video2image:export")
    @Log(title = "视频转图片", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Video2imageBo video2imageBo) {
        List<Video2imageVo> list = video2imageService.selectList(video2imageBo);
        ExcelUtil.exportExcel(list, "视频转图片", Video2imageVo.class, response);
    }

    /**
     * 获取视频转图片详细信息
     */
    @SaCheckPermission("demo:video2image:query")
    @GetMapping(value = "/{id}")
    public CommonResult<Video2imageVo> getInfo(@PathVariable Long id) {
        return CommonResult.success(video2imageService.selectById(id));
    }

    /**
     * 新增视频转图片
     */
    @SaCheckPermission("demo:video2image:add")
    @Log(title = "视频转图片", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping
    public CommonResult add(@Validated @RequestBody Video2imageBo video2imageBo) {
        boolean inserted = video2imageService.insert(video2imageBo);
        if (!inserted) {
            return CommonResult.fail("新增视频转图片记录失败！");
        }
        return CommonResult.success();
    }

    /**
     * 修改视频转图片
     */
    @SaCheckPermission("demo:video2image:edit")
    @Log(title = "视频转图片", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping
    public CommonResult<Void> edit(@Validated @RequestBody Video2imageBo video2imageBo) {
        Boolean updated = video2imageService.update(video2imageBo);
        if (!updated) {
            return CommonResult.fail("修改视频转图片记录失败!");
        }
        return CommonResult.success();
    }

    /**
     * 删除视频转图片
     */
    @SaCheckPermission("demo:video2image:remove")
    @Log(title = "视频转图片", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public CommonResult<Void> remove(@PathVariable Long[] ids) {
        boolean deleted = video2imageService.deleteByIds(ids);
        if (!deleted) {
            return CommonResult.fail("删除视频转图片记录失败!");
        }
        return CommonResult.success();
    }


    /**
     * 此函数弃用，改用系统自带的上传系统
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public CommonResult uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return CommonResult.success("文件不能为空！");
        }

        try {
            // 创建上传目录（如果不存在）
            Path uploadPath = Paths.get(UPLOAD_DIR);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            UUID uuid = UUID.randomUUID();
            String uuidString = uuid.toString();

            // 获取文件名并构建目标路径
            String fileName = uuidString + "_" + file.getOriginalFilename();
            Path targetPath = uploadPath.resolve(fileName);

            // 保存文件到目标路径
            Files.copy(file.getInputStream(), targetPath);

            return CommonResult.success(fileName, "上传成功");
        } catch (IOException e) {
            e.printStackTrace();
            return CommonResult.success("上传失败");
        }
    }

    @GetMapping("/start/{id}")
    public CommonResult startToImage(@PathVariable("id") Long id) {
        /**
         * 传VideoImage的ID
         */
        boolean start = video2imageService.startToImage(id);
        if (start) {
            return CommonResult.success("操作成功！");
        } else {
            return CommonResult.fail("操作失败！");
        }
    }

    @GetMapping("/stop/{id}")
    public CommonResult stopToImage(@PathVariable("id") Long id) {
        /**
         * 传VideoImage的ID
         */
        boolean start = video2imageService.stopToImage(id);
        if (start) {
            return CommonResult.success("操作成功！");
        } else {
            return CommonResult.fail("操作失败！");
        }
    }


    @GetMapping("/zip/{id}")
    public ResponseEntity<org.springframework.core.io.Resource> zipFolder(@PathVariable("id") Long id) throws IOException {
        /**
         * 传VideoImage的ID
         */
        return video2imageService.zipImages(id);
    }
}
