package com.patzn.lims.file.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.patzn.lims.core.web.BaseServiceImpl;
import com.patzn.lims.core.web.LoginHelper;
import com.patzn.lims.file.entity.LmsFileStorage;
import com.patzn.lims.file.mapper.LmsFileStorageMapper;
import com.patzn.lims.file.service.ILmsFileStorageService;
import org.springframework.stereotype.Service;

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

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wangweidong
 * @since 2019-12-13
 */
@Service
public class LmsFileStorageServiceImpl extends BaseServiceImpl<LmsFileStorageMapper, LmsFileStorage> implements ILmsFileStorageService {


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


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

    @Override
    public LmsFileStorage getVOByCompanyId(Long companyId) {
        LmsFileStorage sysFileStorage = getOne(Wrappers.<LmsFileStorage>query().eq("company_id",companyId).last("LIMIT 1"));
       if (null == sysFileStorage){
           sysFileStorage = new LmsFileStorage();
           sysFileStorage.setCompanyId(companyId);
           sysFileStorage.setBucket("files");
           sysFileStorage.setName("主文件夹"+companyId);
           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(LoginHelper.getAccount().getUserId());
           sysFileStorage.setDeleted(0);
           save(sysFileStorage);
           BigDecimal all =sysFileStorage.getCapacity();
           sysFileStorage.setLeftover(all);
           return sysFileStorage;
       }else{
           BigDecimal used = sysFileStorage.getUsed();
           if (used==null){
               used = BigDecimal.ZERO;
           }

           BigDecimal userd =used.divide(new BigDecimal("1024"),2,BigDecimal.ROUND_HALF_UP);
           sysFileStorage.setUsed(userd);

       }

        return sysFileStorage;
    }

    @Override
    public LmsFileStorage getLockStorageById(Long companyId) {
        return baseMapper.selectLockStorageById(companyId);
    }

    @Override
    public LmsFileStorage getByCompanyId(Long companyId) {
        return getOne(Wrappers.<LmsFileStorage>query().eq("company_id",companyId));
    }


}
