package com.yh.saas.plugin.clouddisk.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.winsea.svc.base.base.util.tree.TreeWrapper;
import com.winsea.svc.base.security.util.AuthSecurityUtils;
import com.yh.saas.common.support.util.IdGenerator;
import com.yh.saas.common.support.util.StringUtils;
import com.yh.saas.common.support.util.query.QueryUtils;
import com.yh.saas.plugin.clouddisk.entity.DataManagerFileInfo;
import com.yh.saas.plugin.clouddisk.entity.DataManagerFolder;
import com.yh.saas.plugin.clouddisk.entity.DataManagerFolderFileView;
import com.yh.saas.plugin.clouddisk.exception.DataManagerException;
import com.yh.saas.plugin.clouddisk.exception.DataManagerExceptionEnums;
import com.yh.saas.plugin.clouddisk.mapper.DataManagerFolderMapper;
import com.yh.saas.plugin.clouddisk.service.IDataManagerFileService;
import com.yh.saas.plugin.clouddisk.service.IDataManagerFolderService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 资源管理文件夹 - 实现类
 * </p>
 *
 * @author ZhangMingYu
 * @since 2019年11月5日11:21:58
 */

@Service
public class DataManagerFolderServiceImpl extends ServiceImpl<DataManagerFolderMapper, DataManagerFolder> implements IDataManagerFolderService {


    private static final String PARENT_PARAMETER = "-1";

    @Autowired
    private IDataManagerFileService dataManagerFileService;

    @Override
    @Transactional
    public void save(DataManagerFolder dataManagerFolder) {
        if (StringUtils.isEmpty(dataManagerFolder.getName())) {
            throw new DataManagerException(DataManagerExceptionEnums.DATA_MANAGER_FOLDER_NULL_NAME_ERROR);
        }
        if (StringUtils.isEmpty(dataManagerFolder.getParentFolderId())) {
            dataManagerFolder.setParentFolderId(PARENT_PARAMETER);
        }
        if (checkRepeatFolderName(dataManagerFolder.getName(), dataManagerFolder.getParentFolderId())) {
            throw new DataManagerException(DataManagerExceptionEnums.DATA_MANAGER_FOLDER_NAME);
        }
        dataManagerFolder.setId(IdGenerator.generateUUID());
        dataManagerFolder.insert();
    }

    @Override
    @Transactional
    public void remove(DataManagerFolder dataManagerFolder) {
        // 查出改父类下的所有文件夹id
        List<String> idList = getFolderIdList(dataManagerFolder.getFolderId());
        this.deleteBatchIds(idList);
        this.dataManagerFileService.delete(new EntityWrapper<DataManagerFileInfo>().in(DataManagerFileInfo.QueryFields.FOLDER_ID, idList));
    }

    @Override
    public void removeFolderFile(List<DataManagerFolderFileView> list) {
        if (!list.isEmpty()) {
            list.forEach(dataManagerFolderFileView -> {
                if (dataManagerFolderFileView.getType().equals("FOLDER")) {
                    DataManagerFolder dataManagerFolder = new DataManagerFolder();
                    dataManagerFolder.setFolderId(dataManagerFolderFileView.getId());
                    this.remove(dataManagerFolder);
                } else {
                    dataManagerFileService.deleteById(dataManagerFolderFileView.getId());
                }

            });
        }
    }

    @Override
    public void moveFolder(List<DataManagerFolderFileView> list) {
        if (!list.isEmpty()){
            list.stream().forEach(dataManagerFolderFileView->{
                if (dataManagerFolderFileView.getType().equals("FOLDER")){
                    DataManagerFolder dataManagerFolder = this.selectById(dataManagerFolderFileView.getId());
                    if (null == dataManagerFolder) {
                        throw new DataManagerException(DataManagerExceptionEnums.DATA_MANAGER_ID_NULL);
                    }
                    dataManagerFolder.setParentFolderId(dataManagerFolderFileView.getParentFolderId());
                    this.updateById(dataManagerFolder);
                }else{
                    DataManagerFileInfo dataManagerFileInfo=dataManagerFileService.selectById(dataManagerFolderFileView.getId());
                    if (null == dataManagerFileInfo){
                        throw new DataManagerException(DataManagerExceptionEnums.DATA_MANAGER_ID_NULL);
                    }
                    dataManagerFileInfo.setFolderId(dataManagerFolderFileView.getParentFolderId());
                    dataManagerFileService.updateById(dataManagerFileInfo);
                }
            });
        }

    }

