package cn.service.atv.impl;

import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.facade.abs.IService;
import cn.constant.CommonConst;
import cn.orm.sqltoy.plus.Wrappers;
import cn.orm.sqltoy.plus.query.QueryWrapper;
import cn.orm.sqltoy.plus.update.UpdateWrapper;
import cn.orm.util.builder.BuildSQL;
import cn.pojo.atv.AtvKnowledge;
import cn.pojo.atv.AtvKnowledgeFile;
import cn.service.atv.IAtvKnowledgeService;
import cn.util.file.FileKit;

@Service
public class AtvKnowledgeServiceImpl extends IService implements IAtvKnowledgeService
{
	@Override
	@Transactional
	public AtvKnowledge getKnowledgeDetailById(String id)
	{
		QueryWrapper<AtvKnowledge> queryWrapper = Wrappers.wrapper(AtvKnowledge.class)
				.eq("id", id);//相当于设置：id=1
		return daoService.findOne(queryWrapper);
	}
	
	@Override
	@Transactional
	public void saveMain(AtvKnowledge atvKnowledge, List<AtvKnowledgeFile> atvKnowledgeFileList) 
	{
		daoService.save(atvKnowledge);
		if (atvKnowledgeFileList != null && atvKnowledgeFileList.size() > 0) {
			for (AtvKnowledgeFile entity : atvKnowledgeFileList) {
				//外键设置
				entity.setKnowledgeId(atvKnowledge.getId());
				daoService.save(entity);
			}
		}
	}

	@Override
	@Transactional
	public void updateMain(AtvKnowledge atvKnowledge, List<AtvKnowledgeFile> atvKnowledgeFileList) 
	{
		daoService.update(atvKnowledge);
		//1.先删除子表数据
		//atvKnowledgeFileMapper.deleteByMainId(atvKnowledge.getId());
		//?daoService.deleteByIds(AtvKnowledge.class,atvKnowledge.getId());
    
		//2.子表数据重新插入
		if(atvKnowledgeFileList!=null && atvKnowledgeFileList.size()>0) {
			for(AtvKnowledgeFile entity:atvKnowledgeFileList) {
				//外键设置
				entity.setKnowledgeId(atvKnowledge.getId());
				daoService.save(entity);
			}
		}
	}
	@Override
	@Transactional
	public Boolean updateIsRelease(Map<String,Object> pageParam) 
	{
		UpdateWrapper<AtvKnowledge> updateWrapper = Wrappers.updateWrapper(AtvKnowledge.class)
				.set("isRelease", pageParam.get("isRelease"))
				.eq("id", pageParam.get("id"));
		return daoService.update(updateWrapper) > 0 ;
	}

	/**批量删除知识库表. 不判断是否真删除*/
	@Override
	@Transactional
	public Boolean delBatch(List<String> idList)
	{
		String sql = null;
		//3、增强for循环遍历
		for(String id : idList){
			//删除atv_knowledge
			sql = BuildSQL.delete("atv_knowledge",CommonConst.DEFAULT_PRIMARY_KEY,id);
			daoService.executeSql(sql, null, null);
			//删除atv_knowledge_file
			sql = BuildSQL.delete("atv_knowledge_file","knowledge_id",id);
			daoService.executeSql(sql, null, null);
			//删除文件id开头
			FileKit.delMultiFile("archive",id);	
		}
		return true;
	}  
}
