package com.xhkjedu.sstudy.service.resource;

import com.alibaba.fastjson.JSON;
import com.xhkjedu.sstudy.mapper.resource.ResourceCollectMapper;
import com.xhkjedu.sstudy.mapper.resource.ResourceDirectorMapper;
import com.xhkjedu.sstudy.mapper.resource.ResourceFileMapper;
import com.xhkjedu.sstudy.mapper.resource.ResourceMapper;
import com.xhkjedu.sstudy.mapper.subjectbook.SubjectBookMapper;
import com.xhkjedu.sstudy.model.resource.TResource;
import com.xhkjedu.sstudy.model.resource.TResourceCollect;
import com.xhkjedu.sstudy.model.resource.TResourceDirector;
import com.xhkjedu.sstudy.model.resource.TResourceFile;
import com.xhkjedu.sstudy.model.subjectbook.TSubjectBook;
import com.xhkjedu.sstudy.utils.ConvertUtil;
import com.xhkjedu.sstudy.utils.StudyUtil;
import com.xhkjedu.utils.N_Utils;
import com.xhkjedu.sstudy.vo.resource.ResourceCollectVo;
import com.xhkjedu.sstudy.vo.resource.ResourceVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ywx
 * @classname ResourceService
 * @description 
 * @date 2020/6/5 9:50
 **/
@Service
public class ResourceService {
    @Resource
    private ResourceMapper resourceMapper;
    @Resource
    private ResourceCollectMapper resourceCollectMapper;
    @Resource
    private ResourceDirectorMapper resourceDirectorMapper;
    @Resource
    private SubjectBookMapper subjectBookMapper;
    @Resource
    private ResourceFileMapper resourceFileMapper;
    @Autowired
    private ConvertUtil convertUtil;

    //添加
    @Transactional
    public String save(TResource model) {
        model.setReadcount(0);
        model.setDowncount(0);
        model.setResourcestate(1);
        model.setCreatetime(N_Utils.getSecondTimestamp());
        String directorid = model.getDirectorid();
        if (directorid != null && (directorid.equals("0") || directorid.equals(""))) {
            model.setDirectorid(null);
        }
        String resourceid = StudyUtil.getId();
        model.setResourceid(resourceid);
        if (N_Utils.isEmpty(model.getSubjectid())) {//科目为空根据教材id取科目
            TSubjectBook book = subjectBookMapper.selectByPrimaryKey(model.getLsbid());
            model.setSubjectid(book.getSubjectid());
        }

        List<TResourceFile> ziplist = new ArrayList<>();
        if(model.getResourceclass()==7 && model.getCosttime()!=null && model.getCosttime()==7){
            ziplist = JSON.parseArray(model.getPdfurl(),TResourceFile.class);
            for(TResourceFile rf : ziplist){
                rf.setResourceid(resourceid);
            }

            model.setPdfurl(null);
        }

        Integer resourceclass = model.getResourceclass();
        if (resourceclass == 3 || resourceclass == 4 || resourceclass == 6) {
            model.setConverted(1);
        } else if (resourceclass == 5 && (model.getSuffix().equals("flv") || model.getMp4code().equals("h264"))) {
            model.setConverted(1);
        }
        resourceMapper.insertSelective(model);//保存资源

        List<TResourceDirector> directors = model.getDirectors();
        if(N_Utils.isListEmpty(directors)){//兼容以前添加单个章节模式
            directors = new ArrayList<>();
            TResourceDirector rd = new TResourceDirector();
            rd.setLsbid(model.getLsbid());
            rd.setDirectorid(model.getDirectorid());
            directors.add(rd);
        }
        for(TResourceDirector rd : directors){
            rd.setRdid(StudyUtil.getId());
            rd.setResourceid(resourceid);
            rd.setCreateid(model.getCreateid());
            rd.setCreatetime(model.getCreatetime());
        }

        //如果是分享的压缩包并且已经解压
        if(model.getResourceclass()==7 && model.getCosttime()!=null && model.getCosttime()==7 && ziplist!=null && ziplist.size()>0){
            resourceFileMapper.insertList(ziplist);//批量保存压缩文件的集合
        }

        resourceDirectorMapper.batchSave(directors);//保存资源教材章节关系

        convertUtil.convertResource(model);
        return resourceid;
    }

    //删除
    public Integer deleteById(String resourceid) {
        return resourceMapper.deleteById(resourceid);
    }

    //修改
    public Integer update(TResource model) {
        return resourceMapper.updateByPrimaryKeySelective(model);
    }

    //获取详情
    public ResourceVo findById(String resourceid) {
        ResourceVo resource = resourceMapper.findById(resourceid);
        convertUtil.getResourceUrl(resource);
        if (resource.getConverted().equals(1)) updateReadCount(resourceid);
        return resource;
    }
    //获取预览地址
    public String getResourceUrl(String resourceid) {
        ResourceVo resource = resourceMapper.findById2(resourceid);
        Integer resourceclass = resource.getResourceclass();
        if (resourceclass == 1 || resourceclass == 2 || resourceclass == 7 || resourceclass == 5) {
            convertUtil.getResourceUrl(resource);
            return resource.getPdfurl();
        } else {
            return resource.getResourceurl();
        }
    }

    //保存资源附件
    public void saveFiles(String resourceid, List<TResourceFile> files) {
        if (N_Utils.isListNotEmpty(files)) {
            files.forEach(f -> f.setResourceid(resourceid));
            resourceFileMapper.insertList(files);
        }
    }

