package cn.com.ctop.common.module.service.impl;

import cn.com.ctop.common.module.constant.CosConstant;
import cn.com.ctop.common.module.entity.*;
import cn.com.ctop.common.module.enums.MaterialSupplierEnum;
import cn.com.ctop.common.module.mapper.MaterialAscriptionMapper;
import cn.com.ctop.common.module.mapper.MaterialInfoMapper;
import cn.com.ctop.common.module.mapper.MaterialParameterMapper;
import cn.com.ctop.common.module.mapper.MaterialTagMapper;
import cn.com.ctop.common.module.service.*;
import cn.com.ctop.common.module.utils.*;
import cn.com.ctop.common.module.vo.ResFileDTO;
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 com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tencentcloudapi.mps.v20190612.models.DescribeTaskDetailResponse;
import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.EncoderException;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLDecoder;
import java.nio.channels.FileChannel;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static cn.com.ctop.common.module.utils.CloudVideoProcessUtil.getTaskDetailResponse;
import static cn.com.ctop.common.module.utils.CloudVideoProcessUtil.videoWatermarkHandle;

/**
 * 素材信息
 *
 * @author jeecg-boot
 * @version V1.0
 * @date 2019-10-11
 */
@Slf4j
@Service
public class MaterialInfoServiceImpl extends ServiceImpl<MaterialInfoMapper, MaterialInfo> implements IMaterialInfoService {

    private static ExecutorService uploadExecutorService = Executors.newFixedThreadPool(5);

    @Resource
    private ITencentWatermarkTemplateService tencentWatermarkTemplateService;
    @Resource
    private IVideoWatermarkTaskService videoWatermarkTaskService;
    @Resource
    private MaterialInfoMapper materialInfoMapper;
    @Resource
    private MaterialParameterMapper materialParameterMapper;
    @Resource
    private MaterialAscriptionMapper materialAscriptionMapper;
    @Resource
    private MaterialTagMapper materialTagMapper;
    @Resource
    private IMaterialCutFrameService materialCutFrameService;
    @Autowired
    private ISupplierWatermarkService supplierWatermarkService;
    @Resource
    private IProductService productService;
    @Value("${oss.replace.download}")
    private String downloadUrl;

    @Override
    public void watermarkVideo(String materialId, Long videoWatermarkTemplateId, String userId) {
        TencentWatermarkTemplate tentcentWatermarkTemplate = tencentWatermarkTemplateService.getById(videoWatermarkTemplateId);
        MaterialInfo materialInfo = this.getById(materialId);
        if (Check.isNull(materialInfo)) {
            return;
        }
        if (Check.isNull(materialInfo.getUrl())) {
            return;
        }
        String fileUrl = "";
        InputStream imageStream = LoadFileUtil.getFileStream(materialInfo.getUrl());
        if (!Check.isNull(imageStream)) {
            long time = System.currentTimeMillis();
            ResFileDTO file = CosUtils.uploadDetailInputStreamV2(imageStream, time + ".mp4", "mp4", 0L, "temp/");
            fileUrl = file.getFileUrl();
        }
        if (Check.isNull(fileUrl)) {
            return;
        }
        String path = URLDecoder.decode(fileUrl.substring(fileUrl.indexOf("/", 10) + 1, fileUrl.length()));
        String taskId = videoWatermarkHandle(path, tentcentWatermarkTemplate.getTemplateId());
        DescribeTaskDetailResponse taskDetailResponse = null;
        for (int i = 0; i < 30; i++) {
            try {
                Thread.sleep(4000);
            } catch (InterruptedException e) {
                log.error(e.getMessage());
            }
            taskDetailResponse = getTaskDetailResponse(taskId);
            if ("FINISH".equals(taskDetailResponse.getStatus())) {
                break;
            }
        }
        if ("FINISH".equals(taskDetailResponse.getStatus())) {
            String videoUrl = taskDetailResponse.getWorkflowTask().getMediaProcessResultSet()[0].getTranscodeTask().getOutput().getPath();
            VideoWatermarkTask videoWatermarkTask = new VideoWatermarkTask();
            videoWatermarkTask.setVideoUrl(CosConstant.COS_MEDIA_URL_PREFIX + videoUrl);
            videoWatermarkTask.setVideoId(materialId);
            videoWatermarkTask.setJobId(taskId);
            videoWatermarkTask.setUserId(userId);
            videoWatermarkTask.setStatus(taskDetailResponse.getStatus());
            videoWatermarkTaskService.save(videoWatermarkTask);
            materialInfo.setWatermarkUrl(CosConstant.COS_MEDIA_URL_PREFIX + videoUrl);
            materialInfo.setWatermarkCode(taskId);
            this.updateById(materialInfo);
        }

    }


