package com.fdage.service.impl;

import cn.hutool.core.date.DateUtil;
import com.fdage.constant.MsgCode;
import com.fdage.dao.base.SceneMapper;
import com.fdage.dao.base.VideoMapper;
import com.fdage.dto.SceneDto;
import com.fdage.dto.VideoDto;
import com.fdage.entity.SceneEntity;
import com.fdage.entity.VideoEntity;
import com.fdage.service.SceneService;
import com.fdage.service.VideoService;
import com.fdage.util.BaseRuntimeException;
import com.fdage.util.FileUtils;
import com.fdage.util.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * Created by owen on 2021/8/23 0023 17:16
 */
@Service
public class VideoServiceImpl implements VideoService {

    @Resource
    VideoMapper videoMapper;

    @Autowired
    FileUtils fileUtils;

    @Override
    public Result<VideoEntity> findAll() {
        return Result.success(videoMapper.findAll());
    }

    @Override
    public Result<VideoEntity> saveEntity(VideoDto param) {

        Long id = param.getId();
        VideoEntity entity = null;
        if (id == null) {
            entity = new VideoEntity();
            BeanUtils.copyProperties(param, entity);
            videoMapper.insert(entity);
        } else {
            entity = videoMapper.findById(id);
            if (entity == null) {
                return Result.failure("对象不存在： " + id);
            }
            BeanUtils.copyProperties(param, entity);
            entity.setUpdateTime(LocalDateTime.now());
            videoMapper.update(entity);
        }

        return Result.success();
    }



    @Override
    public Result upload(MultipartFile file, String dirCode , boolean useCode) {
        if (!fileUtils.checkFile(file)) {
            throw new BaseRuntimeException("非法文件, 请重新上传");
        }

        String resUrl = "/video";
        if (useCode) {
            if ("null".equals(dirCode) || StringUtils.isBlank(dirCode)) {
                dirCode = DateUtil.format(LocalDateTime.now(), "yyyyMMdd_HHmmssSSS");
            }
            resUrl = resUrl + "/" + dirCode;
        }

        Map<String, Object> result = fileUtils.upload(file, resUrl );

        return Result.success(result);
    }

    @Override
    public Result detail(Long id) {
        VideoEntity entity = videoMapper.findById(id);
        if (entity == null) {
            return Result.failure(MsgCode.e3001,"对象不存在，id: " + id);
        }

        return Result.success(entity);
    }

    @Override
    public Result remove(Long id) {
        videoMapper.remove(id);
        return Result.success();
    }

}
