package com.yonge.cooleshow.student.controller;


import com.alibaba.fastjson.JSON;
import com.yonge.cooleshow.auth.api.client.SysUserFeignService;
import com.yonge.cooleshow.auth.api.entity.SysUser;
import com.yonge.cooleshow.biz.dal.dto.ImGroupResultDto;
import com.yonge.cooleshow.biz.dal.dto.ImGroupSearchDto;
import com.yonge.cooleshow.biz.dal.entity.ImGroup;
import com.yonge.cooleshow.biz.dal.entity.ImGroupMember;
import com.yonge.cooleshow.biz.dal.entity.ImUserFriend;
import com.yonge.cooleshow.biz.dal.enums.ClientEnum;
import com.yonge.cooleshow.biz.dal.enums.ImGroupMemberRoleType;
import com.yonge.cooleshow.biz.dal.enums.MK;
import com.yonge.cooleshow.biz.dal.service.ImGroupMemberService;
import com.yonge.cooleshow.biz.dal.service.ImGroupService;
import com.yonge.cooleshow.biz.dal.service.ImUserFriendService;
import com.yonge.cooleshow.biz.dal.service.SysUserService;
import com.yonge.cooleshow.biz.dal.vo.im.ImUserFriendVO;
import com.yonge.cooleshow.common.controller.BaseController;
import com.yonge.cooleshow.common.entity.HttpResponseResult;
import com.yonge.toolset.utils.validator.ValidationKit;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.Objects;

/**
 * 即时通讯群组(ImGroup)表控制层
 *
 * @author zx
 * @since 2022-03-22 10:45:56
 */
@Api(tags = "即时通讯群组")
@RestController
@RequestMapping("${app-config.url.student:}/imGroup")
public class ImGroupController extends BaseController {
    /**
     * 服务对象
     */
    @Resource
    private ImGroupService imGroupService;
    @Resource
    private SysUserService sysUserService;
    @Autowired
    private SysUserFeignService sysUserFeignService;

    @Autowired
    private ImUserFriendService imUserFriendService;

    @Autowired
    private ImGroupMemberService imGroupMemberService;

    @ApiOperation("获取群详情")
    @PostMapping(value = "/getDetail/{groupId}")
    public HttpResponseResult<ImGroup> getDetail(@ApiParam(value = "群编号", required = true) @PathVariable("groupId") String groupId) throws Exception {

        // 获取用户ID
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null  || sysUser.getId() == null) {
            return failed("用户信息获取失败");
        }

        ImGroup group = imGroupService.findGroupInfoById(groupId, sysUser.getId());
        // ImGroup group = imGroupService.getById(groupId);
        if (group == null) {
            return failed(HttpStatus.NO_CONTENT, "群组不存在");
        }
        ImGroupMember admin = imGroupMemberService.lambdaQuery()
                .eq(ImGroupMember::getGroupId, group.getId())
                .eq(ImGroupMember::getUserId, sysUserService.getUser().getId())
                .last("limit 1").one();
        if (admin == null) {
            // 该用户不在该群，无权限查看，处理用户退出群后，查看历史消息校验
            return failed(HttpStatus.NO_CONTENT, "群组不存在");
        }
        return succeed(group);
    }

    @ApiOperation("群列表")
    @PostMapping(value = "/queryAll")
    public HttpResponseResult<List<ImGroup>> queryAll(@Valid @RequestBody ImGroupSearchDto imGroupSearchDto, BindingResult bindingResult) throws Exception {
        ValidationKit.ignoreFields(bindingResult,"createUserId");
        imGroupSearchDto.setUserId(sysUserService.getUserId());

        // 设置群组成员身份
        imGroupSearchDto.setRoleType(ImGroupMemberRoleType.STUDENT);
        return succeed(imGroupService.queryAll(imGroupSearchDto));
    }

    @ApiOperation("获取指定用户的群列表")
    @PostMapping(value = "/queryTeacherGroup")
    public HttpResponseResult<List<ImGroupResultDto>> queryTeacherGroup(@RequestBody ImGroupSearchDto imGroupSearchDto) throws Exception {

        // 群类型
        if (StringUtils.isEmpty(imGroupSearchDto.getType())) {
            imGroupSearchDto.setType("FAN");
        }
        // 用户群身份
        imGroupSearchDto.setRoleType(ImGroupMemberRoleType.STUDENT);

        return succeed(imGroupService.queryTeacherFun(imGroupSearchDto));
    }

    @ApiOperation("退出群聊")
    @PostMapping(value = "/quit/{groupId}")
    public HttpResponseResult quit(@ApiParam(value = "群编号", required = true) @PathVariable("groupId") String groupId,
                                   @RequestParam(value = "quit",required = false,defaultValue = "false") boolean quit
    ) throws Exception {
        imGroupService.quit(groupId,sysUserService.getUserId(), ClientEnum.STUDENT, quit);
        return succeed();
    }


    @ApiOperation("查询好友详情")
    @GetMapping(value = "/queryFriendDetail")
    public HttpResponseResult<ImUserFriendVO.ImUserFriend> queryFriendDetail(String userId) {

        // 管乐迷、酷乐秀直播播允许多端学生观看，这里增加了对用户ID的解析
        if (userId.matches(MK.EXP_INT)) {
            ImUserFriend userProfile = imUserFriendService.getImUserProfile(userId);
            if (Objects.isNull(userProfile)) {
                return failed("当前好友不存在");
            }
            return succeed(ImUserFriendVO.ImUserFriend.from(JSON.toJSONString(userProfile)));
        }

        String ret = imGroupService.analysisImUserId(userId);
        if (!ret.matches(MK.EXP_INT)) {
            return failed("无效的用户ID");
        }

        ImUserFriendVO.ImUserFriend userFriend = imUserFriendService.getDetail(userId, ClientEnum.TEACHER);
        if (Objects.isNull(userFriend)) {
            return failed("当前好友不存在");
        }

        if (Objects.isNull(userFriend.getFriendType())) {
            userFriend.setFriendType(ClientEnum.STUDENT);
        }

        return succeed(userFriend);
    }
}

