package org.jeecg.modules.orderplatform.service.impl;

import cn.com.ctop.common.module.entity.MaterialTagInfo;
import cn.com.ctop.common.module.material.entity.MaterialVideoAuthor;
import cn.com.ctop.common.module.material.entity.MaterialVideoCover;
import cn.com.ctop.common.module.material.entity.MaterialVideoInfo;
import cn.com.ctop.common.module.material.entity.MaterialVideoProject;
import cn.com.ctop.common.module.material.service.*;
import cn.com.ctop.common.module.service.IMaterialCutFrameService;
import cn.com.ctop.common.module.service.IMaterialTagInfoService;
import cn.com.ctop.common.module.service.IProjectService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.modules.orderplatform.entity.PlatformMaterial;
import org.jeecg.modules.orderplatform.entity.PlatformVideo;
import org.jeecg.modules.orderplatform.mapper.PlatformMaterialMapper;
import org.jeecg.modules.orderplatform.service.IPlatformMaterialService;
import org.jeecg.modules.orderplatform.service.IPlatformVideoService;
import org.jeecg.modules.orderplatform.util.JsonArrayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 物料审批流程
 */
@Service
public class PlatformMaterialServiceImpl extends ServiceImpl<PlatformMaterialMapper, PlatformMaterial> implements IPlatformMaterialService {

    @Autowired
    PlatformMaterialMapper platformMaterialMapper;

    @Autowired
    IPlatformVideoService platformVideoService;

    @Autowired
    IMaterialVideoInfoService materialVideoInfoService;

    @Autowired
    IMaterialVideoCoverService materialVideoCoverService;

    @Autowired
    IMaterialTagInfoService materialTagInfoService;

    @Autowired
    IMaterialVideoAuthorService materialVideoAuthorService;

    @Autowired
    IMaterialVideoProjectService materialVideoProjectService;

    @Autowired
    IMaterialVideoFrameService materialVideoFrameService;

    @Autowired
    IMaterialCutFrameService materialCutFrameService;

    @Autowired
    IProjectService projectService;

    @Override
    public List<JSONObject> queryMaterialsByDesignUserId(String materialStatus, String designUserId) {
        JSONArray materialStatusJsonArray = JsonArrayUtil.Varchar2JSONArray(materialStatus);
        List<JSONObject> result = new ArrayList<>();
        if ("0".equals(materialStatus)) {
            result = platformMaterialMapper.queryMaterialsByDesignLeader(materialStatusJsonArray, designUserId);
        } else {
            result = platformMaterialMapper.queryMaterialsByDesignUserId(materialStatusJsonArray, designUserId);
        }
        return result;
    }

    @Override
    public List<JSONObject> queryMaterialsByOperatorUserId(String operatorUserId) {
        return platformMaterialMapper.queryMaterialsByOperatorUserId(operatorUserId);
    }

    @Override
    public JSONObject queryScriptDetailById(String scriptId) {
        return platformMaterialMapper.queryScriptDetailById(scriptId);
    }

    @Override
    public JSONObject queryVideoDetailById(String videoId) {
        return platformMaterialMapper.queryVideoDetailById(videoId);
    }

    @Override
    public int queryCountByMaterialAndVideo(String materialCode, String videoMd5) {

        return platformMaterialMapper.queryCountByMaterialAndVideo(materialCode, videoMd5);
    }

    @Override
    public boolean syncVideo2CTopMaterial(PlatformMaterial platformMaterial) {
        boolean result=false;
        //step1: 查询下单制物料、视频信息
        QueryWrapper<PlatformVideo> wrapperPV = new QueryWrapper<>();
        wrapperPV.eq("md5", platformMaterial.getVideoId());
        wrapperPV.eq("is_delete", 0);
        PlatformVideo video = platformVideoService.getOne(wrapperPV);
        //查询物料信息
        QueryWrapper<PlatformMaterial> wrapper = new QueryWrapper<>();
        wrapper.eq("material_code", platformMaterial.getMaterialCode());
        platformMaterial= this.getOne(wrapper);
        boolean mv = materialVideoInfoHandle(video, platformMaterial.getMaterialType(), projectService.getSupplierCodeById(platformMaterial.getProjectId()));
        if(mv){
            result = materialVideoCorrelateHandle(video.getMd5());
            if(result){
                //启动截帧
                materialCutFrameHandle(video);
            }
        }else {
            materialVideoInfoService.deleteByMd5(video.getMd5());
        }
        return result;
    }

