package org.jeecg.modules.orderplatform.controller;

import cn.com.ctop.common.module.service.IMaterialInfoService;
import cn.com.ctop.common.module.utils.CosUtils;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.orderplatform.entity.PlatformMaterial;
import org.jeecg.modules.orderplatform.service.IPlatformMaterialService;
import org.jeecg.modules.orderplatform.util.OperateRecordHandler;
import org.jeecg.modules.wps.entity.WpsFile;
import org.jeecg.modules.wps.service.IWpsFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件处理接口
 */
@Slf4j
@RestController
@RequestMapping("/platform/file")
public class PlatformFileCtrl {

    @Autowired
    private IWpsFileService wpsFileService;

    @Autowired
    private IMaterialInfoService materialInfoService;

    @Autowired
    private IPlatformMaterialService platformMaterialService;

    @Autowired
    private OperateRecordHandler operateRecordHandler;

    /**
     * 新建订单上传附件
     */
    @PostMapping("/uploadAttachment")
    public Result<Map<String, Object>> uploadAttachment(@RequestParam("file") MultipartFile file,
                                                        @RequestParam("projectId") Long projectId) {
        Result<Map<String, Object>> result = new Result<>();
        if (file.isEmpty() || !((file.getOriginalFilename().endsWith(".zip") || file.getOriginalFilename().endsWith(".rar") || file.getOriginalFilename().endsWith(".7z")))) {
            result.error500("请上传正确的压缩文件");
        } else {
            String fileName = projectId + "_" + System.currentTimeMillis()+"_"+file.getOriginalFilename();
            InputStream inputStream = null;
            try {
                inputStream = file.getInputStream();
            } catch (IOException e) {
                log.error("工作台下单附件上传异常");
            }
            String attachmentPath = "attachment/zip/" + DateUtils.date2Str() + "/";
            CosUtils.uploadFileByInputStream(inputStream, attachmentPath, fileName);
            Map<String, Object> detail = new HashMap<>();
            detail.put("attachmentName", fileName);
            detail.put("attachmentUrl", "https://media-1301855440.cos.ap-chongqing.myqcloud.com/" + attachmentPath + fileName);
            result.setResult(detail);
        }
        return result;
    }

    /**
     * 编导上传脚本
     */
    @PostMapping("/uploadScript")
    public Result<Object> uploadScript(@RequestParam("file") MultipartFile file,
                                       @RequestParam("materialId") Long materialId,
                                       @RequestParam("projectId") Long projectId) {
        Result<Object> result = new Result<>();
        try {
            LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            // 脚本上传成功需要返回脚本id,更新物料表，更新完成后去更新脚本库的绑定项目
            WpsFile wpsFile = wpsFileService.uploadFile(file, user.getId());
            if (null == wpsFile) {
                result.error500("脚本上传失败");
                return result;
            }
            //物料状态->脚本已上传，待审核
            PlatformMaterial platformMaterial = new PlatformMaterial();
            platformMaterial.setId(materialId);
            platformMaterial.setMaterialStatus(2);
            platformMaterial.setScriptStatus(1);
            platformMaterial.setScriptId(wpsFile.getId());
            boolean save = platformMaterialService.updateById(platformMaterial);
            if (save) {
                // 更新脚本库的绑定项目
                wpsFile.setProjectId(projectId);
                //  Todo 暂时兼容题库
                wpsFile.setIsScript(0);
                wpsFileService.updateById(wpsFile);
                operateRecordHandler.Submit(platformMaterialService.getById(materialId).getMaterialCode(), "SCRIPT");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 剪辑上传视频
     * Todo 在下单制正式上线后，这个接口会改造
     */
    @PostMapping("/uploadVideo")
    public Result<Object> uploadVideo(@RequestBody JSONObject requestBody) {
        Result<Object> result = new Result<>();
        String videoId = materialInfoService.platformUploadVideo(requestBody);
        if (videoId.isEmpty()) {
            result.error500("同步素材库失败，请联系管理员");
        } else {
            //物料状态->视频已上传，待审核
            PlatformMaterial platformMaterial = new PlatformMaterial();
            platformMaterial.setId(requestBody.getLong("materialId"));
            platformMaterial.setMaterialStatus(5);
            platformMaterial.setVideoStatus(1);
            platformMaterial.setVideoId(videoId);
            boolean save = platformMaterialService.updateById(platformMaterial);
            if (save) {
                operateRecordHandler.Submit(platformMaterialService.getById(requestBody.getString("materialId")).getMaterialCode(), "VIDEO");
                result.success("同步素材库成功");
            }
        }
        return result;
    }

}
