package com.zd.exam.service.impl;

import com.zd.common.core.domain.R;
import com.zd.common.core.domain.per.PerPrefix;
import com.zd.common.core.exception.ServiceException;
import com.zd.common.core.utils.DateUtils;
import com.zd.common.core.utils.SecurityUtils;
import com.zd.common.core.utils.StringUtils;
import com.zd.common.datascope.annotation.DataScope;
import com.zd.common.security.utils.SaveUtil;
import com.zd.exam.domain.ElCourseChapter;
import com.zd.exam.domain.ElResources;
import com.zd.exam.mapper.ElCategoryMapper;
import com.zd.exam.mapper.ElCourseChapterMapper;
import com.zd.exam.mapper.ElResourcesMapper;
import com.zd.exam.service.IElResourcesService;
import com.zd.system.api.RemoteFileService;
import com.zd.system.api.domain.SysFile;
import com.zd.system.api.kkFile.RemoteKkFileService;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import ws.schild.jave.EncoderException;
import ws.schild.jave.MultimediaObject;
import ws.schild.jave.info.MultimediaInfo;

import java.net.*;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

/**
 * 课件资源Service业务层处理
 *
 * @author liubo
 * @date 2021-12-07
 */
@Service
public class ElResourcesServiceImpl implements IElResourcesService {
    private static Logger logger = LoggerFactory.getLogger(ElResourcesServiceImpl.class);
    @Autowired
    private ElResourcesMapper elResourcesMapper;
    @Autowired
    private ElCourseChapterMapper elCourseChapterMapper;
    @Autowired
    private RemoteFileService remoteFileService;
    @Autowired
    private ElCategoryMapper categoryMapper;
    @Autowired
    private RemoteKkFileService remoteKkFileService;


    /**
     * 查询课件资源
     *
     * @param id 课件资源主键
     * @return 课件资源
     */
    @Override
    public ElResources selectElResourcesById(Long id) {
        return elResourcesMapper.selectElResourcesById(id);
    }


    /**
     * 查询课件资源列表
     *
     * @param elResources 课件资源
     * @return 课件资源
     */
    @Override
    public ElResources selectElResourcesCate(ElResources elResources) {
        // 查询所有的子分类
        if(elResources.getCateId() != null){
            List<Long> cateIds = new ArrayList<>();
            cateIds.add(elResources.getCateId());

            List<Long> subIds = categoryMapper.selectIdsByParentIds(cateIds);
            if(subIds.size() > 0){
                cateIds.addAll(subIds);
                subIds = categoryMapper.selectIdsByParentIds(subIds);
                if(subIds.size() > 0){
                    cateIds.addAll(subIds);
                }
            }

            elResources.setCateIds(cateIds);
        }


        return elResources;
    }


    /**
     * 查询课件资源列表
     *
     * @param elResources 课件资源
     * @return 课件资源
     */
    @Override
    @DataScope(deptAlias = "t" , userAlias = "t" , permi = PerPrefix.EXAM_EL_RESOURCES)
    public List<ElResources> selectElResourcesList(ElResources elResources) {
//        // 查询所有的子分类
//        if(elResources.getCateId() != null){
//            List<Long> cateIds = new ArrayList<>();
//            cateIds.add(elResources.getCateId());
//
//            List<Long> subIds = categoryMapper.selectIdsByParentIds(cateIds);
//            if(subIds.size() > 0){
//                cateIds.addAll(subIds);
//                subIds = categoryMapper.selectIdsByParentIds(subIds);
//                if(subIds.size() > 0){
//                    cateIds.addAll(subIds);
//                }
//            }
//
//            elResources.setCateIds(cateIds);
//        }


        return elResourcesMapper.selectElResourcesList(elResources);
    }

    @Override
    public List<ElResources> selectElResourcesListALL() {
        return elResourcesMapper.selectElResourcesListALL();
    }

    /**
     * 新增课件资源
     *
     * @return 结果
     */
    @Override
    public ElResources insertElResources(ElResources elResources, MultipartFile file) {
        //设置其他公共字段
        saveResources(elResources, file);
        SaveUtil.setCommonAttr(elResources);
        int num = elResourcesMapper.insertElResources(elResources);
        if(num == 0){
            throw new ServiceException("添加失败！");
        }
        return elResources;
    }

