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

package com.taais.biz.controller;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.taais.biz.domain.VideoStable;
import com.taais.biz.domain.bo.VideoStableStartResultBo;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import cn.dev33.satoken.annotation.SaCheckPermission;
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 com.taais.biz.domain.vo.VideoStableVo;
import com.taais.biz.domain.bo.VideoStableBo;
import com.taais.biz.service.IVideoStableService;

import com.taais.common.core.core.page.PageResult;

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

/**
 * 视频去抖动Controller
 *
 * @author 0
 * 2024-08-30
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/demo/videoStable")
public class VideoStableController extends BaseController {
    @Resource
    private IVideoStableService videoStableService;

    @GetMapping("/compare/num/{task_id}")

    public CommonResult getCompareNum(@PathVariable("task_id") Long taskId) {
        return CommonResult.success(videoStableService.getCompareNum(taskId));
    }


    @GetMapping("/compare/{task_id}/{idx}")
    public ResponseEntity<Map<String, String>> getCompareImages(@PathVariable("task_id") Long taskId, @PathVariable("idx") int idx) {
        try {
            VideoStable videoStable = videoStableService.getById(taskId);

            Path inputPath = null;
            Path outputPath = null;
//            String osName = System.getProperty("os.name");
            // 判断是否是Windows环境
//            if (osName.toLowerCase().contains("windows")) {
//                inputPath = Paths.get("C:", videoStable.getInputPath());
//                outputPath = Paths.get("C:", videoStable.getOutputPath());
//            } else {
            inputPath = Paths.get(videoStable.getInputPath());
            outputPath = Paths.get(videoStable.getOutputPath());
//            }
            System.out.println("inputPath: " + inputPath.toString());
            System.out.println("outputPath: " + outputPath.toString());


            byte[] image1 = Files.readAllBytes(inputPath.resolve(String.format("%05d", idx) + ".jpg"));
            byte[] image2 = Files.readAllBytes(outputPath.resolve(String.format("%05d", idx) + ".jpg"));

            // 将图片编码成Base64字符串
            String base64Image1 = Base64.getEncoder().encodeToString(image1);
            String base64Image2 = Base64.getEncoder().encodeToString(image2);

            // 创建一个Map来存储Base64编码的图片
            Map<String, String> images = new HashMap<>();
            images.put("origin", base64Image1);
            images.put("stable", base64Image2);

            // 返回Map
            return ResponseEntity.ok(images);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).build();
        }
    }

     @PostMapping("/get_result")
     public CommonResult getResult(@Valid @RequestBody VideoStableStartResultBo videoStableStartResultBo) {
         return videoStableService.getResult(videoStableStartResultBo);
     }

    @GetMapping("/start/{id}")
    public CommonResult start(@PathVariable("id") Long id) {
        return videoStableService.start(id);
    }

    @GetMapping("/stop/{id}")
    public CommonResult stop(@PathVariable("id") Long id) {
        return videoStableService.stop(id);
    }

    /**
     * 查询视频去抖动列表
     */
    @SaCheckPermission("demo:videoStable:list")
    @GetMapping("/list")
    public CommonResult<PageResult<VideoStableVo>> list(VideoStableBo videoStableBo) {
        return CommonResult.success(videoStableService.selectPage(videoStableBo));
    }

    /**
     * 导出视频去抖动列表
     */
    @SaCheckPermission("demo:videoStable:export")
    @Log(title = "视频去抖动", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, VideoStableBo videoStableBo) {
        List<VideoStableVo> list = videoStableService.selectList(videoStableBo);
        ExcelUtil.exportExcel(list, "视频去抖动", VideoStableVo.class, response);
    }

    /**
     * 获取视频去抖动详细信息
     */
    @SaCheckPermission("demo:videoStable:query")
    @GetMapping(value = "/{id}")
    public CommonResult<VideoStableVo> getInfo(@PathVariable Long id) {
        return CommonResult.success(videoStableService.selectById(id));
    }

    /**
     * 新增视频去抖动
     */
    @SaCheckPermission("demo:videoStable:add")
    @Log(title = "视频去抖动", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping
    public CommonResult<Void> add(@Validated @RequestBody VideoStableBo videoStableBo) {
        boolean inserted = videoStableService.insert(videoStableBo);
        if (!inserted) {
            return CommonResult.fail("新增视频去抖动记录失败！");
        }
        return CommonResult.success();
    }

    /**
     * 修改视频去抖动
     */
    @SaCheckPermission("demo:videoStable:edit")
    @Log(title = "视频去抖动", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping
    public CommonResult<Void> edit(@Validated @RequestBody VideoStableBo videoStableBo) {
        Boolean updated = videoStableService.update(videoStableBo);
        if (!updated) {
            return CommonResult.fail("修改视频去抖动记录失败!");
        }
        return CommonResult.success();
    }

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

    @GetMapping("/images/{ossId}")
    public CommonResult<List<Map<String, String>>> getImages(@PathVariable("ossId") Long ossId) {
        return CommonResult.success(videoStableService.getImages(ossId));
    }
}
