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

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.FileUtils;
import com.platform.common.utils.PageUtils;
import com.platform.modules.live.constants.SceneConstants;
import com.platform.modules.live.dao.LiveTaskAllocationDao;
import com.platform.modules.live.entity.LiveTaskAllocationEntity;
import com.platform.modules.live.service.LiveTaskAllocationService;
import com.platform.modules.live.vo.LiveTaskAllocationListVo;
import com.platform.modules.live.vo.LiveTaskAllocationVo;
import com.platform.modules.plm.util.MateriaFileProperties;
import com.platform.modules.plm.util.MaterialUtils;
import com.platform.modules.sys.service.SysUserService;
import com.platform.plugs.live.LiveClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ClassUtils;
import org.springframework.web.multipart.MultipartFile;

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

@Service("liveTaskAllocationService")
@Transactional
public class LiveTaskAllocationServiceImpl extends ServiceImpl<LiveTaskAllocationDao, LiveTaskAllocationEntity> implements LiveTaskAllocationService {
	
	@Autowired
	private MateriaFileProperties materiaFileProperties;
	
	@Autowired
    private LiveClient liveClient;

	@Autowired
    private SysUserService userService;

	private static final String BASE_PATH = "/"+ClassUtils.getDefaultClassLoader().getResource("").getPath().substring(1) + "static";
	
	@Override
    @Transactional(readOnly = true)
    public PageUtils queryPage(Map<String, Object> params){

	    Object objNo = params.get("pageNo");
	    Object objSize = params.get("pageSize");

	    int pageNo = 1;
	    int pageSize = 10;

	    if (null != objNo)
	    	pageNo = Integer.parseInt(objNo.toString());
		if (null != objSize)
			pageSize = Integer.parseInt(objSize.toString());

	    Page<LiveTaskAllocationVo> page = new Page<>(pageNo, pageSize);

	    List<LiveTaskAllocationVo> liveTaskAllocationVoList = this.baseMapper.queryByPage(page, params);

	    if (null == liveTaskAllocationVoList || liveTaskAllocationVoList.size() == 0)
	        return null;
	    // 拼地址
	    liveTaskAllocationVoList.forEach(list -> list.setUri(MaterialUtils.getMaterialUrl(list.getUri(), materiaFileProperties.getBasePath())));

	    page.setRecords(liveTaskAllocationVoList);
//		EntityWrapper<LiveTaskAllocationEntity> wrapper = new EntityWrapper<LiveTaskAllocationEntity>();
//        String tenantId = (String)params.get("tenantId"); //现场ID
//        if (StringUtils.isNotBlank(tenantId)) {
//            wrapper.eq("tenant_id", tenantId);
//        }
//        String userId = params.get("userId").toString();
//        if (StringUtils.isNotBlank(userId)){
//            wrapper.eq("reporter_id", userId);
//        }
//        wrapper.eq("is_delete", SceneConstants.NOT_DELETE);
//        wrapper.orderBy("id", false);
//        Page<LiveTaskAllocationEntity> page = this.selectPage(new Query<LiveTaskAllocationEntity>(params).getPage(), wrapper);
        return new PageUtils(page);
	}

    @Override
    public PageUtils backgroundList(Integer pageNo, Integer pageSize) {

		Page<LiveTaskAllocationListVo> page = new Page<>(pageNo, pageSize);

		List<LiveTaskAllocationListVo> entityList = this.baseMapper.query(page);

		// 拼接音频地址
		entityList.forEach(list -> list.setUri(MaterialUtils.getMaterialUrl(list.getUri(), materiaFileProperties.getBasePath())));

		page.setRecords(entityList);

		return new PageUtils(page);
    }

    @Override
	public void save(LiveTaskAllocationEntity liveSceneTaskAllocation){
		this.baseMapper.insert(liveSceneTaskAllocation);
	}
	
	@Override
	public void update(LiveTaskAllocationEntity liveSceneTaskAllocation){
		this.baseMapper.updateById(liveSceneTaskAllocation);
	}
	
	@Override
	public void delete(Integer id){
		this.baseMapper.deleteById(id);
	}
	
	@Override
	public void deleteBatch(Integer[] ids){
		List<LiveTaskAllocationEntity> list = new ArrayList<>();
        for (Integer id : ids) {
        	LiveTaskAllocationEntity entity = selectById(id);
            if (entity != null) {
                entity.setIsDelete(SceneConstants.IS_DELETE);
                list.add(entity);
            }
        }
        updateBatchById(list);
	}
	
	@Override
	public void readBatch(Integer[] ids){
		
		List<LiveTaskAllocationEntity> list = new ArrayList<>();
		Date date = new Date();
        for (Integer id : ids) {
        	LiveTaskAllocationEntity entity = selectById(id);
            if (entity != null) {
                entity.setIsRead(1);
                entity.setReadDate(date);
                list.add(entity);
            }
        }
        updateBatchById(list);
	}

    @Override
    public void handlerAll(boolean flag, Integer reporterId) {

        EntityWrapper<LiveTaskAllocationEntity> wrapper = new EntityWrapper<>();

        wrapper.eq("reporter_id", reporterId);
        wrapper.eq("is_delete", SceneConstants.NOT_DELETE);

        List<LiveTaskAllocationEntity> taskAllocationEntityList = this.selectList(wrapper);

        if (null != taskAllocationEntityList && taskAllocationEntityList.size() > 0){
        	Date now = new Date();
            if (flag){
                taskAllocationEntityList.forEach(list -> {
                	list.setIsRead(1);
                	list.setReadDate(now);
				});
            }else {
                taskAllocationEntityList.stream()
                        .filter(list -> list.getIsRead().equals(1))
                        .forEach(list -> list.setIsDelete(SceneConstants.IS_DELETE));
            }

            this.updateBatchById(taskAllocationEntityList);
        }
    }

    @Override
	public void taskAllocation(Integer[] reporterIds,Integer userId, MultipartFile mediaFile, Integer durationTime){
//		String newFileName = FileUtils.createFileName() + "." + FileUtils.getSuffix(mediaFile.getOriginalFilename());
//        String serverMediaPath = materiaFileProperties.getMateriaPath() + materiaFileProperties.getMediaPath() + "/" +
//				MaterialUtils.getDateDir() ; // 存放在服务器地址
//        String newFilePath = serverMediaPath+ File.separator + newFileName; // 保存视频的路径
//
//        File file = new File(newFilePath);
//        try {
//            FileUtils.copy(mediaFile.getInputStream(), BASE_PATH + newFilePath);
//        } catch (IOException e) {
//        	throw new RRException("上传失败!");
//        }
//
//        String taskId = liveClient.liveAudio().getAudioRecognitionResult(MaterialUtils.getMaterialUrl(newFilePath, materiaFileProperties.getBasePath()), "platform/live/notify/allocation");
//
//        List<LiveTaskAllocationEntity> list = new ArrayList<>();
//
//		for (Integer id : reporterIds){
//			LiveTaskAllocationEntity entity = new LiveTaskAllocationEntity();
//
//			entity.setCreateId(userId);
//			entity.setUri(newFilePath);
//			entity.setTaskId(taskId);
//			entity.setCreateDate(new Date());
//			entity.setReporterId(id);
//			entity.setDurationTime(String.valueOf(durationTime));
//
//			list.add(entity);
//		}
//
//        this.insertBatch(list);
	}
}