    @Override
    public ElResources insertElResources(ElResources elResources) {

        if(elResources.getId() != null){
            updateElResources(elResources, 1);
        }else {
            saveResources(elResources);
            SaveUtil.setCommonAttr(elResources);
            int num = elResourcesMapper.insertElResources(elResources);

            try {
                previewKkFile(elResources.getPath());
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
            if(num == 0){
                throw new ServiceException("添加失败！");
            }
        }


        return elResources;
    }

    @Async
    public void previewKkFile(String filePath) throws URISyntaxException {
        logger.info("****调用kkFileService开始****");
        String kkFilePath=remoteKkFileService.getKkFilePath(new URI("http://127.0.0.1:8012"), URLEncoder.encode(Base64.getEncoder().encodeToString(filePath.getBytes())));
        if(StringUtils.isNotBlank(kkFilePath) && StringUtils.isNotNull(kkFilePath)){
            logger.info("！！！！调用kkFileService成功！！！！");
        }
    }


    private void saveResources(ElResources elResources, MultipartFile file){
        if(file != null){
            elResources.setTitle(file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf(".")));
            elResources.setSize(file.getSize());
            elResources.setPostfix(file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1));

            R<SysFile> fileResult = remoteFileService.upload(file);
            if (StringUtils.isNull(fileResult) || StringUtils.isNull(fileResult.getData())) {
                throw new ServiceException("文件服务异常，保存失败");
            }

            String url = fileResult.getData().getUrl();

            elResources.setPath(url);

            if(elResources.getType() == 2){

                try {
                    // 获取视频时长
                    MultimediaObject instance = new MultimediaObject(new URL(url));
                    MultimediaInfo result = instance.getInfo();
                    elResources.setDuration(result.getDuration() / 1000);
                } catch (EncoderException e) {
                    e.printStackTrace();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    private void saveResources(ElResources elResources){
        if(elResources != null){
            String filePath=elResources.getPath();
            //elResources.setTitle(filePath.substring(filePath.lastIndexOf("/")+1, filePath.lastIndexOf(".")));
            elResources.setTitle(elResources.getFileName() != null ? elResources.getFileName(): "");
            String filePrefix=filePath.substring(filePath.lastIndexOf(".") + 1);
            elResources.setPostfix(filePrefix);
            if(elResources.getType()==2){
                try {
                    // 获取视频时长
                    MultimediaObject instance = new MultimediaObject(new URL(filePath));
                    MultimediaInfo result = instance.getInfo();
                    elResources.setDuration(result.getDuration() / 1000);
                } catch (EncoderException e) {
                    e.printStackTrace();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 修改课件资源
     *
     * @param elResources 课件资源
     * @return 结果
     */
    @Override
    public int updateElResources(ElResources elResources, MultipartFile file) {
        saveResources(elResources, file);
        elResources.setUpdateTime(DateUtils.getNowDate());
        elResources.setUpdateBy(SecurityUtils.getUsername());
        return elResourcesMapper.updateElResources(elResources);
    }

    @Override
    public int updateElResources(ElResources elResources, int type) {
        if(type == 1){
            saveResources(elResources);
        }
        elResources.setUpdateTime(DateUtils.getNowDate());
        elResources.setUpdateBy(SecurityUtils.getUsername());
        try {
            elResourcesMapper.updateElResources(elResources);
            if(type == 1){
                previewKkFile(elResources.getPath());
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        return 1;
    }

    /**
     * 批量删除课件资源
     *
     * @param ids 需要删除的课件资源主键
     * @return 结果
     */
    @Override
    public int deleteElResourcesByIds(Long[] ids) {
        ElCourseChapter elCourseChapter = new ElCourseChapter();
        List<ElCourseChapter> list;
        for (Long id : ids) {
            elCourseChapter.setResourcesId(id);
            list = elCourseChapterMapper.selectElCourseChapterList(elCourseChapter);
            if(CollectionUtils.isNotEmpty(list)){
                throw new ServiceException("资源已经被使用，删除失败！");
            }
        }
        return elResourcesMapper.deleteElResourcesByIds(ids);
    }

    /**
     * 删除课件资源信息
     *
     * @param id 课件资源主键
     * @return 结果
     */
    @Override
    public int deleteElResourcesById(Long id) {
        return elResourcesMapper.deleteElResourcesById(id);
    }
}