    //获取列表
    public List <TResource> findAll(TResource tResource) {
        return resourceMapper.findAll(tResource);
    }

    //分享
    public String share(TResource model) {
        String resourceid = model.getResourceid();

        //判断该资源是否已经分享过该章节，如果已经分享过直接返回
        Integer count = resourceMapper.getLevelResourceForxb(model);
        if(count>0){
            return "99";
        }else{
            return saveShare(model, resourceid);
        }
    }

    /**
     * 分享资源保存
     * @Param [model, resourceid]
     * @Author ywx
     * @Date 2020/7/1 10:18
     * @return java.lang.Integer
     **/
    private String saveShare(TResource model, String resourceid) {
        if (N_Utils.isNotEmpty(resourceid)) {
            ResourceVo r = findById(resourceid);
            model.setResourcename(r.getResourcename());
            model.setResourceclass(r.getResourceclass());
            model.setResourceurl(r.getResourceurl());
            model.setSuffix(r.getSuffix());
            model.setResourcesize(r.getResourcesize());
            model.setResourcecover(r.getResourcecover());
            model.setConverted(r.getConverted());
            model.setPdfurl(r.getPdfurl());
            model.setComm(r.getComm());
            model.setDuration(r.getDuration());
            model.setMp4code(r.getMp4code());
            if(model.getLevel()==1){
                model.setBelong(3);
            }else{
                model.setBelong(r.getBelong());
            }

            if (model.getResourcetype() == null) {
                model.setResourcetype(r.getResourcetype());
            }

            if(r.getResourceclass()==7 && N_Utils.isNotEmpty(r.getPdfurl())){
                //压缩包，用costtime替代分享时的压缩包，设置为7
                model.setCosttime(7);
            }
        }
        return save(model);
    }

    //更新下载次数
    public void updateDownCount(String resourceid) {
        resourceMapper.updateDownCount(resourceid);
    }

    //学生同步视频资源列表
    public List<TResource> studentVideoList(TResource tResource) {
        return resourceMapper.studentVideoList(tResource);
    }

    /**
     * 更新阅读次数
     * @Param [resourceid]
     * @Author ywx
     * @Date 2020/7/2 14:33
     * @return java.lang.Integer
     **/
    public Integer updateReadCount(String resourceid) {
        return resourceMapper.updateReadCount(resourceid);
    }

    /**
     * 教师备课、预习导学资源列表
     * @Param [resource]
     * @Author ywx
     * @Date 2020/7/9 11:45
     * @return java.util.List<com.xhkjedu.model.resource.TResource>
     **/
    public List<TResource> listMyResource(TResource resource) {
        return resourceMapper.listMyResource(resource);
    }

    /**
     * 资源收藏
     * @Param [collect]
     * @Author ywx
     * @Date 2020/8/18 15:47
     * @return java.lang.Integer
     **/
    public Integer saveCollect(TResourceCollect collect) {
        collect.setCreatetime(N_Utils.getSecondTimestamp());
        resourceCollectMapper.insertUseGeneratedKeys(collect);
        return collect.getId();
    }

    /**
     * 资源取消收藏
     * @Param [collect]
     * @Author ywx
     * @Date 2020/8/18 15:52
     * @return void
     **/
    public void cancelCollect(TResourceCollect collect) {
        resourceCollectMapper.cancelCollect(collect);
    }

    /**
     * 获取资源是否收藏列表
     * @Param [resourceids]
     * @Author ywx
     * @Date 2020/8/18 16:20
     * @return java.util.List<com.xhkjedu.vo.resource.ResourceCollectVo>
     **/
    public List<ResourceCollectVo> listCollect(List<String> resourceids, Integer userid) {
        List<String> resourceIds = resourceCollectMapper.listCollect(resourceids, userid);
        List<ResourceCollectVo> list = new ArrayList<>();
        for (String resourceid : resourceids) {
            ResourceCollectVo rc = new ResourceCollectVo();
            rc.setResourceid(resourceid);
            Integer collected = 0;
            if (N_Utils.strInList(resourceid, resourceIds)){
                collected = 1;
            }
            rc.setCollected(collected);
            list.add(rc);
        }
        return list;
    }

    //资源是否收藏
    public Integer isCollected(String resourceid, Integer userid){
        return resourceCollectMapper.isCollected(resourceid, userid);
    }

    //////////////////////////////////////////////学生WEB端//////////////////////////////////////////////


    /**
     * 同步视频列表
     * @Param [resource]
     * @Author ywx
     * @Date 2020/9/3 17:45
     * @return java.util.List<com.xhkjedu.model.resource.TResource>
     **/
    public List<TResource> studentVideoWebList(TResource resource) {
        return resourceMapper.studentVideoWebList(resource);
    }

    //转换pdf
    public void convert(String resourceid, String pdfurl) {
        resourceMapper.convert(resourceid, pdfurl);
    }


    public ResourceVo findById2(String resourceid) {
        return resourceMapper.findById2(resourceid);
    }

    /**
     * 批量保存
     * @Param [resources]
     * @Author ywx
     * @Date 2022/3/14 11:28
     * @return void
     **/
    public void batchAdd(List<TResource> resources) {
        for (TResource resource : resources) {
            save(resource);
        }
    }
}
