package vip.xiaonuo.disk.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.common.pojo.CommonResult;
import vip.xiaonuo.disk.domain.CapacityReAuditInfo;
import vip.xiaonuo.disk.domain.StorageReBean;
import vip.xiaonuo.disk.domain.SysParam;
import vip.xiaonuo.disk.dto.storage.GetUserStorageDTO;
import vip.xiaonuo.disk.mapper.CapacityReAuditInfoMapper;
import vip.xiaonuo.disk.mapper.ResourceUserFileMapper;
import vip.xiaonuo.disk.mapper.StorageReMapper;
import vip.xiaonuo.disk.mapper.SysParamMapper;
import vip.xiaonuo.disk.service.IStorageReService;
import vip.xiaonuo.disk.util.PageQuery;
import vip.xiaonuo.disk.util.TableDataInfo;
import vip.xiaonuo.disk.vo.storage.CapacityReAuditInfoVo;
import vip.xiaonuo.disk.vo.storage.StorageReBeanVO;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
@Slf4j
@Service
@Transactional(rollbackFor=Exception.class)
public class StorageReService implements IStorageReService {
    @Resource
    StorageReMapper storageReMapper;
    @Resource
    SysParamMapper sysParamMapper;
    @Resource
    ResourceUserFileMapper resourceUserFileMapper;

    @Resource
    private CapacityReAuditInfoMapper capacityReAuditInfoMapper;


    public Long getTotalStorageSize(String userId) {
        LambdaQueryWrapper<StorageReBean> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(StorageReBean::getUserId, userId);

        StorageReBean storageReBean = storageReMapper.selectOne(lambdaQueryWrapper);
        Long totalStorageSize = null;
        if (storageReBean == null || storageReBean.getTotalStorageSize() == null) {
            LambdaQueryWrapper<SysParam> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper1.eq(SysParam::getSysParamKey, "totalStorageSize");
            SysParam sysParam = sysParamMapper.selectOne(lambdaQueryWrapper1);
            totalStorageSize = Long.parseLong(sysParam.getSysParamValue());
            storageReBean = new StorageReBean();
            storageReBean.setUserId(userId);
            storageReBean.setTotalStorageSize(totalStorageSize);
            storageReMapper.insert(storageReBean);
        } else  {
            totalStorageSize = storageReBean.getTotalStorageSize();
        }

        if (totalStorageSize != null) {
            totalStorageSize = totalStorageSize * 1024 * 1024;
        }
        return totalStorageSize;
    }

    public boolean checkStorage(String userId, Long fileSize) {
        LambdaQueryWrapper<StorageReBean> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(StorageReBean::getUserId, userId);

        StorageReBean storageReBean = storageReMapper.selectOne(lambdaQueryWrapper);
        Long totalStorageSize = null;
        if (storageReBean == null || storageReBean.getTotalStorageSize() == null) {
            LambdaQueryWrapper<SysParam> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper1.eq(SysParam::getSysParamKey, "totalStorageSize");
            SysParam sysParam = sysParamMapper.selectOne(lambdaQueryWrapper1);
            totalStorageSize = Long.parseLong(sysParam.getSysParamValue());
            storageReBean = new StorageReBean();
            storageReBean.setUserId(userId);
            storageReBean.setTotalStorageSize(totalStorageSize);
            storageReMapper.insert(storageReBean);
        } else  {
            totalStorageSize = storageReBean.getTotalStorageSize();
        }

        if (totalStorageSize != null) {
            totalStorageSize = totalStorageSize * 1024 * 1024;
        }

        Long storageSize = resourceUserFileMapper.selectStorageSizeByUserId(userId);
        if (storageSize == null ){
            storageSize = 0L;
        }
        if (storageSize + fileSize > totalStorageSize) {
            return false;
        }
        return true;

    }

    @Override
    public CommonResult<Long> getDefaultStorage() {
        // 查询sysparam表，根据totalStorageSize标识查询
        LambdaQueryWrapper<SysParam> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper1.eq(SysParam::getSysParamKey, "totalStorageSize");
        SysParam sysParam = sysParamMapper.selectOne(lambdaQueryWrapper1);
        return CommonResult.data(Long.parseLong(sysParam.getSysParamValue()));
    }

    @Override
    public CommonResult<String> updateDefaultStorage(Long size) {
        // 查询sysparam表，根据totalStorageSize标识查询
        LambdaQueryWrapper<SysParam> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper1.eq(SysParam::getSysParamKey, "totalStorageSize");
        SysParam sysParam = sysParamMapper.selectOne(lambdaQueryWrapper1);
        // 进行修改空间大小
        sysParam.setSysParamValue(String.valueOf(size));
        int i = sysParamMapper.updateById(sysParam);
        if (i > 0) {
            return CommonResult.data("修改成功");
        }
        return CommonResult.error("修改失败");
    }

