package com.platform.modules.video.controller;

import com.platform.common.exception.RRException;
import com.platform.common.utils.FileUtils;
import com.platform.common.utils.PageUtils;
import com.platform.common.utils.R;
import com.platform.listener.VideoFileListener;
import com.platform.listener.VideoFileMonitor;
import com.platform.listener.VideoFileProperties;
import com.platform.modules.video.entity.VideoEntity;
import com.platform.modules.video.service.RealPathResolver;
import com.platform.modules.video.service.VideoService;
import com.platform.modules.video.util.VideoUtils;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

/**
 *
 *
 */
@RestController
@RequestMapping(value = "video")
public class VideoController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private static final String DEFAULT_TILLE = "无标题";

    private static final String DEFAULT_CREATE_METHOD = "快手视频下载";

    private static final String POINT = ".";

    private static final String INTERVAL = "interval";

    private static final String LISTENER_PATH = "listenerPath";

    private static final String BASE_PATH = ClassUtils.getDefaultClassLoader().getResource("").getPath().substring(1) + File.separator + "static/";

    @Autowired
    private VideoFileProperties videoFileProperties;

    @Autowired
    private VideoService videoService;

    @Autowired
    private RealPathResolver realPathResolver;

    @Autowired
    private VideoFileListener listener;

    private static VideoFileMonitor monitor = null;


    @GetMapping("/list")
//    @RequiresPermissions("video:list")
    @ApiOperation(value = "列表")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = videoService.queryPage(params);
        return R.ok().put("page", page);
    }

    @PostMapping("/update")
    @ApiOperation(value = "更新")
//    @RequiresPermissions("video:update")
    public R update(@RequestBody VideoEntity video) {
        if (video == null || video.getId() == null) {
            throw new RRException("更新有误!");
        }
        video.init();
        videoService.update(video);
        return R.ok();
    }

    @GetMapping("/listByCondition")
//    @RequiresPermissions("video:listByCondition")
    @ApiOperation(value = "条件查询")
    public R listByCondition(@RequestParam Map<String, Object> params) {
        PageUtils page = videoService.queryPageByConditions(params);
        return R.ok().put("page", page);
    }

    @PostMapping("/sendCheck")
//    @RequiresPermissions("video:sendCheck")
    @ApiOperation(value = "发送审核")
    public R sendCheck(@RequestBody Integer id ) {
        videoService.sendState(id);
        return R.ok();
    }


    @PostMapping("/checkOn")
//    @RequiresPermissions("video:checkOn")
    @ApiOperation(value = "审核通过")
    public R checkOn(@RequestBody  Map<String,Object> params) {
        videoService.updateOKState(Integer.parseInt(params.get("id").toString()), params.get("opinion").toString());
        return R.ok();
    }


    @PostMapping("/NoCheck")
//    @RequiresPermissions("video:NoCheck")
    @ApiOperation(value = "审核失败")
    public R UnCheck(@RequestBody  Map<String,Object> params) {
        videoService.updateNoState(Integer.parseInt(params.get("id").toString()), params.get("opinion").toString());
        return R.ok();
    }


    @PostMapping(value = "/save")
//    @RequiresPermissions("video:save")
    @ApiOperation(value = "保存")
    public R save(@RequestParam VideoEntity video) {
        if (video == null) {
            throw new RRException("保存对象为null");
        }
        video.init();
        videoService.save(video);
        return R.ok();
    }

    //批量删除
    @PostMapping("/deleteBatch")
//    @RequiresPermissions("video:deleteBatch")
    @ApiOperation(value = "批量删除")
    public R deleteBatch(@RequestBody Long[] videoIds) {
        videoService.deleteBatch(videoIds);
        return R.ok();
    }

    @PostMapping("/delete/{id}")
//    @RequiresPermissions("video:delete")
    @ApiOperation(value = "删除")
    public R delete(@PathVariable("id") Integer id) {
        if (id == null ){
            throw new RRException("id 不能为空!");
        }
        videoService.delete(id);
        return R.ok();
    }

    @GetMapping("/selectById")
//    @RequiresPermissions("video:selectById")
    @ApiOperation(value = "根据id查询")
    public R selectById(@RequestParam Integer id) {
        if (id == null ){
            throw new RRException("id 不能为空!");
        }
        VideoEntity video = videoService.selectById(id);
        return R.ok().put("video", video);
    }


    @PostMapping(value = "/local/upload")
    public R localUploadVideo(@RequestParam("file") MultipartFile multipartFile,@RequestParam("titleImg") MultipartFile titleImg, HttpServletRequest request) {
        if (multipartFile == null || multipartFile.isEmpty()){
            throw new RRException("multipartFile 不能为空!");
        }
        Map<String, String[]> map= request.getParameterMap();
        String newFileName = FileUtils.createFileName() + POINT + FileUtils.getSuffix(multipartFile.getOriginalFilename());
        String serverVideoPath = videoFileProperties.getBaseSavePath() + File.separator + VideoUtils.getDateDir() + File.separator + newFileName; // 存放在服务器地址
        String newFilePath = FileUtils.BASE_PATH + File.separator + serverVideoPath; // 保存视频的路径
        File file = new File(newFilePath);
        try {
            FileUtils.copy(multipartFile.getInputStream(), newFilePath);
        } catch (IOException e) {
        	throw new RRException("上传失败!");
        }

        // 保存上传文件
        VideoEntity videoEntity = new VideoEntity();
        videoEntity.setDate(new Date());
        System.out.println(file.getPath());
        videoEntity.setFileSize(VideoUtils.getFileSize(file, null));// 文件大小
        videoEntity.setDurationTime(VideoUtils.getPlayTime(file, null)); // 文件时长
        videoEntity.setTitle(DEFAULT_TILLE);
        videoEntity.setCreateMethod("1");
        videoEntity.setServerVideoPath(serverVideoPath);
        videoService.insert(videoEntity);
        return R.ok();
    }

    /**
     * 开启监控
     */
    @RequestMapping("/start/monitor")
    public void startMonitorVideo(@RequestParam Map<String, Object> params) throws Exception {
        if (params == null || params.size() == 0) {
            throw new RRException("未传入参数");
        }
        if (!params.containsKey(INTERVAL) || !params.containsKey(LISTENER_PATH)) {
            throw new RRException("没有传入必要的参数");
        }
        monitor = new VideoFileMonitor(Long.parseLong(params.get(INTERVAL).toString()));
        monitor.monitor(params.get(LISTENER_PATH).toString(), listener);
        monitor.start();
    }

    /**
     * 停止
     *
     * @throws Exception
     */
    @GetMapping("/stop/monitor")
    public void stopMonitor() throws Exception {

        if (monitor == null) {
            return;
        }
        monitor.stop();
        monitor = null;

    }

}