package com.xhkjedu.sstudy.service.resource;

import com.alibaba.fastjson.JSON;
import com.xhkjedu.exception.MissingParametersException;
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.*;
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 com.xhkjedu.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

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

    //添加
    @Transactional
    public String save(TResource model) {
        List<TResourceDirector> directors = model.getDirectors();
        String directorid = model.getDirectorid();
        if (directorid != null && (directorid.equals("0") || directorid.equals(""))) {
            model.setDirectorid(null);
        }
        if (N_Utils.isListEmpty(directors) && model.getDirectorid() == null) {
            throw new MissingParametersException("请选择章节");
        }
        model.setReadcount(0);
        model.setDowncount(0);
        model.setResourcestate(1);
        model.setCreatetime(N_Utils.getSecondTimestamp());
        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) {
            if("h264".equals(model.getMp4code())){
                model.setConverted(1);
            } else {
                model.setConverted(0);
            }
        } else {

        }
        resourceMapper.insertSelective(model);//保存资源

        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 <Map> findAll(TResource tResource) {
        List<Map> list = resourceMapper.findAll(tResource);
        Integer schoolid = tResource.getSchoolid();
        if(N_Utils.isEmptyInteger(schoolid)) return list;
        String shareqids = list.stream().filter(m -> schoolid.equals(m.get("schoolid")) && !m.get("belong").equals(10))
                               .map(m -> m.get("resourceid").toString()).collect(Collectors.joining("','"));
        List<Map<String, String>> shareList = resourceMapper.listShareNumByIds(shareqids);
        for (Map map : list) {
            setShareNum(shareList, map);
        }
        return list;
    }

    //分享
    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
     **/
    public void updateReadCount(String resourceid) {
        resourceMapper.updateReadCount(resourceid);
    }

    /**
     * 教师备课、预习导学资源列表
     * @Param [resource]
     * @Author ywx
     * @Date 2020/7/9 11:45
     * @return java.util.List<com.xhkjedu.model.resource.TResource>
     **/
    public List<Map> listMyResource(TResource resource) {
        List<Map> list = resourceMapper.listMyResource(resource);
        String shareqids = list.stream().map(m -> m.get("resourceid").toString()).collect(Collectors.joining("','"));
        List<Map<String, String>> shareList = resourceMapper.listShareNumByIds(shareqids);
        for (Map map : list) {
            setShareNum(shareList, map);
        }
        return list;
    }

    /**
     * @Description 资源是否分享过
     * @Date 2023/9/1 15:12
     * @Author YWX
     * @Param [shareList, map]
     * @Return void
     **/
    private void setShareNum(List<Map<String, String>> shareList, Map<String, Object> map) {
        Object shareqid = map.get("resourceid");
        Object sharenum = 0;
        if (N_Utils.isListNotEmpty(shareList)) {
            for (Map<String, String> s : shareList) {
                if (s.get("resourcepid").equals(shareqid)) {
                    sharenum = s.get("sharenum");
                    break;
                }
            }
        }
        map.put("sharenum", sharenum);
    }

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

    /**
     * 资源取消收藏
     * @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);
            int 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);
        }
    }

    /**
     * @Description 分享伙伴校
     * @Param [resource]
     * @Author ywx
     * @Date 2023/7/21 10:28
     * @return com.xhkjedu.vo.ResultVo
     **/
    @Transactional(rollbackFor = Exception.class)
    public ResultVo sharePartnerSchool(TResource resource) {
        List<TGuideGroup> groups = resource.getGuideGroups();
        if (N_Utils.isListEmpty(groups)) return new ResultVo(1, "伙伴校不能为空");
        String resourceid = resource.getResourceid();
        Integer createid = resource.getCreateid();
        int timestamp = N_Utils.getSecondTimestamp();
        TResource vo = resourceMapper.getResourceAndSchoolById(resourceid);
        List<Integer> schoolids = vo.getGuideGroups().stream().map(TGuideGroup::getSchoolid).collect(Collectors.toList());
        List<TResourceDirector> directors = new ArrayList<>(groups.size());
        List<Integer> schoolIds = new ArrayList<>();//已分享过的学校集合
        try {
            //2024-1-10分享到伙伴学校时同时分享到自己所在学校集团校 和 校本资源
            Integer mySchoolid = vo.getSchoolid();
            TGuideGroup myGroup = new TGuideGroup();
            myGroup.setSchoolid(mySchoolid);
            groups.add(myGroup);//分享到自己学校集团校

            resource.setSchoolid(mySchoolid);
            share(resource);//分享校本资源

            for (TGuideGroup g : groups) {
                Integer schoolid = g.getSchoolid();
                if (N_Utils.numInList(schoolid, schoolids)) {//已分享过的学校需更新试题时间
                    schoolIds.add(schoolid);
                    continue;
                }
                TResource r = new TResource();
                String id = StudyUtil.getId();
                r.setResourceid(id);
                r.setResourcename(vo.getResourcename());
                r.setSubjectid(vo.getSubjectid());
                r.setReadcount(0);
                r.setDowncount(0);
                r.setResourceclass(vo.getResourceclass());
                r.setResourcetype(resource.getResourcetype());
                r.setLevel(resource.getLevel());
                r.setResourcegrade(resource.getResourcegrade());
                r.setSource(resource.getSource());
                r.setYear(resource.getYear());
                r.setRegion(resource.getRegion());
                r.setSchoolname(resource.getSchoolname());
                r.setResourceurl(vo.getResourceurl());
                r.setResourcecover(vo.getResourcecover());
                r.setConverted(vo.getConverted());
                r.setConvertmsg(vo.getConvertmsg());
                r.setPdfurl(vo.getPdfurl());
                r.setResourcestate(1);
                r.setSuffix(vo.getSuffix());
                r.setMp4code(vo.getMp4code());
                r.setResourcesize(vo.getResourcesize());
                r.setDuration(vo.getDuration());
                r.setComm(vo.getComm());
                r.setCreateid(createid);
                r.setCreatetime(timestamp);
                r.setBelong(10);
                r.setSchoolid(schoolid);
                r.setResourcepid(resourceid);
                resourceMapper.insertSelective(r);

                TResourceDirector rd = new TResourceDirector();
                rd.setRdid(StudyUtil.getId());
                rd.setResourceid(id);
                rd.setLsbid(resource.getLsbid());
                rd.setCreateid(createid);
                rd.setCreatetime(timestamp);
                rd.setDirectorid(resource.getDirectorid());
                directors.add(rd);
            }
            if(N_Utils.isListNotEmpty(directors)) resourceDirectorMapper.batchSave(directors);
            if (N_Utils.isListNotEmpty(schoolIds)) resourceMapper.batchUpdateTime(schoolIds, resourceid, timestamp);
        } catch (Exception e) {
            log.error("分享伙伴校出错：" + e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new ResultVo(1, "分享失败");
        }
        return new ResultVo(0, "分享成功");
    }

    /**
     * @Description 获取分享的伙伴校
     * @Date 2023/8/29 14:48
     * @Author YWX
     * @Param [resourceid]
     * @Return java.util.List<java.util.Map>
     **/
    public List<Map<String, Object>> listSharePartnerSchool(String resourceid) {
        return resourceMapper.listSharePartnerSchool(resourceid);
    }

    /**
     * @Description 分享集团校
     * @Date 2023/8/29 16:33
     * @Author YWX
     * @Param [tResource]
     * @Return com.xhkjedu.vo.ResultVo
     **/
    @Transactional(rollbackFor = Exception.class)
    public ResultVo shareGroupSchool(TResource tResource) {
        List<TGuideGroup> groups = tResource.getGuideGroups();
        if (N_Utils.isListEmpty(groups)) return new ResultVo(1, "伙伴校不能为空");
        String resourcepid = tResource.getResourceid();
        Integer createid = tResource.getCreateid();
        int timestamp = N_Utils.getSecondTimestamp();
        TResource r = resourceMapper.getResourceAndSchoolById(resourcepid);
        List<Integer> schoolids = r.getGuideGroups().stream().map(TGuideGroup::getSchoolid).collect(Collectors.toList());
        List<TResourceDirector> resourceDirectors = r.getDirectors();
        List<TResourceDirector> directors = new ArrayList<>();
        List<Integer> schoolIds = new ArrayList<>();//已分享过的学校集合

        //2024-1-10分享到伙伴学校时同时分享到自己所在学校集团校 和 校本资源
        Integer mySchoolid = r.getSchoolid();
        TGuideGroup myGroup = new TGuideGroup();
        myGroup.setSchoolid(mySchoolid);
        groups.add(myGroup);//分享到自己学校集团校

        for (TGuideGroup group : groups) {
            Integer schoolid = group.getSchoolid();
            if (N_Utils.numInList(schoolid, schoolids)) {//已分享过的学校需更新资源时间
                schoolIds.add(schoolid);
                continue;
            }
            //资源
            TResource tr = new TResource();
            BeanUtils.copyProperties(r, tr);
            String resourceid = StudyUtil.getId();
            tr.setResourceid(resourceid);
            tr.setReadcount(0);
            tr.setDowncount(0);
            tr.setCreateid(createid);
            tr.setCreatetime(timestamp);
            tr.setBelong(10);
            tr.setSchoolid(schoolid);
            tr.setResourcepid(resourcepid);
            resourceMapper.insertSelective(tr);

            //资源管理章节
            for (TResourceDirector d : resourceDirectors) {
                TResourceDirector rd = new TResourceDirector();
                BeanUtils.copyProperties(d, rd);
                rd.setRdid(StudyUtil.getId());
                rd.setResourceid(resourceid);
                rd.setCreateid(createid);
                rd.setCreatetime(timestamp);
                directors.add(rd);
            }
        }
        if (N_Utils.isListNotEmpty(directors)) resourceDirectorMapper.batchSave(directors);
        if (N_Utils.isListNotEmpty(schoolIds)) resourceMapper.batchUpdateTime(schoolIds, resourcepid, timestamp);
        return new ResultVo(0, "分享成功");
    }
}
