/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.disk.controller;

import cn.hutool.core.collection.CollStreamUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import vip.xiaonuo.auth.core.enums.SysUserStatusEnum;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.common.annotation.CommonLog;
import vip.xiaonuo.common.pojo.CommonResult;
import vip.xiaonuo.common.pojo.CommonValidList;
import vip.xiaonuo.common.util.CommonAvatarUtil;
import vip.xiaonuo.common.util.CommonCryptogramUtil;
import vip.xiaonuo.common.util.PinyinUtils;
import vip.xiaonuo.dev.api.DevConfigApi;
import vip.xiaonuo.disk.dto.shareGroupuser.*;
import vip.xiaonuo.disk.service.ShareGroupUserService;
import vip.xiaonuo.sys.modular.relation.enums.SysRelationCategoryEnum;
import vip.xiaonuo.sys.modular.relation.service.SysRelationService;
import vip.xiaonuo.sys.modular.user.entity.SysUser;
import vip.xiaonuo.sys.modular.user.service.SysUserService;
import vip.xiaonuo.sys.modular.user.service.impl.SysUserServiceImpl;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 资源共享-群组控制器
 *
 * @author honorfire
 * @date  2025/06/18 14:16
 */
@Api(tags = "资源共享-群组控制器")
@ApiSupport(author = "SNOWY_TEAM", order = 1)
@RestController
@Validated
public class ShareGroupController {

    @Resource
    private ShareGroupUserService shareGroupUserService;
    @Resource
    private DevConfigApi devConfigApi;
    @Resource
    private PinyinUtils pinyinUtils;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysRelationService sysRelationService;

    private static final String SNOWY_SYS_DEFAULT_PASSWORD_KEY = SysUserServiceImpl.SNOWY_SYS_DEFAULT_PASSWORD_KEY;

    /**
     * 资源共享-群组-分页列表
     *
     * @author honorfire
     * @date  2025/06/18 14:16
     */
    @ApiOperationSupport(order = 1)
    @ApiOperation("资源共享-群组-分页列表")
//    @SaCheckPermission("/disk/sharegroup/page")
    @GetMapping("/disk/sharegroup/page")
    public CommonResult<Page<Map<String,Object>>> page(ShareGroupUserPageParam shareGroupUserPageParam, HttpServletRequest req) {
        Map param =new HashMap();
        param.put("userId", StpLoginUserUtil.getLoginUser().getId());
        Page<Map<String,Object>> groupList=sysUserService.getGroupList(param);
        return CommonResult.data(groupList);
    }

    /**
     * 资源共享-群组-新增
     *
     * @author honorfire
     * @date  2025/06/18 14:16
     */
    @ApiOperationSupport(order = 2)
    @ApiOperation("资源共享-群组-新增")
    @CommonLog("资源共享-群组-新增")
//    @SaCheckPermission("/disk/sharegroup/add")
    @PostMapping("/disk/sharegroup/add")
    public CommonResult<String> add(@RequestBody @Valid ShareGroupAddParam shareGroupAddParam) {
        //1.先创建一个角色为群组的用户
        SysUser groupUser = new SysUser();
        groupUser.setName(shareGroupAddParam.getName());
        //设置账号，账号采取文字拼音加时间戳
        String groupUserAccount=pinyinUtils.toFirstLetters(shareGroupAddParam.getName())+System.currentTimeMillis();
        groupUser.setAccount(groupUserAccount);
        //设置群组默认组织、职位
        groupUser.setOrgId("100");
        groupUser.setPositionId("100");
        //资源库专用账号
        groupUser.setIsResourceaccount("1");
        // 设置默认头像
        groupUser.setAvatar(CommonAvatarUtil.generateImg(groupUser.getName()));
        // 设置默认密码
        groupUser.setPassword(CommonCryptogramUtil.doHashValue(devConfigApi.getValueByKey(SNOWY_SYS_DEFAULT_PASSWORD_KEY)));
        // 设置状态
        groupUser.setUserStatus(SysUserStatusEnum.ENABLE.getValue());
        //先保存一下该群组”用户“
        groupUser=sysUserService.addOne(groupUser);

        //2.存入该群组”用户“特定职务
        sysRelationService.saveRelationWithAppend(groupUser.getId(),"101",SysRelationCategoryEnum.SYS_USER_HAS_ROLE.getValue());

        //3.存入群组关系
        String userIdsStr=shareGroupAddParam.getUserIds();
        String[] userIdList = userIdsStr.split(",");
        List<ShareGroupUser> shareGroupUserList=new ArrayList<>();
        //首先添加创建群组的人
        ShareGroupUser ownGroupUser=new ShareGroupUser();
        ownGroupUser.setUserId(StpLoginUserUtil.getLoginUser().getId());
        ownGroupUser.setGroupId(groupUser.getId());
        ownGroupUser.setIsCreater("1");
        shareGroupUserList.add(ownGroupUser);
        for(String userId:userIdList)
        {
            ShareGroupUser otherGroupUser=new ShareGroupUser();
            otherGroupUser.setUserId(userId);
            otherGroupUser.setGroupId(groupUser.getId());
            otherGroupUser.setIsCreater("0");
            shareGroupUserList.add(otherGroupUser);
        }

        shareGroupUserService.addBatch(shareGroupUserList);
        return CommonResult.ok();
    }