    /**
     * @param id
     * @return
     */
    private List<String> getFolderIdList(String id) {
        List<String> idList = new ArrayList<>();
        idList.add(id);
        List<String> selectList = new ArrayList<>();
        selectList.add(id);
        List<DataManagerFolder> folderList;
        do {
            folderList = this.selectList(new EntityWrapper<DataManagerFolder>().in(DataManagerFolder.QueryFields.PARENT_FOLDER_ID, selectList));
            if (CollectionUtils.isNotEmpty(folderList)) {
                selectList = folderList.stream().map(DataManagerFolder::getFolderId).collect(Collectors.toList());
                idList.addAll(selectList);
            }
        }
        while (CollectionUtils.isNotEmpty(folderList));
        return idList;
    }

    @Override
    public void changeInfo(DataManagerFolder dataManagerFolder) {
        if (checkRepeatFolderName(dataManagerFolder.getName(), dataManagerFolder.getParentFolderId())) {
            throw new DataManagerException(DataManagerExceptionEnums.DATA_MANAGER_FOLDER_NAME);
        }
        this.updateById(dataManagerFolder);
    }

    @Override
    public List<DataManagerFolder> findTreeList(DataManagerFolder dataManagerFolder) {
        List<DataManagerFolder> parentFolders = this.selectList(QueryUtils.convertExampleToWrapper(dataManagerFolder).orderBy("create_date", true));
        return new TreeWrapper<>(parentFolders).polymerize();
    }

    @Override
    public List<DataManagerFolder> getDataManagerFolderList(String parentFolderId, String fileName, String orderColumn, String orderBy) {
        if (StringUtils.isEmpty(parentFolderId)) {
            parentFolderId = PARENT_PARAMETER;
        }
        Wrapper<DataManagerFolder> wrapper = new EntityWrapper<DataManagerFolder>();
        wrapper.eq(DataManagerFolder.QueryFields.PARENT_FOLDER_ID, parentFolderId);
        wrapper.eq(DataManagerFolder.QueryFields.COMP_ID, AuthSecurityUtils.getCurrentUserInfo().getCompId());
        if (!StringUtils.isEmpty(fileName)){
            wrapper.like(DataManagerFolder.QueryFields.FOLDER_NAME,fileName);
        }
        if (!StringUtils.isEmpty(orderColumn) && orderColumn.equals("createDate")){
            wrapper.orderBy(DataManagerFolder.QueryFields.CREATE_DATE,StringUtils.isEmpty(orderBy) || orderBy.equals("ASC")?true:false);
        }else if (!StringUtils.isEmpty(orderColumn) && orderColumn.equals("fileName")){
            wrapper.orderBy("CONVERT(name USING gbk)",StringUtils.isEmpty(orderBy) || orderBy.equals("ASC")?true:false);
        }else{
            wrapper.orderBy(DataManagerFolder.QueryFields.CREATE_DATE,false);
            wrapper.orderBy("CONVERT(name USING gbk)",true);
        }
        return this.selectList(wrapper);
    }

    /**
     * 检测是否有重复文件夹
     *
     * @param folderName 文件夹名称
     * @return Boolean
     */
    private Boolean checkRepeatFolderName(String folderName, String parentFolderId) {
        List<DataManagerFolder> dataManagerFolders = this.selectList(new EntityWrapper<DataManagerFolder>()
                .eq(DataManagerFolder.QueryFields.FOLDER_NAME, folderName)
                .eq(DataManagerFolder.QueryFields.PARENT_FOLDER_ID, parentFolderId));
        return CollectionUtils.isNotEmpty(dataManagerFolders);
    }
}
