package org.dromara.system.controller;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.codec.Base64Decoder;
import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.dromara.system.utils.Utils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.web.core.BaseController;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.system.domain.vo.TblDeviceVo;
import org.dromara.system.domain.bo.TblDeviceBo;
import org.dromara.system.service.ITblDeviceService;
import org.dromara.common.mybatis.core.page.TableDataInfo;

/**
 * 设备-摄像机
 *
 * @author Lion Li
 * @date 2025-07-01
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/device")
public class TblDeviceController extends BaseController {

    private final ITblDeviceService tblDeviceService;

    /**
     * 查询设备-摄像机列表
     */
//    @SaCheckPermission("system:device:list")
    @GetMapping("/list")
    public TableDataInfo<TblDeviceVo> list(TblDeviceBo bo, PageQuery pageQuery) {
        return tblDeviceService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出设备-摄像机列表
     */
//    @SaCheckPermission("system:device:export")
    @Log(title = "设备-摄像机", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(TblDeviceBo bo, HttpServletResponse response) {
        List<TblDeviceVo> list = tblDeviceService.queryList(bo);
        ExcelUtil.exportExcel(list, "设备-摄像机", TblDeviceVo.class, response);
    }

    /**
     * 获取设备-摄像机详细信息
     *
     * @param id 主键
     */
//    @SaCheckPermission("system:device:query")
    @GetMapping("/{id}")
    public R<TblDeviceVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(tblDeviceService.queryById(id));
    }

    /**
     * 新增设备-摄像机
     */
//    @SaCheckPermission("system:device:add")
    @Log(title = "设备-摄像机", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody TblDeviceBo bo) {
        return toAjax(tblDeviceService.insertByBo(bo));
    }

    /**
     * 修改设备-摄像机
     */
//    @SaCheckPermission("system:device:edit")
    @Log(title = "设备-摄像机", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody TblDeviceBo bo) {
        return toAjax(tblDeviceService.updateByBo(bo));
    }

    /**
     * 删除设备-摄像机
     *
     * @param ids 主键串
     */
//    @SaCheckPermission("system:device:remove")
    @Log(title = "设备-摄像机", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(tblDeviceService.deleteWithValidByIds(List.of(ids), true));
    }

    private Map<String, Utils.PrintStream> rtmptohlsmap = new HashMap<>();
    @Value(value = "${user.hls.path}")
    private String path;
    @Value(value = "${user.hls.url}")
    private String url;
    @Value("${user.ffmpegpath}")
    private String ffmpegFilePath = "/usr/local/bin/ffmpeg";

    @GetMapping("/rtmp/{from}")
    public R<Object> getHlsCode(@PathVariable("from") String from) {
        Object data = "";
        try {

            from = Base64Decoder.decodeStr(from);
            String p[] = from.split("/");
            if (rtmptohlsmap.get(from) != null && rtmptohlsmap.get(from).isAlive()) {

            } else {
                File pc = new File(path + p[p.length - 1] + "");
                if (!pc.exists()) {
                    pc.mkdir();
                    pc.setWritable(true, false);
                    File pc1 = new File(path + p[p.length - 1] + "/playlist.m3u8");
                    pc1.createNewFile();
                    pc1.setWritable(true, false);

                }
                rtmptohlsmap.put(from, Utils.push(ffmpegFilePath, from, path + p[p.length - 1] + "/playlist.m3u8"));
            }
            data = url + p[p.length - 1] + "/playlist.m3u8";
        } catch (Exception e) {

        }
        return R.ok(data);
    }

    @GetMapping("/rtmp/close/{from}")
    public R<Object> closeHlsCode(@PathVariable("from") String from) {
        Object data = "";
        try {

            from = Base64Decoder.decodeStr(from);
            String p[] = from.split("/");
            if (rtmptohlsmap.get(from) != null && rtmptohlsmap.get(from).isAlive()) {
                rtmptohlsmap.get(from).interrupt();
                rtmptohlsmap.remove(from);
            }
        } catch (Exception e) {

        }
        return R.ok(data);
    }
}
