package com.zxdmy.excite.system.service.impl.cloud.role;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zxdmy.excite.common.entity.PageList;
import com.zxdmy.excite.common.enums.SystemCode;
import com.zxdmy.excite.common.exception.ServiceException;
import com.zxdmy.excite.system.entity.SysRole;
import com.zxdmy.excite.system.entity.SysUser;
import com.zxdmy.excite.system.entity.SysUserRole;
import com.zxdmy.excite.system.entity.cloud.role.CloudRole;
import com.zxdmy.excite.system.entity.cloud.role.CloudRoleFile;
import com.zxdmy.excite.system.entity.cloud.role.CloudRoleUser;
import com.zxdmy.excite.system.entity.cloud.space.CloudFileRole;
import com.zxdmy.excite.system.entity.req.role.ReqRole;
import com.zxdmy.excite.system.entity.vo.role.RoleVo;
import com.zxdmy.excite.system.mapper.SysUserMapper;
import com.zxdmy.excite.system.mapper.cloud.role.CloudRoleFileMapper;
import com.zxdmy.excite.system.mapper.cloud.role.CloudRoleMapper;
import com.zxdmy.excite.system.service.cloud.role.ICloudRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zxdmy.excite.system.service.cloud.role.ICloudRoleUserService;
import com.zxdmy.excite.system.service.cloud.space.ICloudFileRoleService;
import com.zxdmy.excite.system.utils.AuthUtils;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

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

/**
 * <p>
 * 云盘权限表 服务实现类
 * </p>
 *
 * @author ss
 * @since 2026-01-27
 */
@Service
@AllArgsConstructor
public class CloudRoleServiceImpl extends ServiceImpl<CloudRoleMapper, CloudRole> implements ICloudRoleService {
    private CloudRoleMapper cloudRoleMapper;
    private SysUserMapper sysUserMapper;
    private ICloudRoleUserService iCloudRoleUserService;
    private CloudRoleFileMapper cloudRoleFileMapper;
    private ICloudFileRoleService iCloudFileRoleService;

    @Override
    public PageList<RoleVo> queryByPage(Integer page, Integer limit, ReqRole data) {
        Integer pages = limit * (page - 1);
        ArrayList<RoleVo> list = cloudRoleMapper.queryByPage(pages, limit,data);
        Integer count = cloudRoleMapper.queryByPageCount(data);
        return new PageList<RoleVo>(list,page,limit,count);
    }

    @Override
    public RoleVo getByData(ReqRole data) {
        return cloudRoleMapper.getData(data);
    }

    @Override
    public int saveData(ReqRole data) {
        LocalDateTime localDateTime = LocalDateTime.now();
        CloudRole saveData = new CloudRole();
        saveData.setRoleName(data.getRoleName());
        SysUser sysUser = sysUserMapper.selectById(StpUtil.getLoginIdAsInt());
        saveData.setRoleDown(data.getRoleDown());
        saveData.setRoleUpload(data.getRoleUpload());
        saveData.setCreatorId(sysUser.getId());
        saveData.setCreatorName(sysUser.getUsername());
        saveData.setCreateTime(localDateTime);
        if(cloudRoleMapper.insert(saveData)==1){

            for (String fileId:data.getIds()) {
                CloudRoleFile cloudRoleFile = new CloudRoleFile();
                cloudRoleFile.setFileId(Long.valueOf(fileId));
                cloudRoleFile.setRoleId(saveData.getId());
                cloudRoleFileMapper.insert(cloudRoleFile);
            }

            return 1;
        }
        return 0;
    }

    @Override
    public int updateData(ReqRole data) {
        CloudRole updateData = new CloudRole();
        updateData.setId(Long.valueOf(data.getId()));
        updateData.setRoleName(data.getRoleName());
        updateData.setRoleDown(data.getRoleDown());
        updateData.setRoleUpload(data.getRoleUpload());
        if(cloudRoleMapper.updateById(updateData)==1){

            QueryWrapper<CloudRoleFile> wrapper = new QueryWrapper<>();
            wrapper.eq("role_id",updateData.getId());
            List<CloudRoleFile> list = cloudRoleFileMapper.selectList(wrapper);
            for (CloudRoleFile cloudRoleFile:list) {
                cloudRoleFileMapper.deleteById(cloudRoleFile.getId());
            }


            for (String fileId:data.getIds()) {
                CloudRoleFile cloudRoleFile = new CloudRoleFile();
                cloudRoleFile.setFileId(Long.valueOf(fileId));
                cloudRoleFile.setRoleId(updateData.getId());
                cloudRoleFileMapper.insert(cloudRoleFile);
            }


            return 1;
        }
        return 0;
    }

    @Override
    public int deleteById(String id) {
        if (null == id) {
            throw new ServiceException("删除的ID不能为空！");
        }
        LocalDateTime localDateTime = LocalDateTime.now();
        SysUser sysUser = sysUserMapper.selectById(StpUtil.getLoginIdAsInt());
        CloudRole data = cloudRoleMapper.selectById(id);
        if(null!=data){
            data.setDeleteId(sysUser.getId());
            data.setDeleteName(sysUser.getUsername());
            data.setDeleteTime(localDateTime);
            return cloudRoleMapper.updateById(data);
        }else{
            return 0;
        }
    }

    @Override
    public List<RoleVo> queryByData() {
        return cloudRoleMapper.queryByData();
    }


