package com.platform.modules.plm.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.platform.common.exception.RRException;
import com.platform.common.utils.ConverterUtils;
import com.platform.common.utils.FileUtils;
import com.platform.common.utils.PageUtils;
import com.platform.modules.plm.dao.PlmVideoNewsDao;
import com.platform.modules.plm.entity.PlmVideoNewsEntity;
import com.platform.modules.plm.service.PlmVideoNewsService;
import com.platform.modules.plm.util.FileCalculateUtils;
import com.platform.modules.plm.util.FileSizeUnitEnum;
import com.platform.modules.plm.util.MateriaFileProperties;
import com.platform.modules.plm.util.MaterialUtils;
import com.platform.modules.video.service.RealPathResolver;

@Service("plmVideoNewsService")
public class PlmVideoNewsServiceImpl extends ServiceImpl<PlmVideoNewsDao, PlmVideoNewsEntity> implements PlmVideoNewsService {
	
	@Autowired
	private MateriaFileProperties materiaFileProperties; 
	@Autowired
	private RealPathResolver realPathResolver;
	
	@Override
	public Map<String, Object> queryPageMap(Map<String, Object> params) {
		//检索记录
		Map<String, Object> resultMap = new HashMap<String, Object>();
		PageUtils page = queryPage(params);
		resultMap.put("totalPage", page.getTotalPage());
		resultMap.put("pageSize", page.getPageSize());
		resultMap.put("currPage", page.getCurrPage());
		resultMap.put("totalCount", page.getTotalCount());
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		if(page!=null && page.getList()!=null && page.getList().size()>0){
			for(int i=0;i<page.getList().size();i++){
				Map<String, Object> map = new HashMap<String, Object>();
				PlmVideoNewsEntity bean = (PlmVideoNewsEntity) page.getList().get(i);
				if(bean==null){
					continue;
				}
				map.put("id", bean.getId());
				map.put("title", bean.getTitle());
				map.put("status", bean.getStatus());
				map.put("duration", bean.getMaterialDuration());
				map.put("fileSize", bean.getMaterialSize());
				map.put("sources", bean.getVideoSources());
				map.put("materialUrl", MaterialUtils.getMaterialUrl(bean.getVideoUrl(), materiaFileProperties.getBasePath()));
				map.put("coverUrl", MaterialUtils.getMaterialUrl(bean.getTitleImg(), materiaFileProperties.getBasePath()));
				map.put("auditDate", bean.getAuditDate());
				map.put("auditUserName", bean.getAuditUserName());
				map.put("date", bean.getCreateDate());
				String isDelete = params.get("isDelete")==null ? null : params.get("isDelete").toString();
				if(isDelete=="1" || isDelete.equals("1")){
					map.put("deleteDate", bean.getUpdateDate());
				}
				list.add(map);
			}
		}
		resultMap.put("list", list);
		return resultMap;
	}
	
	@Override
    public PageUtils queryPage(Map<String, Object> params) {
    	//检索记录
		int current = ConverterUtils.parseInt(params.get("page"));
	    int limit = ConverterUtils.parseInt(params.get("limit"));
    	Page<Map<String, Object>> page = new Page<Map<String, Object>>(current, limit);
	    List<PlmVideoNewsEntity> pageList = this.baseMapper.queryPageMap(page, params);
	    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		if(pageList!=null && pageList.size()>0){
			for(int i=0;i<pageList.size();i++){
				Map<String, Object> map = new HashMap<String, Object>();
				PlmVideoNewsEntity bean = pageList.get(i);
				if(bean==null){
					continue;
				}
				map.put("id", bean.getId());
				map.put("title", bean.getTitle());
				map.put("status", bean.getStatus());
				map.put("duration", bean.getMaterialDuration());
				map.put("fileSize", bean.getMaterialSize());
				map.put("sources", bean.getVideoSources());
				map.put("materialUrl", MaterialUtils.getMaterialUrl(bean.getVideoUrl(), materiaFileProperties.getBasePath()));
				map.put("coverUrl", MaterialUtils.getMaterialUrl(bean.getTitleImg(), materiaFileProperties.getBasePath()));
				map.put("auditDate", bean.getAuditDate());
				map.put("auditUserName", bean.getAuditUserName());
				map.put("date", bean.getCreateDate());
				map.put("userName", bean.getCreateUserName());
				map.put("date", bean.getCreateDate());
				String isDelete = params.get("isDelete")==null ? null : params.get("isDelete").toString();
				if(isDelete=="1" || isDelete.equals("1")){
					map.put("deleteDate", bean.getUpdateDate());
					map.put("deleteUserName", bean.getUpdateUserName());
				}
				list.add(map);
			}
		}
	    page.setRecords(list);
        return new PageUtils(page);
    }
	
