package com.artfess.file.persistence.manager.impl;

import com.artfess.base.exception.ApplicationException;
import com.artfess.base.manager.impl.BaseManagerImpl;
import com.artfess.base.util.BeanUtils;
import com.artfess.file.model.FileConfig;
import com.artfess.file.model.FileStorage;
import com.artfess.file.model.FlowUploadProperties;
import com.artfess.file.persistence.dao.FileConfigDao;
import com.artfess.file.persistence.dao.FileStorageDao;
import com.artfess.file.persistence.dao.FlowUploadPropertiesDao;
import com.artfess.file.persistence.manager.FileStorageManager;
import com.artfess.file.persistence.manager.FlowUploadPropertiesManager;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
* @Description: 系统附件存储配置 处理实现类
* @Author: chens
* @Date: 2021/6/8 10:34
*/
@Service("fileStorageManager")
public class FileStorageManagerImpl extends BaseManagerImpl<FileStorageDao, FileStorage> implements FileStorageManager {

	@Resource
	FileConfigDao fileConfigDao;

	@Override
	public String insertFileStorage(FileStorage fileStorage) {
		Assert.notNull(fileStorage, "附件存储信息不能为空！");
		boolean flag = this.checkSameField("", "CODE_",fileStorage.getCode());
		if(!flag){
			throw new ApplicationException("编码重复请修改！");
		}
		baseMapper.insert(fileStorage);
		return fileStorage.getId();
	}

	@Override
	public String updateFileStorage(FileStorage fileStorage) {
		Assert.notNull(fileStorage, "附件存储信息不能为空！");
		boolean flag = this.checkSameField(fileStorage.getId(), "CODE_",fileStorage.getCode());
		if(!flag){
			throw new ApplicationException("编码重复请修改！");
		}
		this.update(fileStorage);
		return fileStorage.getId();
	}

	@Override
	@Transactional
	public String deleteFileStorage(String ...ids) {
		Assert.notEmpty(ids, "参数ids不能为空！");
		List<String> idsList = Arrays.asList(ids);
		List<String> delIds = new ArrayList<>();
		List<String> notDelIds = new ArrayList<>();
		for(String storageId : idsList){
			QueryWrapper<FileConfig> queryWrapper = new QueryWrapper();
			queryWrapper.eq("STORAGE_ID_", storageId);
			int num = fileConfigDao.selectCount(queryWrapper);
			if(num == 0){
				delIds.add(storageId);
			}else{
				notDelIds.add(storageId);
			}
		}
		if(BeanUtils.isNotEmpty(delIds)){
			this.baseMapper.deleteBatchIds(delIds);
		}
		if(BeanUtils.isNotEmpty(notDelIds)){
			return "主键为："+notDelIds.toString()+"的配置已被应用，不能删除！";
		}else{
			return "删除成功！";
		}
	}

	@Override
	public FileStorage getByCode(String code) {
		Assert.hasText(code, "编码不能为空");
		QueryWrapper<FileStorage> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("CODE_", code);

		return baseMapper.selectOne(queryWrapper);
	}
}
