package com.platform.controller;

import com.alibaba.fastjson.JSON;
import com.platform.annotation.SysLog;
import com.platform.entity.Result;
import com.platform.entity.SysOssEntity;
import com.platform.enums.ResultCodeEnum;
import com.platform.exception.CommonBaseException;
import com.platform.oss.CloudStorageConfig;
import com.platform.oss.OSSFactory;
import com.platform.service.SysConfigService;
import com.platform.service.SysOssService;
import com.platform.service.impl.ZhiHouseService;
import com.platform.utils.*;
import com.platform.validator.ValidatorUtils;
import com.platform.validator.group.AliyunGroup;
import com.platform.validator.group.DiskGroup;
import com.platform.validator.group.QcloudGroup;
import com.platform.validator.group.QiniuGroup;
import com.platform.vos.TbUser;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * 文件上传Controller
 *
 * @author lipengjun
 * @email 939961241@qq.com
 * @gitee https://gitee.com/fuyang_lipengjun/platform
 * @date 2017-03-25 12:13:26
 */
@RestController
@RequestMapping("sys/oss")
@Slf4j
public class SysOssController extends AbstractController{
    @Autowired
    private SysOssService sysOssService;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private UploadToOssUtil uploadToOssUtil;

    @Autowired
    private OssCheckPointUploadUtil ossCheckPointUploadUtil;

    @Value("${oss.query.url}")
    private String ossQueryUrl;

    @Value("${oss.video.file.path}")
    private String ossVideoPath;

    @Value("${video-file-path}")
    private String videoLocalBackupPath;

    private final static String KEY = Constant.CLOUD_STORAGE_CONFIG_KEY;

    /**
     * 列表
     *
     * @param params 请求参数
     * @return R
     */
    @RequestMapping("/list")
    
    public Result list(@RequestBody Map<String, Object> params) {
        //查询列表数据
        PageUtilsPlus pageUtil = sysOssService.queryPage(params);
        return Result.success(pageUtil);
    }


    /**
     * 获取云存储配置信息
     *
     * @return R
     */
    @RequestMapping("/config")
    
    public Result config() {
        CloudStorageConfig config = sysConfigService.getConfigObject(KEY, CloudStorageConfig.class);

        return Result.success(config);
    }


    /**
     * 保存云存储配置信息
     *
     * @param config 配置信息
     * @return R
     */
    @SysLog("保存云存储配置信息")
    @RequestMapping("/saveConfig")
    
    public Result saveConfig(@RequestBody CloudStorageConfig config) {
        //校验类型
        ValidatorUtils.validateEntity(config);

        if (config.getType() == Constant.CloudService.QINIU.getValue()) {
            //校验七牛数据
            ValidatorUtils.validateEntity(config, QiniuGroup.class);
        } else if (config.getType() == Constant.CloudService.ALIYUN.getValue()) {
            //校验阿里云数据
            ValidatorUtils.validateEntity(config, AliyunGroup.class);
        } else if (config.getType() == Constant.CloudService.QCLOUD.getValue()) {
            //校验腾讯云数据
            ValidatorUtils.validateEntity(config, QcloudGroup.class);
        } else if (config.getType() == Constant.CloudService.DISCK.getValue()) {
            //校验腾讯云数据
            ValidatorUtils.validateEntity(config, DiskGroup.class);
        }

        sysConfigService.updateValueByKey(KEY, JSON.toJSONString(config));

        return Result.success();
    }

    @ApiOperation(value = "上传视频")
    @PostMapping("/upLoadVideo")
    @ResponseBody
    public Result uploadIntroduceVideo(@RequestParam("file") MultipartFile file) {
        if (null == file) {
            throw new CommonBaseException(ResultCodeEnum.D3001);
        }
        log.info("当前视频大小为:{} bytes" , file.getSize());
        if(file.getSize() > 1024000000){
            return Result.failure("视频不能超过1G");
        }
        String downLoanVideoPath = FileUtils.parseFile(file, videoLocalBackupPath);
        log.info("视频文件已经下载到本地:{}", downLoanVideoPath);
        //视频文件名一般为:xxx.mp4这种格式
        String videoFilePureName = file.getOriginalFilename();
        log.info("视频文件名为:{}", videoFilePureName);
        //去掉格式，只获取纯名字
        int index = videoFilePureName.indexOf(".");
        //获取纯名字
        if (index != -1) {
            videoFilePureName = videoFilePureName.substring(0, index);
        } else {
            Random random = new Random();
            videoFilePureName = "default_imag_" + random.nextInt(10000);
            log.info("采用默认的图片名字:{}", videoFilePureName);
        }
        //这里默认第一帧图片是jpg格式
        String imageFormatter = "jpg";
        //视频在oss中的object name
        String imageOssObjectName = ossVideoPath + videoFilePureName + "." + imageFormatter;
        //截取视频第一帧图片
        boolean cutFirstImageResult = FileUtils.executeCodecs(downLoanVideoPath, videoLocalBackupPath,
                videoFilePureName, imageFormatter);

        if (cutFirstImageResult) {
            log.info("成功截取第一帧图片，将上传到oss上");
            String imageLocalPath = videoLocalBackupPath + videoFilePureName + "." + imageFormatter;
            uploadToOssUtil.uploadThenDelete(imageLocalPath, imageOssObjectName);
            log.info("上传第一帧图片到oss完成");
        }

        String videoObjectName = ossVideoPath + file.getOriginalFilename();
        ossCheckPointUploadUtil.doUploadThenDelete(downLoanVideoPath, videoObjectName);

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("image", ossQueryUrl + imageOssObjectName);
        resultMap.put("video", ossQueryUrl + videoObjectName);
        return Result.success("视频文件上传oss结束", resultMap);
    }

    /**
     * 上传文件
     *
     * @param file 文件
     * @return R
     * @throws Exception 异常
     */
    @RequestMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }
        //上传文件
        String url = OSSFactory.build().upload(file);

        //保存文件信息
        SysOssEntity ossEntity = new SysOssEntity();
        ossEntity.setUrl(url);
        ossEntity.setCreateDate(new Date());
        ossEntity.setUserId(getUserId());
        if( getUser() != null){
            ossEntity.setUsername(getUser().getUserName());
        }
        sysOssService.save(ossEntity);
        HashMap<String,Object> map = new HashMap<>();
        map.put("url", url);
        map.put("link", url);
        return Result.success(map);
    }


    /**
     * 删除图片
     *
     * @param ids 主键集
     * @return R
     */
    @SysLog("删除图片")
    @RequestMapping("/delete")
    
    public Result delete(@RequestBody Long[] ids) {
        sysOssService.removeByIds(Arrays.asList(ids));

        return Result.success();
    }
}
