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.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qiwenshare.common.result.RestResult;
import org.apache.commons.lang3.StringUtils;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.common.pojo.CommonResult;
import vip.xiaonuo.disk.domain.CapacityAuditInfo;
import vip.xiaonuo.disk.dto.storage.GetUserStorageDTO;
import vip.xiaonuo.disk.mapper.CapacityAuditInfoMapper;
import vip.xiaonuo.disk.service.IStorageService;
import vip.xiaonuo.disk.domain.StorageBean;
import vip.xiaonuo.disk.domain.SysParam;
import vip.xiaonuo.disk.mapper.StorageMapper;
import vip.xiaonuo.disk.mapper.SysParamMapper;
import vip.xiaonuo.disk.mapper.UserFileMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.disk.util.PageQuery;
import vip.xiaonuo.disk.util.TableDataInfo;
import vip.xiaonuo.disk.vo.storage.CapacityAuditInfoVo;
import vip.xiaonuo.disk.vo.storage.StorageBeanVO;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
@Transactional(rollbackFor=Exception.class)
public class StorageService extends ServiceImpl<StorageMapper, StorageBean> implements IStorageService {
    @Resource
    StorageMapper storageMapper;
    @Resource
    SysParamMapper sysParamMapper;
    @Resource
    UserFileMapper userFileMapper;

    @Resource
    private CapacityAuditInfoMapper capacityAuditInfoMapper;


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

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

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

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

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

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

        Long storageSize = userFileMapper.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<StorageBeanVO>> getUserStorageList(GetUserStorageDTO getUserStorageDTO) {
        PageQuery pageQuery = new PageQuery();
        pageQuery.setPageNum(getUserStorageDTO.getPageNum());
        pageQuery.setPageSize(getUserStorageDTO.getPageSize());
        Page<StorageBeanVO> storageBeanList = storageMapper.getUserStorageList(pageQuery.build(), getUserStorageDTO);
        if (storageBeanList.getRecords() != null && storageBeanList.getSize() > 0) {
            // 如果查出的数据不为空，关联用户的角色
            for (StorageBeanVO storageBean : storageBeanList.getRecords()) {
                String userId = storageBean.getUserId();
                List<String> roleNameList = storageMapper.getUserRoleNameListById(userId);
                if (roleNameList != null && roleNameList.size() > 0) {
                    storageBean.setRoleName(roleNameList);
                }
            }
        }
        return CommonResult.data(TableDataInfo.build(storageBeanList));
    }

    @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<StorageBean> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().eq(StorageBean::getUserId, userId);
                StorageBean storageBean = storageMapper.selectOne(queryWrapper);
                if (storageBean != null) {
                    storageBean.setTotalStorageSize(getUserStorageDTO.getTotalStorageSize());
                    storageMapper.updateById(storageBean);
                }
            }
        } catch (Exception ex) {
            log.error("更新用户存储空间失败", ex);
        }
        return CommonResult.ok("更新成功");
    }

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

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

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

    @Override
    public CommonResult<CapacityAuditInfoVo> getCapacityAuditDetail(String id) {
        // 查询审核详情
        CapacityAuditInfoVo capacityAuditInfo = capacityAuditInfoMapper.getCapacityAuditById(id);
        if (capacityAuditInfo != null) {
            String userId = capacityAuditInfo.getApplicantUserId();
            List<String> roleNameList = storageMapper.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) {
        // 校验申请单
        CapacityAuditInfo capacityAuditInfo = capacityAuditInfoMapper.selectById(id);
        if (capacityAuditInfo == null) {
            return CommonResult.error("扩容申请单不存在");
        }
        // 审核扩容申请
        capacityAuditInfo.setAuditState(auditState);
        if (auditState == 1) { // 通过审核
            // 更新用户存储空间
            QueryWrapper<StorageBean> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(StorageBean::getUserId, capacityAuditInfo.getApplicantUserId());
            StorageBean storageBean = storageMapper.selectOne(queryWrapper);
            storageBean.setTotalStorageSize(capacityAuditInfo.getApplicantAfterCapacity());
            int update = storageMapper.updateById(storageBean);
            if (update > 0) {
                // 修改审核状态
                capacityAuditInfo.setAuditTime(new Date());
                capacityAuditInfo.setAuditUserId(StpLoginUserUtil.getLoginUser().getId());
                capacityAuditInfoMapper.updateById(capacityAuditInfo);
                return CommonResult.ok("扩容申请通过，已更新用户存储空间");
            } else {
                return CommonResult.error("扩容申请通过失败");
            }
        } else if (auditState == 2) { // 拒绝审核
            capacityAuditInfo.setRejectReason(rejectReason); // 拒绝原因
            int update = capacityAuditInfoMapper.updateById(capacityAuditInfo);
            if (update > 0) {
                return CommonResult.ok("扩容申请驳回成功");
            } else {
                return CommonResult.error("扩容申请驳回失败");
            }
        } else {
            return CommonResult.error("审核状态不正确，请重新选择");
        }
    }

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


}
