package org.wcs.serve.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.wcs.factory.AppServeResponseFactory;
import org.wcs.mapper.intf.AppBaseGroupPermissionService;
import org.wcs.mapper.intf.AppBaseMenuService;
import org.wcs.mapper.intf.AppBaseUserGroupService;
import org.wcs.mapper.intf.AppBaseUserService;
import org.wcs.model.dto.serve.userGroup.AddUserGroupReq;
import org.wcs.model.dto.serve.userGroup.UpdateGroupPermissionReq;
import org.wcs.model.dto.serve.userGroup.UpdateUserGroupReq;
import org.wcs.model.po.app.*;
import org.wcs.model.vo.serve.AppServeDataResponse;
import org.wcs.model.vo.serve.AppServeResponse;
import org.wcs.model.vo.serve.userGroup.QueryUserGroupPermissionResp;
import org.wcs.model.vo.serve.userGroup.QueryUserGroupResp;
import org.wcs.serve.service.intf.IUserGroupService;
import org.wcs.utils.AppBeanUtils;
import org.wcs.utils.AppDataBaseTransUtils;
import org.wcs.utils.AppStringUtils;
import org.wcs.utils.AppUUIDUtils;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class UserGroupService implements IUserGroupService {

    private final AppDataBaseTransUtils appDataBaseTransUtils;
    private final AppBaseGroupPermissionService baseGroupPermissionService;
    private final AppBaseUserService baseUserService;
    private final AppBaseUserGroupService baseUserGroupService;
    private final AppBaseMenuService baseMenuService;

    /**
     * 查询用户组级别比自己低的用户组
     * @return 查询到的用户组
     */
    @Override
    public AppServeDataResponse<List<QueryUserGroupResp>> queryMinLevelUserGroup() {
        Object userIdObj = StpUtil.getLoginId();
        if(userIdObj == null) {
            return AppServeResponseFactory.unauthorized("用户未登录", null);
        }
        String userId = userIdObj.toString();
        List<JoinUserInfoWithGroupInfo> users = baseUserService.query(userId);
        if(users == null) {
            return AppServeResponseFactory.internalServerError("数据服务异常", null);
        }
        if(users.isEmpty()) {
            return AppServeResponseFactory.fail("您的用户组没有启用或者没有相关用户组，联系管理员", null);
        }
        JoinUserInfoWithGroupInfo user = users.getFirst();
        List<AppBaseUserGroup> appBaseUserGroups = baseUserGroupService.queryWithLevelMin(user.getGroupLevel());
        if(appBaseUserGroups == null) {
            return AppServeResponseFactory.internalServerError("数据服务异常", null);
        }
        List<QueryUserGroupResp> queryUserGroupResponse = appBaseUserGroups.stream().map(appBaseUserGroup -> {
            QueryUserGroupResp queryUserGroupResp = new QueryUserGroupResp();
            queryUserGroupResp.setUserGroup(appBaseUserGroup.getUserGroup());
            queryUserGroupResp.setGroupName(appBaseUserGroup.getGroupName());
            queryUserGroupResp.setGroupLevel(appBaseUserGroup.getGroupLevel());
            queryUserGroupResp.setGroupStatus(appBaseUserGroup.getGroupStatus());
            queryUserGroupResp.setCreateTime(appBaseUserGroup.getCreateTime());
            queryUserGroupResp.setUpdateTime(appBaseUserGroup.getUpdateTime());
            return queryUserGroupResp;
        }).toList();
        return AppServeResponseFactory.success(queryUserGroupResponse);
    }

    /**
     * 查询用户组权限
     * @param userGroup 用户组
     * @return 查询结果
     */
    @Override
    public AppServeDataResponse<List<QueryUserGroupPermissionResp>> queryUserGroupPermission(String userGroup) {
        List<AppBaseMenu> menuList = baseMenuService.queryPermission(userGroup);
        if(menuList == null) {
            return AppServeResponseFactory.internalServerError("数据服务异常", null);
        }
        if(menuList.isEmpty()) {
            return AppServeResponseFactory.fail("用户权限不足，请联系管理员查看是否授予您访问资源的权限", null);
        }
        List<QueryUserGroupPermissionResp> returnMenuList = AppBeanUtils.copyListProperties(menuList, QueryUserGroupPermissionResp::new);
        return AppServeResponseFactory.success(returnMenuList);
    }

    /**
     * 添加用户组
     * @param addUserGroupReq 新用户组参数
     * @return 结果
     */
    @Override
    public AppServeResponse addUserGroup(AddUserGroupReq addUserGroupReq) {
        Object userIdObj = StpUtil.getLoginId();
        if(userIdObj == null) {
            return AppServeResponseFactory.unauthorized("用户未登录");
        }
        String userId = userIdObj.toString();
        AppBaseUserGroup appBaseUserGroup = new AppBaseUserGroup();
        appBaseUserGroup.setUserGroup("ug-" + addUserGroupReq.getUserGroup());
        appBaseUserGroup.setGroupName(addUserGroupReq.getGroupName());
        appBaseUserGroup.setGroupLevel(addUserGroupReq.getGroupLevel());
        appBaseUserGroup.setGroupStatus(addUserGroupReq.getGroupStatus());
        int insertResult = baseUserGroupService.insert(appBaseUserGroup);
        if(insertResult <= 0) {
            return AppServeResponseFactory.fail("添加用户组失败");
        }
        log.info("用户：{} 添加用户组：{}", userId, AppStringUtils.objectToString(addUserGroupReq));
        return AppServeResponseFactory.success("添加用户组成功");
    }

    /**
     * 删除用户组
     * @param userGroup 用户组名称
     * @return 结果
     */
    @Override
    public AppServeResponse deleteUserGroup(String userGroup) {
        Object userIdObj = StpUtil.getLoginId();
        if(userIdObj == null) {
            return AppServeResponseFactory.unauthorized("用户未登录");
        }
        String userId = userIdObj.toString();
        if(appDataBaseTransUtils.useTran(() -> {
            baseGroupPermissionService.deleteByUserGroupThrowException(userGroup); // 删除用户组的权限
            baseUserGroupService.deleteByUserGroupThrowException(userGroup); // 删除用户组
        })) {
            log.info("用户：{} 删除用户组：{}", userId, userGroup);
            return AppServeResponseFactory.success("删除用户组成功");
        }
        return AppServeResponseFactory.fail("删除用户组失败，事务处理失败");
    }

    /**
     * 修改用户组
     * @param updateUserGroupReq 修改用户组参数
     * @return 修改结果
     */
    @Override
    public AppServeResponse updateUserGroup(UpdateUserGroupReq updateUserGroupReq) {
        Object userIdObj = StpUtil.getLoginId();
        if(userIdObj == null) {
            return AppServeResponseFactory.unauthorized("用户未登录");
        }
        String userId = userIdObj.toString();
        AppBaseUserGroup appBaseUserGroup = new AppBaseUserGroup();
        AppBeanUtils.copyProperties(updateUserGroupReq, appBaseUserGroup);
        int update = baseUserGroupService.update(appBaseUserGroup);
        if(update == 0) {
            return AppServeResponseFactory.internalServerError("数据服务异常");
        }
        log.info("用户 {} 修改了用户组 {}", userId, AppStringUtils.objectToString(updateUserGroupReq));
        return AppServeResponseFactory.success(String.format("更新成功，更新了 %d 条记录", update));
    }

    /**
     * 更新用户的权限
     * @param updateGroupPermissionReq 更新信息
     * @return 更新结果
     */
    @Override
    public AppServeResponse updateGroupPermission(UpdateGroupPermissionReq updateGroupPermissionReq) {
        Object userIdObj = StpUtil.getLoginId();
        if(userIdObj == null) {
            return AppServeResponseFactory.unauthorized("用户未登录");
        }
        String userId = userIdObj.toString();
        List<AppBaseGroupPermission> appBaseGroupPermissionList = new ArrayList<>();
        for(String permission : updateGroupPermissionReq.getPermissionList()) {
            AppBaseGroupPermission appBaseGroupPermission = new AppBaseGroupPermission();
            appBaseGroupPermission.setId(AppUUIDUtils.getNewUUID());
            appBaseGroupPermission.setUserGroup(updateGroupPermissionReq.getUserGroup());
            appBaseGroupPermission.setMenuId(permission);
            appBaseGroupPermission.setCreateUser(userId);
            appBaseGroupPermissionList.add(appBaseGroupPermission);
        }
        if(appDataBaseTransUtils.useTran(() -> {
            baseGroupPermissionService.deleteByUserGroupThrowException(updateGroupPermissionReq.getUserGroup());
            baseGroupPermissionService.insertThrowException(appBaseGroupPermissionList);
        })) {
            log.info("用户 {} 更新了用户组 {} 的权限", userId, updateGroupPermissionReq.getUserGroup());
            return AppServeResponseFactory.success("权限更新成功");
        }
        return AppServeResponseFactory.fail("权限更新失败，事务处理失败");
    }
}