    /**
     * 资源共享-群组-编辑
     *
     * @author honorfire
     * @date  2025/06/18 14:16
     */
    @ApiOperationSupport(order = 3)
    @ApiOperation("资源共享-群组-编辑")
    @CommonLog("资源共享-群组-编辑")
//    @SaCheckPermission("/disk/sharegroup/edit")
    @PostMapping("/disk/sharegroup/edit")
    public CommonResult<String> edit(@RequestBody @Valid ShareGroupEditParam shareGroupEditParam) {
        //1.先创建一个角色为群组的用户
        SysUser groupUser = new SysUser();
        if(StringUtils.isNotEmpty(shareGroupEditParam.getName()))
        {
            groupUser.setName(shareGroupEditParam.getName());
            //设置账号，账号采取文字拼音加时间戳
            String groupUserAccount=pinyinUtils.toFirstLetters(shareGroupEditParam.getName())+System.currentTimeMillis();
        }
        //先保存一下该群组”用户“
        groupUser=sysUserService.editOne(groupUser);

        //2.群组用户id不为空的情况，删除旧群组关系，重新存入
        List<ShareGroupUser> shareGroupUserList=new ArrayList<>();
        if(StringUtils.isNotEmpty(shareGroupEditParam.getUserIds()))
        {
            //删除旧群组id
            //查询旧关联id
            Map queryDeleteGroupUserMap=new HashMap();
            queryDeleteGroupUserMap.put("groupId",groupUser.getId());
            List<Map<String, Object>> groupUserList= shareGroupUserService.queryGroupUserList(queryDeleteGroupUserMap);
            List<String> deleteGroupUserIdList=new ArrayList<>();
            for(Map<String, Object> deleteGroupUser:groupUserList)
            {
                deleteGroupUserIdList.add(deleteGroupUser.get("groupUserId").toString());
            }
            shareGroupUserService.deleteByIds(deleteGroupUserIdList);

            //重新存入群组关系
            String userIdsStr=shareGroupEditParam.getUserIds();
            String[] userIdList = userIdsStr.split(",");
            //首先添加创建群组的人
            ShareGroupUser ownGroupUser=new ShareGroupUser();
            ownGroupUser.setUserId(StpLoginUserUtil.getLoginUser().getId());
            ownGroupUser.setGroupId(groupUser.getId());
            ownGroupUser.setIsCreater("1");
            shareGroupUserList.add(ownGroupUser);
            for(String userId:userIdList)
            {
                ShareGroupUser otherGroupUser=new ShareGroupUser();
                otherGroupUser.setUserId(userId);
                otherGroupUser.setGroupId(groupUser.getId());
                otherGroupUser.setIsCreater("0");
                shareGroupUserList.add(otherGroupUser);
            }
        }

        shareGroupUserService.addBatch(shareGroupUserList);
        return CommonResult.ok();
    }

    /**
     * 资源共享-群组-删除
     *
     * @author honorfire
     * @date  2025/06/18 14:16
     */
    @ApiOperationSupport(order = 4)
    @ApiOperation("资源共享-群组-删除")
    @CommonLog("资源共享-群组-删除")
//    @SaCheckPermission("/disk/sharegroup/delete")
    @PostMapping("/disk/sharegroup/delete")
    public CommonResult<String> delete(@RequestBody @Valid @NotEmpty(message = "集合不能为空")
                                                   CommonValidList<ShareGroupIdParam> shareGroupIdParamList) {
        List<String> groupIdList = CollStreamUtil.toList(shareGroupIdParamList, ShareGroupIdParam::getGroupId);
        sysUserService.deleteByIds(groupIdList);
        return CommonResult.ok();
    }

    /**
     * 资源共享-群组-详情
     *
     * @author honorfire
     * @date  2025/06/18 14:16
     */
    @ApiOperationSupport(order = 5)
    @ApiOperation("资源共享-群组-详情")
//    @SaCheckPermission("/disk/sharegroup/detail")
    @GetMapping("/disk/sharegroup/detail")
    public CommonResult<Map<String,Object>> detail(@Valid ShareGroupIdParam shareGroupIdParam) {
        Map param=new HashMap();
        Map<String,Object> result= new HashMap<>();
        //查回群组基本信息
        SysUser group=sysUserService.queryEntity(shareGroupIdParam.getGroupId());
        result.put("groupId",group.getId());
        result.put("groupName",group.getName());
        result.put("groupAccount",group.getAccount());
        //查回群组所有关联人员
        Map queryGroupUserMap=new HashMap();
        queryGroupUserMap.put("groupId",group);
        List<Map<String, Object>> groupUserList= shareGroupUserService.queryGroupUserList(queryGroupUserMap);
        result.put("groupUserList",groupUserList);

        return CommonResult.data(result);
    }

}