	@Override
    public Map<String, Object> queryById(Long id){
		if(id==null){
			return null;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		PlmVideoNewsEntity bean = this.baseMapper.queryById(id);
		if(bean==null || bean.getId()==null){
			return null;
		}
		map.put("title", bean.getTitle());
		map.put("status", bean.getStatus());
		map.put("duration", bean.getMaterialDuration());
		map.put("fileSize", bean.getMaterialSize());
		map.put("sources", bean.getVideoSources());
		map.put("description", bean.getDescription());
		map.put("materialUrl", MaterialUtils.getMaterialUrl(bean.getVideoUrl(), materiaFileProperties.getBasePath()));
		map.put("coverUrl", MaterialUtils.getMaterialUrl(bean.getTitleImg(), materiaFileProperties.getBasePath()));
		map.put("date", bean.getCreateDate());
		map.put("userName", bean.getCreateUserName());
		if(bean.getIsDelete()==1 || bean.getIsDelete().equals(1)){
			map.put("deleteDate", bean.getUpdateDate());
			map.put("deleteUserName", bean.getUpdateUserName());
		}else{
			map.put("updateDate", bean.getUpdateDate());
			map.put("updateUserName", bean.getUpdateUserName());
		}
		map.put("auditUserName", bean.getAuditUserName());
		map.put("auditDate", bean.getAuditDate());
		map.put("auditOpinion", bean.getAuditOpinion());
		return map;
	}

	@Override
	public PlmVideoNewsEntity queryByTaskId(Long taskId){
		return this.baseMapper.queryByTaskId(taskId);
	}
	
	@Override
	public void upload(MultipartFile materialFile, MultipartFile coverFile,String title,String description,Long userId){
		PlmVideoNewsEntity entity = new PlmVideoNewsEntity();
        try {
        	String newMaterialName = FileUtils.createFileName() + "." + FileUtils.getSuffix(materialFile.getOriginalFilename());
            String serverMaterialPath = materiaFileProperties.getMediaPath() + materiaFileProperties.getSPT() + MaterialUtils.getDateDir() + materiaFileProperties.getSPT() + newMaterialName;
            String newMaterialPath = realPathResolver.get(materiaFileProperties.getMateriaPath() + serverMaterialPath);
        	File file = new File(newMaterialPath);
            FileUtils.copy(materialFile.getInputStream(), newMaterialPath);
            
            entity.setTitle(title);
    		entity.setDescription(description);
    		
    		Long fileSize = MaterialUtils.getFileSize(file);
            Long playTime = MaterialUtils.getPlayTime(file);
            if(fileSize!=null){
            	entity.setMaterialSize(FileCalculateUtils.calculateFileSizeString(fileSize, FileSizeUnitEnum.MB));
            	entity.setFileSize(fileSize);
            }
            if(playTime!=null){
            	entity.setPlayTime(playTime);
            	entity.setMaterialDuration(FileCalculateUtils.calculateFilePlayTimeString(playTime));
            }
    		
        	String newCoverName = FileUtils.createFileName() + "." + FileUtils.getSuffix(coverFile.getOriginalFilename());
            String serverCoverPath = materiaFileProperties.getMediaPath() + materiaFileProperties.getSPT() + MaterialUtils.getDateDir() +materiaFileProperties.getSPT() + newCoverName;
            String newCoverPath = materiaFileProperties.getMateriaPath()+ serverCoverPath;
            FileUtils.copy(coverFile.getInputStream(), realPathResolver.get(newCoverPath));
            entity.setCreateDate(new Date());
            entity.setCreateUser(userId);
            entity.setVideoSources(2);
            entity.setTitleImg(serverCoverPath);
            entity.setVideoUrl(serverMaterialPath);
            entity.setIsDelete(0);
            entity.setStatus(2);
            this.baseMapper.save(entity);
        } catch (IOException e) {
        	throw new RRException("上传失败!");
        }
	}
	
	@Override
	public void update(Long id,MultipartFile materialFile,MultipartFile coverFile,String title,String description,Long userId){
		if(id==null){
			throw new RRException("Id不能为空!");
		}
		
        try {
        	PlmVideoNewsEntity entity = this.baseMapper.selectById(id);
        	if(entity==null){
        		throw new RRException("对象不存在!");
        	}
        	if(materialFile!=null && !materialFile.isEmpty()){
        		String newMaterialName = FileUtils.createFileName() + "." + FileUtils.getSuffix(materialFile.getOriginalFilename());
                String serverMaterialPath = materiaFileProperties.getMediaPath() + materiaFileProperties.getSPT() + MaterialUtils.getDateDir() + materiaFileProperties.getSPT() + newMaterialName;
                String newMaterialPath = materiaFileProperties.getMateriaPath() + serverMaterialPath;
            	File file = new File(realPathResolver.get(newMaterialPath));
                FileUtils.copy(materialFile.getInputStream(), newMaterialPath);
                entity.setVideoUrl(serverMaterialPath);
                
                Long fileSize = MaterialUtils.getFileSize(file);
                Long playTime = MaterialUtils.getPlayTime(file);
                if(fileSize!=null){
                	entity.setMaterialSize(FileCalculateUtils.calculateFileSizeString(fileSize, FileSizeUnitEnum.MB));
                	entity.setFileSize(fileSize);
                }
                if(playTime!=null){
                	entity.setPlayTime(playTime);
                	entity.setMaterialDuration(FileCalculateUtils.calculateFilePlayTimeString(playTime));
                }
        	}
        	if(coverFile!=null && !coverFile.isEmpty()){
        		String newCoverName = FileUtils.createFileName() + "." + FileUtils.getSuffix(coverFile.getOriginalFilename());
			 	String serverCoverPath = materiaFileProperties.getMediaPath() + materiaFileProperties.getSPT() + MaterialUtils.getDateDir() +materiaFileProperties.getSPT() + newCoverName;
			 	String newCoverPath = realPathResolver.get(materiaFileProperties.getMateriaPath() + serverCoverPath);
			 	FileUtils.copy(coverFile.getInputStream(), newCoverPath);
			 	entity.setTitleImg(newCoverPath);
        	}
        	entity.setUpdateUser(userId);
        	entity.setUpdateDate(new Date());
            entity.setTitle(title);
    		entity.setDescription(description);
            this.baseMapper.save(entity);
        } catch (IOException e) {
        	throw new RRException("修改失败!");
        }
	}
	
	@Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids,Long userId) {
		if(ids==null || ids.length==0){
			return;
		}
		for(Long id : ids){
			if(id==null){
				continue;
			}
			PlmVideoNewsEntity entity = new PlmVideoNewsEntity();
			entity.setIsDelete(1);
			entity.setId(id);
			entity.setUpdateDate(new Date());
			entity.setUpdateUser(userId);
			this.baseMapper.updateById(entity);
		}
    }
	
	@Override
    @Transactional(rollbackFor = Exception.class)
    public void recycleBatch(Long[] ids,Long userId){
		if(ids==null || ids.length==0){
			return;
		}
		for(Long id : ids){
			if(id==null){
				continue;
			}
			PlmVideoNewsEntity entity = new PlmVideoNewsEntity();
			entity.setIsDelete(0);
			entity.setId(id);
			entity.setUpdateDate(new Date());
			entity.setUpdateUser(userId);
			this.baseMapper.updateById(entity);
		}
	}
	
	@Override
    @Transactional(rollbackFor = Exception.class)
    public void recycleDelete(Long[] ids,Long userId){
		if(ids==null || ids.length==0){
			return;
		}
		for(Long id : ids){
			if(id==null){
				continue;
			}
			PlmVideoNewsEntity entity = new PlmVideoNewsEntity();
			entity.setIsDelete(2);
			entity.setId(id);
			entity.setUpdateDate(new Date());
			entity.setUpdateUser(userId);
			this.baseMapper.updateById(entity);
		}
	}
}
