package com.patzn.lims.file.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.patzn.lims.common.StringHandleUtils;
import com.patzn.lims.core.api.PtAssert;
import com.patzn.lims.core.web.Account;
import com.patzn.lims.core.web.BaseServiceImpl;
import com.patzn.lims.file.entity.LmsFile;
import com.patzn.lims.file.entity.LmsFileFolder;
import com.patzn.lims.file.entity.LmsFileStorage;
import com.patzn.lims.file.mapper.LmsFileFolderMapper;
import com.patzn.lims.file.service.ILmsFileFolderService;
import com.patzn.lims.file.service.ILmsFileService;
import com.patzn.lims.file.service.ILmsFileStorageService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wangweidong
 * @since 2019-12-13
 */
@Service
public class LmsFileFolderServiceImpl extends BaseServiceImpl<LmsFileFolderMapper, LmsFileFolder> implements ILmsFileFolderService {

    @Autowired
    private ILmsFileStorageService lmsFileStorageService;
    @Autowired
    private ILmsFileService lmsFileService;

    @Override
    public Page<LmsFileFolder> page(Page<LmsFileFolder> page, LmsFileFolder schoolFileFolder) {
        QueryWrapper wrapper = Wrappers.<LmsFileFolder> query(schoolFileFolder);
        return this.page(page, wrapper);
    }


    @Override
    public List<LmsFileFolder> list(LmsFileFolder schoolFileFolder) {
        return this.list(Wrappers.<LmsFileFolder> query(schoolFileFolder));
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean addFolder(LmsFileFolder sysFolder, Account account) {
        if (null == account){
            PtAssert.fail("数据有误");
        }

        if (null == account.getCompanyId()){
            PtAssert.fail("数据有误");
        }
        if (StringUtils.isBlank(sysFolder.getName())){
            PtAssert.fail("文件名称数据有误");
        }

        synchronized (lmsFileStorageService){
            List<LmsFileStorage> sysFileStorageList= lmsFileStorageService.list(Wrappers.<LmsFileStorage>query().eq("company_id",account.getCompanyId()));
            if (CollectionUtils.isEmpty(sysFileStorageList)){
                LmsFileStorage sysFileStorage = new LmsFileStorage();
                sysFileStorage.setCompanyId(account.getCompanyId());
                sysFileStorage.setBucket("files");
                sysFileStorage.setName("主文件夹"+account.getCompanyId());
                sysFileStorage.setCapacity(new BigDecimal("512"));
                sysFileStorage.setCapacityKb(new BigDecimal("524288"));
                sysFileStorage.setLeftover(new BigDecimal("512"));
                sysFileStorage.setUsed(BigDecimal.ZERO);
                sysFileStorage.setCtime(new Date());
                sysFileStorage.setUid(account.getUserId());
                sysFileStorage.setDeleted(0);

                if (lmsFileStorageService.save(sysFileStorage)){
                    sysFolder.setFileType("文件夹");
                    sysFolder.setCtime(new Date());
                    sysFolder.setStorageId(sysFileStorage.getId());
                    sysFolder.setUid(account.getUserId());
                    sysFolder.setUname(account.getUserName());

                    return    save(sysFolder);
                }
            }else{
                sysFolder.setFileType("文件夹");
                sysFolder.setCtime(new Date());
                sysFolder.setStorageId(sysFileStorageList.get(0).getId());
                sysFolder.setUid(account.getUserId());
                sysFolder.setUname(account.getUserName());
                return  save(sysFolder);
            }
        }
        return false;
      }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean removeFolder(Long[] ids, Account account) {
        StringHandleUtils.emptyArrayJudge(ids);
        List<LmsFileFolder> folderList = list(Wrappers.<LmsFileFolder>query().in("id",ids));
       LmsFileStorage fileStorage = lmsFileStorageService.getByCompanyId(account.getCompanyId());
        if (null == fileStorage){
            return false;
        }
        if (CollectionUtils.isEmpty(folderList)){
           return deleteFiles(fileStorage,ids);
        }else{
            //说明删除的有文件夹，此时要判断文件夹下有没有文件 有文件不允许删除
            List<Long> folderIdList = new ArrayList<>();
            for (LmsFileFolder schoolFileFolder : folderList) {
                folderIdList.add(schoolFileFolder.getId());
            }
            List<LmsFileFolder> checkFolderList = list(Wrappers.<LmsFileFolder>query().in("folder_id",folderIdList));

            List<LmsFile> checkFileList = lmsFileService.list(Wrappers.<LmsFile>query().in("folder_id",folderIdList));
            if (CollectionUtils.isNotEmpty(checkFileList)||CollectionUtils.isNotEmpty(checkFolderList)){
                PtAssert.fail("只能删除空文件夹，您选择的文件夹含有非空的，请确认");
                 return false;
            }

            if (remove(Wrappers.<LmsFileFolder>query().in("id",folderIdList))){
               return deleteFiles(fileStorage,ids);
            }
        }

        return true;
    }


    public boolean deleteFiles(LmsFileStorage fileStorage,Long [] ids){
        //删除的全部是文件而不是文件夹
        List<LmsFile> fileList =lmsFileService.list(Wrappers.<LmsFile>query().in("id",ids));
        BigDecimal release=BigDecimal.ZERO;
        for (LmsFile file:fileList) {
            if (null != file){
                if (null!=file.getFileSize()){
                    release=  release.add(file.getFileSize());
                }
            }
        }
        BigDecimal used = fileStorage.getUsed();
        if (null == used){
            return false;
        }
        BigDecimal nowUsed=  used.subtract(release);
        LmsFileStorage updateStorage = new LmsFileStorage();
        updateStorage.setUsed(nowUsed);
        Integer version = fileStorage.getVersion();
        updateStorage.setVersion(version+1);
        if (lmsFileStorageService.update(updateStorage,Wrappers.<LmsFileStorage>query().eq("id",fileStorage.getId()).eq("version",version))){
            lmsFileService.remove(Wrappers.<LmsFile>query().in("id",ids));
        }
        return true;
    }


}
