package com.ruixuan.jiaoyang.service.impl;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruixuan.common.core.domain.ResultResponse;
import com.ruixuan.common.utils.Check;
import com.ruixuan.common.utils.DateUtils;
import com.ruixuan.data.service.VideoTextService;
import com.ruixuan.jiaoyang.entity.JyMaterialList;
import com.ruixuan.jiaoyang.mapper.JyMaterialListMapper;

import com.ruixuan.jiaoyang.service.ICloudVideoProcessService;
import com.ruixuan.jiaoyang.service.IJyMaterialListService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * 素材信息Service业务层处理
 *
 * @author ruoyi
 * @date 2023-11-16
 */
@Slf4j
@Service
public class JyMaterialListServiceImpl implements IJyMaterialListService {
    @Autowired
    private JyMaterialListMapper jyMaterialListMapper;
    @Autowired
    private ICloudVideoProcessService cloudVideoProcessService;
    @Autowired
    private VideoTextService videoTextService;
    private static ExecutorService uploadExecutorService = Executors.newFixedThreadPool(5);
    private static List<JSONObject> keyList = new ArrayList<>();

    /**
     * 查询素材信息
     *
     * @param id 素材信息主键
     * @return 素材信息
     */
    @Override
    public JyMaterialList selectJyMaterialListById(Long id) {
        return jyMaterialListMapper.selectJyMaterialListById(id);
    }

    /**
     * 查询素材信息列表
     *
     * @param jyMaterialList 素材信息
     * @return 素材信息
     */
    @Override
    public PageInfo<JyMaterialList> selectJyMaterialListList(JyMaterialList jyMaterialList) {
        PageHelper.startPage(jyMaterialList.getPageNum(), jyMaterialList.getPageSize());
        List<JyMaterialList> jyMaterialLists = jyMaterialListMapper.selectJyMaterialListList(jyMaterialList);
        PageInfo<JyMaterialList> pageInfo = new PageInfo<>(jyMaterialLists);
        return pageInfo;
    }

    @Override
    public PageInfo<JSONObject> getKeyWordList(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<JSONObject> list = jyMaterialListMapper.getKeyWordList();
        PageInfo<JSONObject> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }


    /**
     * 新增素材信息
     *
     * @param jyMaterialList 素材信息
     * @return 结果
     */
    @Override
    public int insertJyMaterialList(JyMaterialList jyMaterialList) {
        jyMaterialList.setCreateTime(DateUtils.getNowDate());
        return jyMaterialListMapper.insertJyMaterialList(jyMaterialList);
    }

    /**
     * 修改素材信息
     *
     * @param jyMaterialList 素材信息
     * @return 结果
     */
    @Override
    public int updateJyMaterialList(JyMaterialList jyMaterialList) {
        jyMaterialList.setUpdateTime(DateUtils.getNowDate());
        return jyMaterialListMapper.updateJyMaterialList(jyMaterialList);
    }

    /**
     * 批量删除素材信息
     *
     * @param ids 需要删除的素材信息主键
     * @return 结果
     */
    @Override
    public int deleteJyMaterialListByIds(Long[] ids) {
        return jyMaterialListMapper.deleteJyMaterialListByIds(ids);
    }

    /**
     * 删除素材信息信息
     *
     * @param id 素材信息主键
     * @return 结果
     */
    @Override
    public int deleteJyMaterialListById(Long id) {
        return jyMaterialListMapper.deleteJyMaterialListById(id);
    }

    @Override
    public Integer checkMaterial(String signature) {
        return jyMaterialListMapper.checkMaterial(signature);
    }

    @Override
    public void addMaterials(Long userId, String userName, JSONArray materialList) {
        for (int i = 0; i < materialList.size(); i++) {
            JSONObject jsonObject = materialList.getJSONObject(i);
            String signature = jsonObject.getString("signature");
            Integer count = jyMaterialListMapper.checkMaterial(signature);
            if (count > 0) {
                continue;
            }
            String materialUrl = jsonObject.getString("materialUrl");
            String url = "";
            if (!Check.isNull(materialUrl) && !materialUrl.contains("https:")) {
                url = "https:" + materialUrl;
            } else {
                url = materialUrl;
            }
            String materialName = jsonObject.getString("materialName");
            String videoUrl = URLDecoder.decode(url.replace("https://live-1301855440.cos.ap-chongqing.myqcloud.com/", ""));//  System.err.println(videoUrl);
            String loadImage = "screenshot/" + signature + "/zero.jpg";
            String coverUrl = cloudVideoProcessService.videoCutPictureHandle(videoUrl, loadImage);
            JyMaterialList material = new JyMaterialList();
            material.setSignature(signature);
            material.setMaterialName(getFileNameNoEx(materialName));
            material.setMaterialUrl(url);
            material.setCoverUrl(coverUrl);
            material.setMaterialStatus(1);
            material.setUserId(userId);
            material.setUserName(userName);
            jyMaterialListMapper.insertJyMaterialList(material);
            this.checkText(signature, url);
        }
    }


    @Override
    public void insertKeyWord(String type, String keyWord) {
        jyMaterialListMapper.insertKeyWord(type, keyWord);
        keyList = new ArrayList<>();
        getKeyList();
    }

    private void checkText(String signature, String videoUrl) {
        uploadExecutorService.submit(new Runnable() {
            @Override
            public void run() {
                JSONArray keyArray = new JSONArray();
                Integer isKey = 2; // 2 未命中 3 命中
                JyMaterialList updateMaterial = new JyMaterialList();
                String videoText = videoTextService.getVideoText(videoUrl);
                if (!Check.isNull(videoText)) {
                    if (Check.isNull(keyList)) {
                        getKeyList();
                    }
                    for (JSONObject keyJson : keyList) {
                        String keyWord = keyJson.getString("keyWord");
                        if (videoText.contains(keyWord)) {
                            isKey = 3;
                            keyArray.add(keyJson);
                        }
                    }
                    updateMaterial.setMaterialStatus(isKey);
                    updateMaterial.setMaterialText(videoText);
                    updateMaterial.setViolatingText(keyArray.toJSONString());
                    updateMaterial.setSignature(signature);
                } else {
                    updateMaterial.setMaterialStatus(isKey);
                    updateMaterial.setMaterialText(videoText);
                    updateMaterial.setViolatingText(keyArray.toJSONString());
                    updateMaterial.setSignature(signature);
                }
                jyMaterialListMapper.updateJyMaterialListBySignature(updateMaterial);
                log.info("违规词判定成功,code:{}", signature);

            }
        });
    }


    private void getKeyList() {
        keyList = jyMaterialListMapper.jyMaterialListMapper();
    }

    private String getFileNameNoEx(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length()))) {
                return filename.substring(0, dot);
            }
        }
        return filename;
    }
}

