package org.jeecg.modules.orderplatform.controller;

import cn.com.ctop.common.module.utils.CosUtils;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.orderplatform.entity.PlatformMaterial;
import org.jeecg.modules.orderplatform.entity.PlatformScript;
import org.jeecg.modules.orderplatform.service.IPlatformMaterialService;
import org.jeecg.modules.orderplatform.service.IPlatformScriptService;
import org.jeecg.modules.orderplatform.service.IPlatformVideoService;
import org.jeecg.modules.orderplatform.util.ApprovalNodeNoticeHandler;
import org.jeecg.modules.orderplatform.util.OperateRecordHandler;
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 IPlatformVideoService platformVideoService;

    @Autowired
    private IPlatformScriptService platformScriptService;

    @Autowired
    private IPlatformMaterialService platformMaterialService;

    @Autowired
    private OperateRecordHandler operateRecordHandler;

    @Autowired
    private ApprovalNodeNoticeHandler approvalNodeNoticeHandler;

    /**
     * 新建订单上传附件
     */
    @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 {
            // 脚本上传成功需要返回脚本id,更新物料表，更新完成后去更新脚本库的绑定项目
            PlatformScript script = platformScriptService.saveScript(file,projectId);
            if (null == script) {
                result.error500("脚本上传失败");
                return result;
            }
            //物料状态->脚本已上传，待审核
            PlatformMaterial platformMaterial = platformMaterialService.getById(materialId);
            if (platformMaterial.getScriptStatus() ==3) {
                result.error500("数据已更新，请刷新页面");
                return result;
            }
            platformMaterial.setId(materialId);
            platformMaterial.setMaterialStatus(2);
            platformMaterial.setScriptStatus(1);
            platformMaterial.setScriptId(script.getId());
            boolean save = platformMaterialService.updateById(platformMaterial);
            if (save) {
                operateRecordHandler.Submit(platformMaterial.getMaterialCode(), "SCRIPT");
                approvalNodeNoticeHandler.NOTICE_WE_CHAT_MATERIAL("SCRIPT", platformMaterial.getMaterialCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @PostMapping("/uploadVideo")
    public Result<Object> uploadVideo(@RequestBody JSONObject requestBody) {
        Result<Object> result = new Result<>();
        //同一个视频不能出现在不同的物料下
        int repeat = platformMaterialService.queryCountByMaterialAndVideo(requestBody.getString("materialCode"), requestBody.getString("md5"));
        if (repeat > 0) {
            result.error500("视频已被其他物料上传，请重新选择视频");
            return result;
        }
        String videoMd5 = platformVideoService.uploadVideo(requestBody);
        if (videoMd5.isEmpty()) {
            result.error500("素材视频上传失败,参数为空");
        } else {
            //物料状态->视频已上传，待审核
            PlatformMaterial platformMaterial = platformMaterialService.getById(requestBody.getString("materialId"));
            if (platformMaterial.getVideoStatus() ==3) {
                result.error500("数据已更新，请刷新页面");
                return result;
            }
            platformMaterial.setId(requestBody.getLong("materialId"));
            platformMaterial.setMaterialStatus(5);
            platformMaterial.setVideoStatus(1);
            platformMaterial.setVideoId(videoMd5);
            boolean save = platformMaterialService.updateById(platformMaterial);
            if (save) {
                operateRecordHandler.Submit(platformMaterial.getMaterialCode(), "VIDEO");
                approvalNodeNoticeHandler.NOTICE_WE_CHAT_MATERIAL("VIDEO", platformMaterial.getMaterialCode());
                result.success("素材视频上传成功");
            }
        }
        return result;
    }
}