    @Override
    public CommonResult<TableDataInfo<StorageReBeanVO>> getUserStorageList(GetUserStorageDTO getUserStorageDTO) {
        PageQuery pageQuery = new PageQuery();
        pageQuery.setPageNum(getUserStorageDTO.getPageNum());
        pageQuery.setPageSize(getUserStorageDTO.getPageSize());
        Page<StorageReBeanVO> StorageReBeanList = storageReMapper.getUserStorageList(pageQuery.build(), getUserStorageDTO);
        if (StorageReBeanList.getRecords() != null && StorageReBeanList.getSize() > 0) {
            // 如果查出的数据不为空，关联用户的角色
            for (StorageReBeanVO StorageReBean : StorageReBeanList.getRecords()) {
                String userId = StorageReBean.getUserId();
                List<String> roleNameList = storageReMapper.getUserRoleNameListById(userId);
                if (roleNameList != null && roleNameList.size() > 0) {
                    StorageReBean.setRoleName(roleNameList);
                }
            }
        }
        return CommonResult.data(TableDataInfo.build(StorageReBeanList));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<String> updateUserStorage(GetUserStorageDTO getUserStorageDTO) {
        // 校验是否有此用户的存储空间
        List<Long> userIdList = getUserStorageDTO.getUserIdList();
        if (userIdList == null || userIdList.size() == 0) {
            return CommonResult.error("用户ID不能为空");
        }
        try {
            for (Long userId : userIdList) {
                QueryWrapper<StorageReBean> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().eq(StorageReBean::getUserId, userId);
                StorageReBean StorageReBean = storageReMapper.selectOne(queryWrapper);
                if (StorageReBean != null) {
                    StorageReBean.setTotalStorageSize(getUserStorageDTO.getTotalStorageSize());
                    storageReMapper.updateById(StorageReBean);
                }
            }
        } catch (Exception ex) {
            log.error("更新用户存储空间失败", ex);
        }
        return CommonResult.ok("更新成功");
    }

    @Override
    public CommonResult<Long> getUserStorage() {
        // 获取当前用户id
        String userId = StpLoginUserUtil.getLoginUser().getId();
        QueryWrapper<StorageReBean> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(StorageReBean::getUserId, userId);
        StorageReBean StorageReBean = storageReMapper.selectOne(queryWrapper);
        if (StorageReBean != null) {
            return CommonResult.data(StorageReBean.getTotalStorageSize());
        } else {
            return CommonResult.error("未查询到用户存储空间");
        }
    }

    @Override
    public CommonResult<String> applyChangeStorage(CapacityReAuditInfo capacityReAuditInfo) {
        String userId = StpLoginUserUtil.getLoginUser().getId();
        // 校验是否有此用户的存储空间
        QueryWrapper<StorageReBean> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(StorageReBean::getUserId, userId);
        StorageReBean StorageReBean = storageReMapper.selectOne(queryWrapper);
        if (StorageReBean == null) {
            return CommonResult.error("未查询到用户存储空间");
        }
        // 校验是否已经提交过扩容申请
        QueryWrapper<CapacityReAuditInfo> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.lambda().eq(CapacityReAuditInfo::getApplicantUserId, userId).eq(CapacityReAuditInfo::getAuditState, 0);
        List<CapacityReAuditInfo> capacityAuditInfos = capacityReAuditInfoMapper.selectList(queryWrapper1);
        if (capacityAuditInfos != null && capacityAuditInfos.size() > 0) {
            return CommonResult.error("您已经提交过扩容申请，请耐心等待审核");
        }
        // 保存扩容申请信息
        capacityReAuditInfo.setId(IdUtil.simpleUUID()); // 主键id
        capacityReAuditInfo.setApplicantBeforeCapacity(StorageReBean.getTotalStorageSize()); // 扩容前容量
        capacityReAuditInfo.setApplicantUserId(userId); // 申请人id
        capacityReAuditInfo.setApplicantTime(new Date()); // 申请时间
        int insert = capacityReAuditInfoMapper.insert(capacityReAuditInfo);
        if (insert > 0) {
            return CommonResult.ok("扩容申请提交成功，请耐心等待审核");
        } else {
            return CommonResult.error("扩容申请提交失败");
        }
    }

    @Override
    public CommonResult<TableDataInfo<CapacityReAuditInfoVo>> getCapacityAuditList(Integer pageNum, Integer pageSize, Integer auditState, String usernameOrNickname) {
        // 查询审核列表
        PageQuery pageQuery = new PageQuery();
        pageQuery.setPageNum(pageNum);
        pageQuery.setPageSize(pageSize);
        Page<CapacityReAuditInfoVo> capacityAuditInfos = capacityReAuditInfoMapper.getCapacityAuditList(pageQuery.build(), auditState, usernameOrNickname);
        // 关联申请人的角色
        if (capacityAuditInfos.getRecords().size() > 0) {
            for (CapacityReAuditInfoVo record : capacityAuditInfos.getRecords()) {
                String userId = record.getApplicantUserId();
                List<String> roleNameList = storageReMapper.getUserRoleNameListById(userId);
                if (roleNameList != null && roleNameList.size() > 0) {
                    record.setRoles(roleNameList);
                }
            }
        }
        return CommonResult.data(TableDataInfo.build(capacityAuditInfos));
    }

    @Override
    public CommonResult<CapacityReAuditInfoVo> getCapacityAuditDetail(String id) {
        // 查询审核详情
        CapacityReAuditInfoVo capacityAuditInfo = capacityReAuditInfoMapper.getCapacityAuditById(id);
        if (capacityAuditInfo != null) {
            String userId = capacityAuditInfo.getApplicantUserId();
            List<String> roleNameList = storageReMapper.getUserRoleNameListById(userId);
            if (roleNameList != null && roleNameList.size() > 0) {
                capacityAuditInfo.setRoles(roleNameList);
            }
            return CommonResult.data(capacityAuditInfo);
        }
        return null;
    }

    @Override
    public CommonResult<String> auditCapacityAudit(String id, Integer auditState, String rejectReason) {
        // 校验申请单
        CapacityReAuditInfo capacityAuditInfo = capacityReAuditInfoMapper.selectById(id);
        if (capacityAuditInfo == null) {
            return CommonResult.error("扩容申请单不存在");
        }
        // 审核扩容申请
        capacityAuditInfo.setAuditState(auditState);
        if (auditState == 1) { // 通过审核
            // 更新用户存储空间
            QueryWrapper<StorageReBean> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(StorageReBean::getUserId, capacityAuditInfo.getApplicantUserId());
            StorageReBean StorageReBean = storageReMapper.selectOne(queryWrapper);
            StorageReBean.setTotalStorageSize(capacityAuditInfo.getApplicantAfterCapacity());
            int update = storageReMapper.updateById(StorageReBean);
            if (update > 0) {
                // 修改审核状态
                capacityAuditInfo.setAuditTime(new Date());
                capacityAuditInfo.setAuditUserId(StpLoginUserUtil.getLoginUser().getId());
                capacityReAuditInfoMapper.updateById(capacityAuditInfo);
                return CommonResult.ok("扩容申请通过，已更新用户存储空间");
            } else {
                return CommonResult.error("扩容申请通过失败");
            }
        } else if (auditState == 2) { // 拒绝审核
            capacityAuditInfo.setRejectReason(rejectReason); // 拒绝原因
            int update = capacityReAuditInfoMapper.updateById(capacityAuditInfo);
            if (update > 0) {
                return CommonResult.ok("扩容申请驳回成功");
            } else {
                return CommonResult.error("扩容申请驳回失败");
            }
        } else {
            return CommonResult.error("审核状态不正确，请重新选择");
        }
    }

    @Override
    public CommonResult<TableDataInfo<CapacityReAuditInfoVo>> getUserCapacityAuditList(Integer pageNum, Integer pageSize, Integer auditState) {
        // 查询审核列表
        PageQuery pageQuery = new PageQuery();
        pageQuery.setPageNum(pageNum);
        pageQuery.setPageSize(pageSize);
        String id = StpLoginUserUtil.getLoginUser().getId();
        Page<CapacityReAuditInfoVo> capacityAuditInfos = capacityReAuditInfoMapper.getUserCapacityAuditList(pageQuery.build(), auditState, id);
        // 关联申请人的角色
        if (capacityAuditInfos.getRecords().size() > 0) {
            for (CapacityReAuditInfoVo record : capacityAuditInfos.getRecords()) {
                String userId = record.getApplicantUserId();
                List<String> roleNameList = storageReMapper.getUserRoleNameListById(userId);
                if (roleNameList != null && roleNameList.size() > 0) {
                    record.setRoles(roleNameList);
                }
            }
        }
        return CommonResult.data(TableDataInfo.build(capacityAuditInfos));
    }

}
