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.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
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.common.utils.Query;
import com.platform.modules.plm.dao.PlmMaterialDao;
import com.platform.modules.plm.entity.PlmMaterialEntity;
import com.platform.modules.plm.service.PlmMaterialService;
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("plmMaterialService")
public class PlmMaterialServiceImpl extends ServiceImpl<PlmMaterialDao, PlmMaterialEntity> implements PlmMaterialService {
	
	@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>();
				PlmMaterialEntity bean = (PlmMaterialEntity) page.getList().get(i);
				if(bean==null){
					continue;
				}
				map.put("id", bean.getId());
				map.put("title", bean.getMaterialTitle());
				map.put("materialType", bean.getMaterialType());
				map.put("materialUrl", MaterialUtils.getMaterialUrl(bean.getMaterialUrl(), materiaFileProperties.getBasePath()));
				map.put("coverUrl", MaterialUtils.getMaterialUrl(bean.getMaterialCoverUrl(), materiaFileProperties.getBasePath()));
				map.put("uploadDate", bean.getCreateDate());
				map.put("sources", bean.getMaterialSources());
				list.add(map);
			}
		}
		resultMap.put("list", list);
		return resultMap;
	}
	
	@Override
	public PageUtils queryPageByParams(Map<String, Object> params) {
		//检索记录
		int current = ConverterUtils.parseInt(params.get("page"));
	    int limit = ConverterUtils.parseInt(params.get("limit"));
	    Integer[] materialSources = params.get("materialSources")==null ? null : (Integer[]) params.get("materialSources");
	    Page<Map<String, Object>> page = new Page<Map<String, Object>>(current, limit);
	    List<PlmMaterialEntity> 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>();
				PlmMaterialEntity bean = (PlmMaterialEntity) pageList.get(i);
				if(bean==null){
					continue;
				}
				map.put("id", bean.getId());
				map.put("title", bean.getMaterialTitle());
				map.put("materialType", bean.getMaterialType());
				map.put("materialUrl", MaterialUtils.getMaterialUrl(bean.getMaterialUrl(), materiaFileProperties.getBasePath()));
				if(bean.getMaterialType()==3 || bean.getMaterialType().equals(3)){
					map.put("coverUrl", MaterialUtils.getMaterialUrl(bean.getMaterialUrl(), materiaFileProperties.getBasePath()));
				}else{
					map.put("coverUrl", MaterialUtils.getMaterialUrl(bean.getMaterialCoverUrl(), materiaFileProperties.getBasePath()));
				}
				map.put("createDate", bean.getCreateDate());
				map.put("createUserName", bean.getCreateUserName());
				map.put("materialSize", bean.getMaterialSize());
				map.put("materialDuration", bean.getMaterialDuration());
				if(materialSources==null || materialSources.length>1){
					map.put("materialStatus", bean.getMaterialStatus());
					map.put("materialSources", bean.getMaterialSources());
				}
				list.add(map);
			}
		}
	    page.setRecords(list);
		return new PageUtils(page);
	}
	
	@Override
	public PageUtils queryRecyclePageMap(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<PlmMaterialEntity> 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>();
				PlmMaterialEntity bean = (PlmMaterialEntity) pageList.get(i);
				if(bean==null){
					continue;
				}
				map.put("id", bean.getId());
				map.put("title", bean.getMaterialTitle());
				map.put("materialType", bean.getMaterialType());
				map.put("materialUrl", MaterialUtils.getMaterialUrl(bean.getMaterialUrl(), materiaFileProperties.getBasePath()));
				
				if(bean.getMaterialType()==3 || bean.getMaterialType().equals(3)){
					map.put("coverUrl", MaterialUtils.getMaterialUrl(bean.getMaterialUrl(), materiaFileProperties.getBasePath()));
				}else{
					map.put("coverUrl", MaterialUtils.getMaterialUrl(bean.getMaterialCoverUrl(), materiaFileProperties.getBasePath()));
				}
				map.put("materialSources", bean.getMaterialSources());
				map.put("materialSize", bean.getMaterialSize());
				map.put("materialDuration", bean.getMaterialDuration());
				map.put("createDate", bean.getCreateDate());
				map.put("createUserName", bean.getCreateUserName());
				map.put("deleteDate", bean.getUpdateDate());
				map.put("deleteUserName", bean.getUpdateUserName());
				list.add(map);
			}
		}
		page.setRecords(list);
		return new PageUtils(page);
	}
	
	@Override
    public PageUtils queryPage(Map<String, Object> params) {
		String materialType = params.get("materialType")==null ? null : params.get("materialType").toString();
    	String title = params.get("title")==null ? null : params.get("title").toString();
    	String isDelete = params.get("isDelete")==null ? null : params.get("isDelete").toString();
    	String materialSources = params.get("materialSources")==null ? null : params.get("materialSources").toString();
        Page<PlmMaterialEntity> page = this.selectPage(
                new Query<PlmMaterialEntity>(params).getPage(),
                new EntityWrapper<PlmMaterialEntity>()
                .eq(StringUtils.isNotBlank(materialType),"material_type",materialType)
                .eq(StringUtils.isNotBlank(materialSources),"material_sources",materialSources)
                .like(StringUtils.isNotBlank(title),"material_title",title)
                .eq(StringUtils.isNotBlank(isDelete),"is_delete",isDelete));
        return new PageUtils(page);
    }
	
	@Override
    public void save(MultipartFile materialFile, MultipartFile coverFile,String materialTitle,String materialDescription,Integer materialType,Long userId){
		if (materialFile == null || materialFile.isEmpty()){
            throw new RRException("资源文件不能为空!");
        }
		PlmMaterialEntity plmMaterial = new PlmMaterialEntity();
		plmMaterial.setMaterialTitle(materialTitle);
		plmMaterial.setMaterialType(materialType);
		plmMaterial.setMaterialDescription(materialDescription);
        try {
        	String newMaterialName = FileUtils.createFileName() + "." + FileUtils.getSuffix(materialFile.getOriginalFilename());
            String serverMaterialPath = materiaFileProperties.getMediaPath() + "/" + MaterialUtils.getDateDir() + "/" + newMaterialName;
            String newMaterialPath = realPathResolver.get(materiaFileProperties.getMateriaPath() + serverMaterialPath);
        	File file = new File(newMaterialPath);
            FileUtils.copy(materialFile.getInputStream(), newMaterialPath);
            
            Long fileSize = MaterialUtils.getFileSize(file);
            Long playTime = MaterialUtils.getPlayTime(file);
            if(fileSize!=null){
            	plmMaterial.setMaterialSize(FileCalculateUtils.calculateFileSizeString(fileSize, FileSizeUnitEnum.MB));
            	plmMaterial.setFileSize(fileSize);
            }
            if(playTime!=null){
            	plmMaterial.setPlayTime(playTime);
            	plmMaterial.setMaterialDuration(FileCalculateUtils.calculateFilePlayTimeString(playTime));
            }
            
            plmMaterial.setMaterialDuration(MaterialUtils.getPlayTime(file, null));
            if(plmMaterial.getMaterialType()!=null && (plmMaterial.getMaterialType()==1 || plmMaterial.getMaterialType().equals(1) || plmMaterial.getMaterialType()==2 || plmMaterial.getMaterialType().equals(2)) 
            		&& coverFile!=null && !coverFile.isEmpty()){
            	String newCoverName = FileUtils.createFileName() + "." + FileUtils.getSuffix(coverFile.getOriginalFilename());
                String serverCoverPath = materiaFileProperties.getMediaPath() + "/" + MaterialUtils.getDateDir() +"/" + newCoverName;
                String newCoverPath = materiaFileProperties.getMateriaPath() + serverCoverPath;
                FileUtils.copy(coverFile.getInputStream(), realPathResolver.get(newCoverPath));
                plmMaterial.setMaterialCoverUrl(serverCoverPath);
            }
            // 保存上传文件
            plmMaterial.setCreateDate(new Date());
            plmMaterial.setCreateUser(userId);
            plmMaterial.setUpdateUser(userId);
            plmMaterial.setUpdateDate(new Date());
            plmMaterial.setMaterialSources(1);
            plmMaterial.setMaterialUrl(serverMaterialPath);
            plmMaterial.setIsDelete(0);
            plmMaterial.setMaterialStatus(1);
            this.baseMapper.insert(plmMaterial);
        } catch (IOException e) {
        	throw new RRException("上传失败!");
        }
	}
	
	@Override
    public void update(Long id,MultipartFile materialFile, MultipartFile coverFile,String materialTitle,String materialDescription,Integer materialType,Long userId){
		PlmMaterialEntity plmMaterial = new PlmMaterialEntity();
		if(id==null){
			throw new RRException("Id不能为空!");
		}
		plmMaterial.setId(id);
		plmMaterial.setMaterialTitle(materialTitle);
		plmMaterial.setMaterialType(materialType);
		plmMaterial.setMaterialDescription(materialDescription);
        try {
        	if(materialFile!=null && !materialFile.isEmpty()){
        		String newMaterialName = FileUtils.createFileName() + "." + FileUtils.getSuffix(materialFile.getOriginalFilename());
                String serverMaterialPath = materiaFileProperties.getMediaPath() + "/" + MaterialUtils.getDateDir() + "/" + newMaterialName;
                String newMaterialPath = realPathResolver.get(materiaFileProperties.getMateriaPath() + serverMaterialPath);
            	File file = new File(newMaterialPath);
                FileUtils.copy(materialFile.getInputStream(), newMaterialPath);
                plmMaterial.setMaterialSize(MaterialUtils.getFileSize(file, null));
                plmMaterial.setMaterialDuration(MaterialUtils.getPlayTime(file, null));
                plmMaterial.setMaterialUrl(serverMaterialPath);
        	}
            if(plmMaterial.getMaterialType()!=null && (plmMaterial.getMaterialType()==1 || plmMaterial.getMaterialType().equals(1) || plmMaterial.getMaterialType()==2 || plmMaterial.getMaterialType().equals(2)) 
            		&& coverFile!=null && !coverFile.isEmpty()){
            	String newCoverName = FileUtils.createFileName() + "." + FileUtils.getSuffix(coverFile.getOriginalFilename());
                String serverCoverPath = materiaFileProperties.getMediaPath() + "/" + MaterialUtils.getDateDir() +"/" + newCoverName;
                String newCoverPath = materiaFileProperties.getMateriaPath() + serverCoverPath;
                FileUtils.copy(coverFile.getInputStream(), realPathResolver.get(newCoverPath));
                plmMaterial.setMaterialCoverUrl(serverCoverPath);
            }
            // 保存上传文件
            plmMaterial.setUpdateUser(userId);
            plmMaterial.setUpdateDate(new Date());
            this.baseMapper.updateById(plmMaterial);
        } catch (IOException e) {
        	throw new RRException("修改失败!");
        }
	}
	
	@Override
    public Map<String, Object> findById(Long id){
		if(id==null){
			return null;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		PlmMaterialEntity entity = this.baseMapper.queryById(id);
		if(entity==null || entity.getId()==null){
			return null;
		}
		map.put("id", entity.getId());
		map.put("materialTitle", entity.getMaterialTitle());
		map.put("materialDescription", entity.getMaterialDescription());
		map.put("materialType", entity.getMaterialType());
		if(entity.getMaterialType()!=null && entity.getMaterialType().equals(3)){
			if(entity.getMaterialUrl().indexOf(",")>0){
				String[]  strs = entity.getMaterialUrl().split(",");
				if(strs!=null && strs.length>0){
					String[] imgList = new String[strs.length];
					for(int i=0;i<strs.length;i++){
						imgList[i] = MaterialUtils.getMaterialUrl(strs[i], materiaFileProperties.getBasePath());
					}
					map.put("imgList", imgList);
				}
			}else{
				map.put("imgList", new String[]{entity.getMaterialUrl()});
			}
		}
		map.put("materialStatus", entity.getMaterialStatus());
		map.put("materialUrl", MaterialUtils.getMaterialUrl(entity.getMaterialUrl(), materiaFileProperties.getBasePath()));
		map.put("materialCoverUrl", MaterialUtils.getMaterialUrl(entity.getMaterialCoverUrl(), materiaFileProperties.getBasePath()));
		map.put("createDate", entity.getCreateDate());
		map.put("createUserName", entity.getCreateUserName());
		map.put("materialDuration", entity.getMaterialDuration());
		map.put("materialSize", entity.getMaterialSize());
		map.put("materialSources", entity.getMaterialSources());
		if(entity.getIsDelete()==1 || entity.getIsDelete().equals(1)){
			map.put("deleteDate", entity.getUpdateDate());
			map.put("deleteUserName", entity.getUpdateUserName());
		}else{
			map.put("updateDate", entity.getUpdateDate());
			map.put("updateUserName", entity.getUpdateUserName());
		}
		return map;
	}
	
	@Override
	public void deleteBatch(Long[] ids,Long userId){
		if(ids==null || ids.length==0){
			return;
		}
		for(Long id : ids){
			if(id==null){
				continue;
			}
			PlmMaterialEntity entity = new PlmMaterialEntity();
			entity.setIsDelete(1);
			entity.setId(id);
			entity.setUpdateDate(new Date());
			entity.setUpdateUser(userId);
			this.baseMapper.updateById(entity);
		}
	}
	
	@Override
	public void recycleBatch(Long[] ids,Long userId){
		if(ids==null || ids.length==0){
			return;
		}
		for(Long id : ids){
			if(id==null){
				continue;
			}
			PlmMaterialEntity entity = new PlmMaterialEntity();
			entity.setIsDelete(0);
			entity.setId(id);
			entity.setUpdateDate(new Date());
			entity.setUpdateUser(userId);
			this.baseMapper.updateById(entity);
		}
	}
	
	@Override
	public void recycleDelete(Long[] ids,Long userId){
		if(ids==null || ids.length==0){
			return;
		}
		for(Long id : ids){
			if(id==null){
				continue;
			}
			PlmMaterialEntity entity = new PlmMaterialEntity();
			entity.setIsDelete(2);
			entity.setId(id);
			entity.setUpdateDate(new Date());
			entity.setUpdateUser(userId);
			this.baseMapper.updateById(entity);
		}
	}
}