    @Override
    public String watermarkVideoBySupplierCode(String videoSignature, String videoUrl, Long templateId) {
        try {
            QueryWrapper<SupplierWatermark> supplierWatermarkQueryWrapper = new QueryWrapper<>();
            supplierWatermarkQueryWrapper.eq("video_signature", videoSignature);
            supplierWatermarkQueryWrapper.last("limit 1");
            SupplierWatermark one = supplierWatermarkService.getOne(supplierWatermarkQueryWrapper);
            if (!Check.isNull(one)) {
                log.info("供应商水印已存在，videoCode:{}", videoSignature);
                return one.getWatermarkUrl();
            }
            String path = URLDecoder.decode(videoUrl).replace("https://media-1301855440.cos.ap-chongqing.myqcloud.com/", "");
            String taskId = videoWatermarkHandle(path, templateId);
            DescribeTaskDetailResponse taskDetailResponse = null;
            for (int i = 0; i < 30; i++) {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    log.error(e.getMessage());
                }
                taskDetailResponse = getTaskDetailResponse(taskId);
                if ("FINISH".equals(taskDetailResponse.getStatus())) {
                    break;
                }
            }
            if ("FINISH".equals(taskDetailResponse.getStatus())) {
                String url = taskDetailResponse.getWorkflowTask().getMediaProcessResultSet()[0].getTranscodeTask().getOutput().getPath();
                SupplierWatermark supplierWatermark = new SupplierWatermark();
                supplierWatermark.setVideoSignature(videoSignature);
                String watermarkUrl = "https://media-1301855440.cos.ap-chongqing.myqcloud.com" + url;
                supplierWatermark.setWatermarkUrl(watermarkUrl);
                boolean save = supplierWatermarkService.save(supplierWatermark);
                if (save) {
                    log.info("供应商水印生成完毕，videoCode:{}", videoSignature);

                }
                return watermarkUrl;
            }
        } catch (Exception e) {
            log.info("供应商水印生成异常，videoCode:{}", videoSignature);
            e.printStackTrace();
        }
        return null;
    }


    @Override
    public MaterialInfo getMaterialInfoByCodeAndProductId(String code, Long projectId) {
        QueryWrapper<MaterialInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code", code);
        queryWrapper.eq("project_id", projectId);
        queryWrapper.orderByDesc("id").last("limit 1");
        return this.getOne(queryWrapper);
    }


    @Override
    public MaterialInfo getMaterialInfoByCode(String code) {
        QueryWrapper<MaterialInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code", code);
        queryWrapper.orderByDesc("id").last("limit 1");
        return this.getOne(queryWrapper);
    }

    @Override
    public Map<String, Object> checkMaterialInfo(String code, Long projectId) {
        Map<String, Object> result = new HashMap<>();
        MaterialInfo info = this.getMaterialInfoByCodeAndProductId(code, projectId);
        if (null != info) {
            //文件已存在
            ResultMapUtils.setResultMap(result, StatusCode.FILE_HAS_UPLOAD.getCode());
            result.put("url", info.getUrl());
            return result;
        } else {
            //文件尚未上传
            ResultMapUtils.setResultMap(result, StatusCode.FILE_HAS_NOT_UPLOAD.getCode());
            return result;
        }
    }

    @Override
    public Map<String, Object> insert(JSONObject jsonObject) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            String type = jsonObject.getString("type");
            if ("IMAGE".equals(type)) {
                JSONArray imageArr = jsonObject.getJSONArray("imageArr");
                if (!Check.isNull(imageArr)) {
                    jsonObject.remove("imageArr");
                    for (int i = 0; i < imageArr.size(); i++) {
                        String url = imageArr.getString(i);
                        if (!Check.isNull(url)) {
                            jsonObject.remove("code");
                            jsonObject.remove("materialName");
                            url = "https:" + url;
                            String localPath = LoadFileUtil.downLoadFromUrl(url, PropertiesUtils.getValue("kuaishou_config", "video_sava_path"));
                            String md5 = LoadFileUtil.getMD5(localPath);
                            jsonObject.put("code", md5);
                            LoadFileUtil.delFile(localPath);
                            String fileName = url.substring(url.lastIndexOf("/") + 1);
                            String fileNameStr = null;
                            if (!Check.isNull(fileName)) {
                                String[] split = fileName.split("-");
                                fileNameStr = split[0];
                            }
                            jsonObject.put("materialName", AesEncryptUtil.getUrlDecoderString(fileNameStr));
                            insertMaterialInfo(url, type, jsonObject);
                        }

                    }
                }

            } else {
                String url = "";
                if (!Check.isNull(jsonObject.getString("url"))) {
                    url = "https:" + jsonObject.getString("url");
                }
                insertMaterialInfo(url, type, jsonObject);
            }

            ResultMapUtils.setResultMap(resultMap, StatusCode.COMMON_SUCCESS.getCode());
        } catch (Exception e) {
            ResultMapUtils.setResultMap(resultMap, StatusCode.MATERIAL_UPLOAD_FAIL.getCode());
            e.printStackTrace();

        }


        return resultMap;
    }

    private void insertMaterialInfo(String url, String type, JSONObject jsonObject) {
        MaterialInfo info = new MaterialInfo();
//        Long projectId = jsonObject.getLong("projectId");
        Long productId = jsonObject.getLong("productId");
        String code = jsonObject.getString("code");
        info.setId(code + productId);
        info.setCode(code);
        if (!Check.isNull(jsonObject.getString("watermarkUrl"))) {
            info.setWatermarkUrl(jsonObject.getString("watermarkUrl"));
        }
        info.setUrl(url);
        info.setUserId(jsonObject.getString("userId"));
//        info.setProjectId(projectId);
        info.setProductId(productId);
        info.setWatermarkCode(jsonObject.getString("watermarkCode"));
        info.setStatus(0);
        info.setMaterialName(jsonObject.getString("materialName"));
        info.setWatermarkMaterialName(jsonObject.getString("watermarkMaterialName"));
        info.setMaterialDescribe(jsonObject.getString("materialDescribe"));
        info.setCreateTime(new Date());
        info.setUpdateTime(new Date());
        info.setType(type);
        this.save(info);
        Map<String, Object> deleteMap = new HashMap<>();
        deleteMap.put("material_id", info.getCode());
        JSONObject ascription = jsonObject.getJSONObject("ascription");
        if (!Check.isNull(ascription)) {
            MaterialAscription materialAscription = new MaterialAscription();
            materialAscription.setMaterialId(info.getId());
            // 剪辑人
            materialAscription.setClipId(ascription.getString("clipId"));
            // 拍摄人id
            materialAscription.setShotId(ascription.getString("shotId"));
            // 策划id
            materialAscription.setPlanId(ascription.getString("planId"));
            //平面id
            materialAscription.setPlaneId(ascription.getString("planeId"));
            materialAscriptionMapper.deleteByMap(deleteMap);
            int i = materialAscriptionMapper.insert(materialAscription);
            if (i > 0) {
                log.info("素材归属信息入库完成，MaterialId:{}", info.getId());
            }

        }

        JSONArray tag = jsonObject.getJSONArray("tag");
        if (!Check.isNull(tag)) {
            materialTagMapper.deleteByMap(deleteMap);
            for (int i = 0; i < tag.size(); i++) {
                String tagStr = tag.getString(i);
                if (!Check.isNull(tagStr)) {
                    MaterialTag materialTag = new MaterialTag();
                    materialTag.setMaterialId(info.getId());
                    materialTag.setTag(tagStr);
                    materialTagMapper.insert(materialTag);
                }
            }
        }

        getFile(info);

    }


    /**
     * 获取素材详细信息
     *
     * @param materialId
     * @return
     */
    @Override
    public JSONObject getDetail(String materialId) {
        JSONObject json = new JSONObject();
        MaterialInfo materialInfo = this.getById(materialId);
        if (!Check.isNull(materialInfo.getAuditorId())) {
            String auditorName = materialInfoMapper.selectUserNameById(materialInfo.getAuditorId());
            json.put("auditorName", auditorName);
        } else {
            json.put("auditorName", "");
        }

        List<String> tagList = materialTagMapper.selectByMaterialId(materialInfo.getCode());
        if (!Check.isNull(tagList)) {
            json.put("tag", tagList);
        }
        QueryWrapper<MaterialParameter> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("material_id", materialInfo.getCode());
        queryWrapper.orderByDesc("create_time");
        queryWrapper.last("limit 1");
        MaterialParameter materialParameter = materialParameterMapper.selectOne(queryWrapper);

        if (!Check.isNull(materialParameter)) {
            json.put("parameter", materialParameter);
        }

        JSONObject ascriptionJson = materialAscriptionMapper.selectByMaterialId(materialInfo.getCode());
        if (!Check.isNull(ascriptionJson)) {
            json.put("ascription", ascriptionJson);
        }
        return json;
    }

    /**
     * 工作台报表
     *
     * @param userId
     * @return
     */
    @Override
    public JSONObject report(String userId) {

        JSONObject json = new JSONObject();
        try {
            Map<String, Object> requestMap = new HashMap<>();
            requestMap.put("userId", userId);
            Integer totalCount = materialInfoMapper.selectCountByMap(requestMap);
            json.put("total", totalCount);
            requestMap.put("status", 0);
            Integer waitAudit = materialInfoMapper.selectCountByMap(requestMap);
            json.put("waitAudit", waitAudit);
            requestMap.put("status", 1);
            Integer passAudit = materialInfoMapper.selectCountByMap(requestMap);
            json.put("passAudit", passAudit);
            requestMap.put("status", 2);
            Integer refuseAudit = materialInfoMapper.selectCountByMap(requestMap);
            json.put("refuseAudit", refuseAudit);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    @Override
    public void getFile(MaterialInfo materialInfo) {
        uploadExecutorService.submit(new Runnable() {
            @Override
            public void run() {
                log.info("获取素材基本信息，code:{}", materialInfo.getCode());
                if (!Check.isNull(materialInfo)) {
                    long l = System.currentTimeMillis();
                    String url = materialInfo.getUrl();
                    log.info("replaceUrl:{}", url);
                    String localUrl = null;
                    it.sauronsoftware.jave.MultimediaInfo m = null;
                    FileInputStream fis = null;
                    try {
                        localUrl = LoadFileUtil.downLoadFromUrl(url, downloadUrl);
                        File file = new File(localUrl);
                        it.sauronsoftware.jave.Encoder encoder = new Encoder();
                        m = encoder.getInfo(file);
                        long duration = m.getDuration();
                        long secondDuration = duration / 1000;
                        MaterialParameter materialParameter = new MaterialParameter();
                        materialParameter.setMaterialId(materialInfo.getCode());
                        // 视频秒数
                        materialParameter.setSecond(secondDuration);
                        // 视频格式
                        materialParameter.setFormat(m.getFormat());
                        // 视频宽
                        String width = String.valueOf(m.getVideo().getSize().getWidth());
                        materialParameter.setWidth(width);
                        // 视频高
                        String height = String.valueOf(m.getVideo().getSize().getHeight());
                        materialParameter.setHeight(height);

                        fis = new FileInputStream(file);
                        FileChannel fc = fis.getChannel();
                        BigDecimal fileSize = new BigDecimal(fc.size());
                        String size = fileSize.divide(new BigDecimal(1048576), 2, RoundingMode.HALF_UP) + "MB";
                        materialParameter.setSize(size);
                        materialParameter.setUpdateTime(new Date());

                        Map<String, Object> deleteMap = new HashMap<>();
                        deleteMap.put("material_id", materialInfo.getId());
                        materialParameterMapper.deleteByMap(deleteMap);
                        int insert = materialParameterMapper.insert(materialParameter);
                        if (insert > 0) {
                            log.info("素材基本信息入库完成，用时：{} s", (System.currentTimeMillis() - l) / 1000);
                        }
                        // 默认抽帧 素造供应商
                        Long templateId = MaterialSupplierEnum.getTemplateIdBySize(Integer.valueOf(width), Integer.valueOf(height));
                        if (!Check.isNull(templateId)) {
                            Thread thread = new Thread() {
                                @Override
                                public void run() {
                                    watermarkVideoBySupplierCode(materialInfo.getCode(), materialInfo.getUrl(), templateId);
                                }
                            };
                            thread.start();
                        }
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (EncoderException e) {
                        e.printStackTrace();

                    } finally {
                        try {
                            if (fis != null) {
                                fis.close();
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }


        });
    }


    @Override
    public void setExcellent(String code, Integer excellent) {
        MaterialInfo info = this.getMaterialInfoByCode(code);
        info.setExcellent(excellent);
        this.updateById(info);
    }

    @Override
    public Integer getKuaishouUpVideoCount(String code) {
        return materialInfoMapper.getKuaishouUpVideoCount(code);
    }

    @Override
    public Integer getToutiaoUpVideoCount(String code) {
        return materialInfoMapper.getToutiaoUpVideoCount(code);
    }


    @Autowired
    private IMaterialImageInfoService materialImageInfoService;
    @Autowired
    private IProjectService projectService;

    /**
     * 素材库关联上传素材 1
     *
     * @param json
     * @return
     */
    @Override
    public Map<String, Object> correlationUpload(JSONObject json) {
        String userId = json.getString("userId");
        Map<String, Object> resultMap = new HashMap<>();
        try {
            String type = json.getString("type");
            String url = "";
            if (!Check.isNull(json.getString("url"))) {
                url = "https:" + json.getString("url");
            }
            MaterialInfo info = new MaterialInfo();
            Long projectId = json.getLong("projectId");
            Project project = projectService.getById(projectId);
            Long productId = project.getProductId();
            String code = json.getString("code");
            info.setId(UUID.randomUUID().toString().replace("-", ""));
            info.setCode(code);
            if (!Check.isNull(json.getString("watermarkUrl"))) {
                info.setWatermarkUrl(json.getString("watermarkUrl"));
            }
            info.setUrl(url);
            info.setUserId(userId);
            info.setProjectId(projectId);
            info.setProductId(productId);
            info.setWatermarkCode(json.getString("watermarkCode"));
            info.setStatus(0);
            info.setMaterialName(StringUtils.getFileNameNoEx(json.getString("materialName")));
            info.setWatermarkMaterialName(json.getString("watermarkMaterialName"));
            info.setMaterialDescribe(json.getString("materialDescribe"));
            info.setCreateTime(new Date());
            info.setUpdateTime(new Date());
            info.setType(type);
            //TODO 此处逻辑待调整
            //      Project project = projectService.getById(projectId);
            if (!Check.isNull(project)) {
                if (!Check.isNull(project.getSupplierCode())) {
                    info.setSupplierCode(project.getSupplierCode());
                }
            }
            MaterialCutFrame cutFrame = materialCutFrameService.getCutFrameByCode(code);
            if (Check.isNull(cutFrame)) {
                String videoUrl = URLDecoder.decode(info.getUrl()).replace("https://media-1301855440.cos.ap-chongqing.myqcloud.com/", "");
                String loadImage = "cutFrame/" + code + "/zero.jpg";
                String coverUrl = CloudVideoProcessUtil.videoCutPictureHandle(videoUrl, loadImage);
                info.setCoverUrl(coverUrl);
                Thread thread = new Thread() {
                    @Override
                    public void run() {
                        try {
                            log.info("开始抽帧,code:{}", code);
                            materialCutFrameService.getTencentCutFrame(videoUrl, code, coverUrl);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                };
                thread.start();
            } else {
                info.setCoverUrl(cutFrame.getUrl());
            }
            this.save(info);
            JSONArray imageArr = json.getJSONArray("imageArr");
            if (!Check.isNull(imageArr)) {
                JSONObject imageJson = new JSONObject();
                imageJson.put("videoId", info.getCode());
                imageJson.put("userId", userId);
                imageJson.put("imageArr", imageArr);
                materialImageInfoService.insertImage(imageJson);
            }
            Map<String, Object> deleteMap = new HashMap<>();
            deleteMap.put("material_id", info.getCode());
            JSONObject ascription = json.getJSONObject("ascription");
            if (!Check.isNull(ascription)) {
                MaterialAscription materialAscription = new MaterialAscription();
                materialAscription.setMaterialId(info.getCode());
                String clipId = ascription.getString("clipId");
                if (null != clipId && !"".equals(clipId.trim())) {
                    materialAscription.setClipId(clipId);
                }
                materialAscription.setShotId(ascription.getString("shotId"));
                materialAscription.setPlanId(ascription.getString("planId"));
                materialAscription.setPlaneId(ascription.getString("planeId"));
                materialAscription.setCode(info.getCode());
                materialAscriptionMapper.deleteByMap(deleteMap);
                int result = materialAscriptionMapper.insert(materialAscription);
                if (result > 0) {
                    log.info("素材归属信息入库完成，MaterialId:{}", info.getId());
                }
            }
            materialTagInfoService.deleteByCode(code);
            JSONArray modalityTagList = json.getJSONArray("modalityTagList");
            insertTagList(code, userId, modalityTagList);
            JSONArray contentTagList = json.getJSONArray("contentTagList");
            insertTagList(code, userId, contentTagList);
            JSONArray senceTagList = json.getJSONArray("senceTagList");
            insertTagList(code, userId, senceTagList);
            JSONArray modTagList = json.getJSONArray("modTagList");
            insertTagList(code, userId, modTagList);
            getFile(info);
            ResultMapUtils.setResultMap(resultMap, StatusCode.COMMON_SUCCESS.getCode());
        } catch (Exception e) {
            ResultMapUtils.setResultMap(resultMap, StatusCode.MATERIAL_UPLOAD_FAIL.getCode());
            e.printStackTrace();
        }
        return resultMap;
    }

    @Override
    public String platformUploadVideo(JSONObject json) {
        String userId = ((LoginUser) SecurityUtils.getSubject().getPrincipal()).getId();
        MaterialInfo info = new MaterialInfo();
        String type = json.getString("type");
        info.setType(type);
        String url = "";
        if (!Check.isNull(json.getString("url"))) {
            url = "https:" + json.getString("url");

        }
//        Long projectId = json.getLong("projectId");
        Long productId = json.getLong("productId");
        String code = json.getString("code");
        info.setCode(code);
        String id = code + "_" + productId;
        info.setId(id);
        if (!Check.isNull(json.getString("watermarkUrl"))) {
            info.setWatermarkUrl(json.getString("watermarkUrl"));
        }
        info.setUrl(url);
        info.setUserId(userId);
        info.setProductId(productId);
        info.setWatermarkCode(json.getString("watermarkCode"));
        info.setStatus(0);
        info.setMaterialName(json.getString("materialName"));
        info.setWatermarkMaterialName(json.getString("watermarkMaterialName"));
        info.setMaterialDescribe(json.getString("materialDescribe"));
        //TODO 此处逻辑待调整
//        Project project = projectService.getById(projectId);
//        if (!Check.isNull(project)) {
//            if (!Check.isNull(project.getSupplierCode())) {
//                info.setSupplierCode(project.getSupplierCode());
//            }
//        }
        MaterialCutFrame cutFrame = materialCutFrameService.getCutFrameByCode(code);
        if (Check.isNull(cutFrame)) {
            String videoUrl = URLDecoder.decode(info.getUrl()).replace("https://media-1301855440.cos.ap-chongqing.myqcloud.com/", "");
            String loadImage = "cutFrame/" + code + "/zero.jpg";
            String coverUrl = CloudVideoProcessUtil.videoCutPictureHandle(videoUrl, loadImage);
            info.setCoverUrl(coverUrl);
            Thread thread = new Thread() {
                @Override
                public void run() {
                    try {
                        log.info("开始抽帧,code:{}", code);
                        materialCutFrameService.getTencentCutFrame(videoUrl, code, coverUrl);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };
            thread.start();
        } else {
            info.setCoverUrl(cutFrame.getUrl());
        }
        this.save(info);
        JSONArray imageArr = json.getJSONArray("imageArr");
        if (!Check.isNull(imageArr)) {
            JSONObject imageJson = new JSONObject();
            imageJson.put("videoId", info.getCode());
            imageJson.put("userId", userId);
            imageJson.put("imageArr", imageArr);
            materialImageInfoService.insertImage(imageJson);
        }
        Map<String, Object> deleteMap = new HashMap<>();
        deleteMap.put("material_id", info.getCode());
        JSONObject ascription = json.getJSONObject("ascription");
        if (!Check.isNull(ascription)) {
            MaterialAscription materialAscription = new MaterialAscription();
            materialAscription.setMaterialId(info.getCode());
            materialAscription.setClipId(ascription.getString("clipId"));
            materialAscription.setShotId(ascription.getString("shotId"));
            materialAscription.setPlanId(ascription.getString("planId"));
            materialAscription.setPlaneId(ascription.getString("planeId"));
            materialAscriptionMapper.deleteByMap(deleteMap);
            int result = materialAscriptionMapper.insert(materialAscription);
            if (result > 0) {
                log.info("素材归属信息入库完成，MaterialId:{}", info.getId());
            }
        }
        materialTagInfoService.deleteByCode(code);
        JSONArray modalityTagList = json.getJSONArray("modalityTagList");
        insertTagList(code, userId, modalityTagList);
        JSONArray contentTagList = json.getJSONArray("contentTagList");
        insertTagList(code, userId, contentTagList);
        JSONArray senceTagList = json.getJSONArray("senceTagList");
        insertTagList(code, userId, senceTagList);
        JSONArray modTagList = json.getJSONArray("modTagList");
        insertTagList(code, userId, modTagList);
        getFile(info);

        return id;
    }


    private void insertTagList(String code, String userId, JSONArray tagList) {
        if (null != tagList && !tagList.isEmpty()) {
            for (int m = 0; m < tagList.size(); m++) {
                Long tagId = tagList.getLong(m);
                TagInfo tagInfo = tagInfoService.getById(tagId);
                MaterialTagInfo setTag = new MaterialTagInfo(code, tagInfo, userId);
                setTag.setCategoryId(tagInfo.getTagCategoryId());
                materialTagInfoService.save(setTag);
            }
        }
    }

    @Autowired
    private ITagInfoService tagInfoService;
    @Autowired
    private IMaterialTagInfoService materialTagInfoService;

    @Override
    public Map<String, Object> insertImage(JSONObject imageJson) {
        Map<String, Object> resultMap = new HashMap<>();
        ResultMapUtils.setResultMap(resultMap, StatusCode.COMMON_SUCCESS.getCode());
        try {
            materialImageInfoService.insertImage(imageJson);
        } catch (Exception e) {
            ResultMapUtils.setResultMap(resultMap, StatusCode.MATERIAL_UPLOAD_FAIL.getCode());
            e.printStackTrace();
        }

        return resultMap;
    }

    @Override
    public List<String> getEffiCode() {
        return materialInfoMapper.getEffiSignature();
    }


    @Override
    public List<MaterialInfo> effiMaterialInfo() {
        List<MaterialInfo> materialInfoList = new ArrayList<>();
        List<String> effiSignatureList = materialInfoMapper.getEffiSignature();
        for (String code : effiSignatureList) {
            MaterialInfo materialInfo = materialInfoMapper.getMaterialInfoByCode(code);
            if (materialInfo == null) {
                continue;
            }
            //判断是否已经同步到快手平台
            Integer kuaishouMaterialUpCount = materialInfoMapper.getKuaishouUpVideoCount(code);
            if (kuaishouMaterialUpCount > 0) {
                materialInfo.setKuaishouVideoIsUp(1);
            } else {
                materialInfo.setKuaishouVideoIsUp(0);
            }
            //判断是否已经同步到抖音平台
            Integer toutiaoMaterialUpCount = materialInfoMapper.getToutiaoUpVideoCount(code);
            if (toutiaoMaterialUpCount > 0) {
                materialInfo.setToutiaoVideoIsUp(1);
            } else {
                materialInfo.setToutiaoVideoIsUp(0);
            }
            materialInfoList.add(materialInfo);
        }

        return materialInfoList;
    }

    @Override
    public List<MaterialInfo> getListByDate(String startDate, String endDate) {
        return materialInfoMapper.getListByDate(startDate, endDate);
    }


    @Override
    public Map<String, Object> getListByParams(String tagCode, String type, Integer status, String materialName, List<Long> projectIds, String code, String startDate, String endDate, String userId, String clipId, String shotId, String planId, Integer offlineFlag, Integer pageNo, Integer pageSize) {
        Map<String, Object> result = new HashMap<>();
        PageHelper.startPage(pageNo, pageSize);

        String ascription = null;
        if (!Check.isNull(clipId) || !Check.isNull(shotId) || !Check.isNull(planId)) {
            ascription = "true";
        }

        if (!Check.isNull(startDate)) {
            startDate = startDate + " 00:00:01";
        }

        if (!Check.isNull(endDate)) {
            endDate = endDate + " 23:59:59";
        }

        List<MaterialInfo> dailyList = materialInfoMapper.getListByParams(tagCode, type, status, materialName, code, startDate, endDate, userId, projectIds, ascription, clipId, shotId, planId, offlineFlag);
        List<MaterialInfo> setList = new ArrayList<>();
        PageInfo<MaterialInfo> pageInfo = new PageInfo<>(dailyList);
        if (null != dailyList && !dailyList.isEmpty()) {
            for (MaterialInfo info : dailyList) {
                MaterialInfo materialInfo = materialInfoMapper.selectById(info.getId());
                materialInfo.setSlogansCount(info.getSlogansCount());
                materialInfo.setOfflineFlag(info.getOfflineFlag());
                materialInfo.setConfirmTime(info.getConfirmTime());
                //素材名称为空 则使用素材id 同步失败
                materialInfo.setMaterialName(Check.isNull(materialInfo.getMaterialName()) ? materialInfo.getId() : materialInfo.getMaterialName());
                //判断是否已经同步到快手平台
                Integer kuaishouMaterialUpCount = this.getKuaishouUpVideoCount(info.getCode());
                if (kuaishouMaterialUpCount > 0) {
                    materialInfo.setKuaishouVideoIsUp(1);
                } else {
                    materialInfo.setKuaishouVideoIsUp(0);
                }
                //判断是否已经同步到抖音平台
                Integer toutiaoMaterialUpCount = this.getToutiaoUpVideoCount(info.getCode());
                if (toutiaoMaterialUpCount > 0) {
                    materialInfo.setToutiaoVideoIsUp(1);
                } else {
                    materialInfo.setToutiaoVideoIsUp(0);
                }
                //统计快手总消耗数据
                JSONObject kuaishous = materialParameterMapper.getMaterialTotalCharge(info.getCode());
                if (!Check.isNull(kuaishous)) {
                    materialInfo.setCost(kuaishous.getBigDecimal("charges"));
                } else {
                    materialInfo.setCost(new BigDecimal(0));
                }
                //统计抖音总消耗数据
                JSONObject bytedances = materialParameterMapper.getByteDanceMaterialTotalCharge(info.getCode());
                if (!Check.isNull(bytedances)) {
                    materialInfo.setBytedanceCost(bytedances.getBigDecimal("charges"));
                } else {
                    materialInfo.setBytedanceCost(new BigDecimal(0));
                }
                Project project = projectService.getById(info.getProjectId());
                if (!Check.isNull(project)) {
                    materialInfo.setMediaId(project.getMediaId());
                    materialInfo.setProjectName(project.getProjectName());
                }
                QueryWrapper<MaterialImageInfo> imageInfoQueryWrapper = new QueryWrapper<>();
                imageInfoQueryWrapper.eq("video_id", info.getCode());
                imageInfoQueryWrapper.eq("status", 0);
                List<MaterialImageInfo> imageInfoList = materialImageInfoService.list(imageInfoQueryWrapper);
                if (Check.isNull(imageInfoList)) {
                    materialInfo.setWhetherUnaudited(false);
                } else {
                    materialInfo.setWhetherUnaudited(true);
                }
                //统计广告语数量
//                List<BytedanceVideoSlogenInfo> slogenInfos = slogenInfoService.listByParams(materialInfo.getCode(), 1);
//                JSONArray slogenArray = new JSONArray();
//                if (null != slogenInfos && !slogenInfos.isEmpty()) {
//                    slogenArray.addAll(slogenInfos);
//                }
//                materialInfo.setSlogans(slogenArray);
                setList.add(materialInfo);
            }
        }
        pageInfo.setList(setList);
        result.put("data", pageInfo);
        ResultMapUtils.setResultMap(result, StatusCode.COMMON_SUCCESS);
        return result;
    }

    @Override
    public List<String> getCodeList(String date) {
        return materialInfoMapper.getCodeList(date);
    }

    @Override
    public Integer getCountByCode(String s) {
        return materialInfoMapper.getCountByCode(s);
    }

    @Override
    public void updateByCode(String s) {
        materialInfoMapper.updateByCode(s);
    }

    @Override
    public List<String> getBytedanceCodeList(String date) {
        return materialInfoMapper.getBytedanceCodeList(date);
    }

    @Override
    public Integer getBytedanceCountByCode(String s) {
        return materialInfoMapper.getBytedanceCountByCode(s);
    }

    @Override
    public void updateByteDanceByCode(String s) {
        materialInfoMapper.updateByteDanceByCode(s);
    }

    @Override
    public List<String> getDuxiaomanMaterialInfoByStatus(Integer status) {
        return baseMapper.getDuxiaomanMaterialInfoByStatus(status);
    }

    @Override
    public List<String> getDuxiaomanMaterialInfoByTime() {
        return baseMapper.getDuxiaomanMaterialInfoByTime();
    }

    @Override
    public JSONArray getIdListByProject(Long projectId) {
        return materialInfoMapper.getIdListByProject(projectId);
    }


}