    @Override
    public int[] changeUploadStatus(Integer newStatus, String[] ids) {
        /// 信息不能为空
        if (null == newStatus || null == ids) {
            throw new ServiceException("新状态或ID不能为空");
        }
        // 新状态只能为 0 | 1
        if (newStatus == 0 || newStatus == 1) {
            int[] result = new int[2];
            for (String id : ids) {
                CloudRole data = cloudRoleMapper.selectById(id);
                data.setRoleUpload(newStatus);
                if (cloudRoleMapper.updateById(data) > 0) {
                    result[0]++;
                } else result[1]++;
            }
            // 返回结果
            return result;
        } else {
            throw new ServiceException("新状态只能为0或1！");
        }
    }
    @Override
    public int[] changeDownStatus(Integer newStatus, String[] ids) {
        /// 信息不能为空
        if (null == newStatus || null == ids) {
            throw new ServiceException("新状态或ID不能为空");
        }
        // 新状态只能为 0 | 1
        if (newStatus == 0 || newStatus == 1) {
            int[] result = new int[2];
            for (String id : ids) {
                CloudRole data = cloudRoleMapper.selectById(id);
                data.setRoleDown(newStatus);
                if (cloudRoleMapper.updateById(data) > 0) {
                    result[0]++;
                } else result[1]++;
            }
            // 返回结果
            return result;
        } else {
            throw new ServiceException("新状态只能为0或1！");
        }
    }
    @Override
    public int[] changeDeleteStatus(Integer newStatus, String[] ids) {
        /// 信息不能为空
        if (null == newStatus || null == ids) {
            throw new ServiceException("新状态或ID不能为空");
        }
        // 新状态只能为 0 | 1
        if (newStatus == 0 || newStatus == 1) {
            int[] result = new int[2];
            for (String id : ids) {
                CloudRole data = cloudRoleMapper.selectById(id);
                data.setRoleDelete(newStatus);
                if (cloudRoleMapper.updateById(data) > 0) {
                    result[0]++;
                } else result[1]++;
            }
            // 返回结果
            return result;
        } else {
            throw new ServiceException("新状态只能为0或1！");
        }
    }
    @Override
    public boolean authRoleForUsers(String roleId, String[] userIds) {
        // 如果用户列表为空，则直接返回真即可
        if (null == userIds || userIds.length == 0) {
            return true;
        }
        // 存储列表
        List<CloudRoleUser> userRoleList = new ArrayList<>();
        for (String userId : userIds) {
            // 构造数据，并添加至列表
            CloudRoleUser userRole = new CloudRoleUser();
            userRole.setRoleId(Long.valueOf(roleId));
            userRole.setUserId(Integer.valueOf(userId));
            userRoleList.add(userRole);

            QueryWrapper<CloudRoleFile> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("role_id",roleId);
            List<CloudRoleFile> fileList = cloudRoleFileMapper.selectList(wrapper1);
            List<CloudFileRole> fileRoleList = new ArrayList<>();
            for (CloudRoleFile cloudRoleFile:fileList) {
                CloudFileRole cloudFileRole = new CloudFileRole();
                cloudFileRole.setFileId(cloudRoleFile.getFileId());
                cloudFileRole.setUserId(Integer.valueOf(userId));
                fileRoleList.add(cloudFileRole);
            }
            iCloudFileRoleService.saveBatch(fileRoleList);
        }
        // 执行插入
        if (iCloudRoleUserService.saveBatch(userRoleList)) {
            return true;
        } else
            return false;

    }

    @Override
    public int[] revokeRoleForUsers(String roleId, String[] userIds) {
        if (null == userIds || userIds.length == 0) {
            return new int[]{0, 0};
        }
        int[] result = new int[2];
        // 遍历用户列表，逐个删除
        for (String userId : userIds) {
            QueryWrapper<CloudRoleUser> wrapper = new QueryWrapper<>();
            wrapper.eq("role_id", roleId).eq("user_id", userId);
            // TODO 完善：超级管理员不允许取消授权！
            if (iCloudRoleUserService.remove(wrapper)) {

                QueryWrapper<CloudRoleFile> wrapper1 = new QueryWrapper<>();
                wrapper1.eq("role_id",roleId);
                List<CloudRoleFile> fileList = cloudRoleFileMapper.selectList(wrapper1);
                for (CloudRoleFile cloudRoleFile:fileList) {

                    QueryWrapper<CloudFileRole> wrapper2 = new QueryWrapper<>();
                    wrapper2.eq("file_id", cloudRoleFile.getFileId());
                    wrapper2.eq("user_id", userId);
                    iCloudFileRoleService.remove(wrapper2);
                }

                result[0]++;
            } else
                result[1]++;
        }
        return result;
    }

    @Override
    public List<CloudRole> getListByUserId(Integer userId) {
        // 查询status正常的角色
        QueryWrapper<CloudRole> wrapper = new QueryWrapper<>();
        wrapper.isNull("delete_time");
        // 如果userId为0，则表示获取全部角色
        if (userId == 0) {
            return cloudRoleMapper.selectList(wrapper);
        }
        // 否则，获取角色后，将该用户已分配的角色checkArr设置为1
        else {
            // 获取全部正常角色
            List<CloudRole> roleList = cloudRoleMapper.selectList(wrapper);
            // 获取当前用户拥有的角色ID列表
            List<Long> userRoleList = iCloudRoleUserService.getListByUserId(userId).stream().map(CloudRoleUser::getRoleId).collect(Collectors.toList());
            // 使用lambda表达式，直接在角色列表上修改checkArr字段
            return roleList.stream().peek(
                    role -> {
                        if (userRoleList.contains(role.getId())) {
                            role.setCheckArr("1");
                            role.setLAY_CHECKED(true);
                        }
                    }
            ).collect(Collectors.toList());
        }
    }
}