    @Override
    public Map<String, Object> videoEcho(String videoId) {
        Map<String, Object> result = new HashMap<>();
        QueryWrapper<PlatformVideo> wrapperPV = new QueryWrapper<>();
        wrapperPV.eq("md5", videoId);
        wrapperPV.eq("is_delete", 0);
        result.put("video", platformVideoService.getOne(wrapperPV));
        QueryWrapper<MaterialVideoCover> wrapperMVC = new QueryWrapper<>();
        wrapperMVC.eq("video_md5", videoId);
        result.put("covers", materialVideoCoverService.list(wrapperMVC));
        MaterialTagInfo materialTagInfo = new MaterialTagInfo();
        materialTagInfo.setCode(videoId);
        materialTagInfo.setStatus(1);
        result.put("tags", materialTagInfoService.getTagDetail(materialTagInfo));
        return result;
    }

    @Override
    public JSONObject getMaterialRelatePersonByMaterialCode(String materialCode) {
        return platformMaterialMapper.queryMaterialRelatePersonByMaterialCode(materialCode);
    }

    @Override
    public JSONObject getOrderRelatePersonByMaterialCode(String orderCode) {
        return platformMaterialMapper.queryOrderRelatePersonByMaterialCode(orderCode);
    }

    /**
     * 同步素材视频
     */
    private boolean materialVideoInfoHandle(PlatformVideo platformVideo, int materialType, String supplierCode) {

        MaterialVideoInfo materialVideoInfo = new MaterialVideoInfo();
        materialVideoInfo.setName(platformVideo.getName());
        materialVideoInfo.setMd5(platformVideo.getMd5());
        materialVideoInfo.setUrl(platformVideo.getUrl());
        materialVideoInfo.setCoverUrl(platformVideo.getCoverUrl());
        materialVideoInfo.setMaterialType(materialType);
        materialVideoInfo.setSupplierCode(supplierCode);
        materialVideoInfo.setDescription(platformVideo.getDescription());
        materialVideoInfo.setFormat(platformVideo.getFormat());
        materialVideoInfo.setDuration(platformVideo.getDuration());
        materialVideoInfo.setSize(platformVideo.getSize());
        materialVideoInfo.setHeight(platformVideo.getHeight());
        materialVideoInfo.setWidth(platformVideo.getWidth());
        //先验证是否有重复
        materialVideoInfoService.deleteByMd5(platformVideo.getMd5());
        //再同步视频
        return materialVideoInfoService.save(materialVideoInfo);
    }

    /**
     * 保存视频素材关联项目、作者信息
     */
    private boolean materialVideoCorrelateHandle(String videoMd5) {

        JSONObject videoDetail = platformMaterialMapper.queryVideoDetailById(videoMd5);
        //项目绑定
        MaterialVideoProject materialVideoProject = new MaterialVideoProject();
        materialVideoProject.setProjectId(videoDetail.getLong("projectId"));
        materialVideoProject.setVideoMd5(videoMd5);
        //作者信息绑定
        MaterialVideoAuthor materialVideoAuthor = new MaterialVideoAuthor();
        materialVideoAuthor.setVideoMd5(videoMd5);
        materialVideoAuthor.setClipId(videoDetail.getString("clip"));
        materialVideoAuthor.setClipName(videoDetail.getString("clipName"));
        materialVideoAuthor.setShotId(videoDetail.getString("shot"));
        materialVideoAuthor.setShotName(videoDetail.getString("shotName"));
        materialVideoAuthor.setPlanId(videoDetail.getString("plan"));
        materialVideoAuthor.setPlanName(videoDetail.getString("planName"));
        materialVideoAuthor.setPlaneId(videoDetail.getString("plane"));
        materialVideoAuthor.setPlaneName(videoDetail.getString("plane_name"));

        return materialVideoProjectService.save(materialVideoProject) && materialVideoAuthorService.save(materialVideoAuthor);
    }

    /**
     * 开启截帧任务
     */
    private void materialCutFrameHandle(PlatformVideo platformVideo) {
        int cutFrame = materialVideoFrameService.getFrameCountByCode(platformVideo.getMd5());
        if (cutFrame == 0) {
            String videoUrl = URLDecoder.decode(platformVideo.getUrl()).replace("https://media-1301855440.cos.ap-chongqing.myqcloud.com/", "");
            Thread thread = new Thread() {
                @Override
                public void run() {
                    try {
                        materialVideoFrameService.getTencentCutFrame(videoUrl, platformVideo.getMd5(), platformVideo.getCoverUrl());
                    } catch (Exception e) {
                        log.error("智能抽帧任务失败，视频md5:" + platformVideo.getMd5());
                    }
                }
            };
            thread.start();
        }
    }
}
