package com.yonge.cooleshow.teacher.controller;


import com.alibaba.fastjson.JSON;
import com.microsvc.toolkit.common.response.template.R;
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.service.im.ImGroupCoreService;
import com.yonge.cooleshow.biz.dal.vo.im.ImUserFriendVO;
import com.yonge.cooleshow.biz.dal.wrapper.im.ImGroupWrapper;
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.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
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.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;

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

    @Autowired
    private ImUserFriendService imUserFriendService;

    @Autowired
    private ImGroupMemberService imGroupMemberService;

    @Autowired
    private ImGroupCoreService imGroupCoreService;

    @ApiOperation("创建群聊")
    @PostMapping(value = "/create")
    public HttpResponseResult create(@Valid @RequestBody ImGroupWrapper.ImGroup imGroup, BindingResult bindingResult) throws Exception {
        ValidationKit.ignoreFields(bindingResult,"id");
        imGroup.setCreateBy(sysUserService.getUserId());
        imGroupService.create(imGroup);
        return succeed();
    }

    @ApiOperation("添加群成员")
    @PostMapping(value = "/addGroupMember")
    public HttpResponseResult addGroupMember(@Valid @RequestBody ImGroupWrapper.ImGroup imGroup,
                                             BindingResult bindingResult) throws Exception {
        imGroupService.addGroupMember(imGroup.getGroupId(), imGroup.getStudentIdList());
        return succeed();
    }

    @ApiOperation("创建群聊")
    @PostMapping(value = "/create/v2")
    public HttpResponseResult createV2(@Valid @RequestBody ImGroupWrapper.ImGroup imGroup, BindingResult bindingResult) throws Exception {

        // 将imUserId 转为userId
        Set<String> imUserIdList = imGroup.getImUserIdList();

        Set<Long> studentIdList = new HashSet<>();
        for (String imUserId : imUserIdList) {
            studentIdList.add(Long.parseLong(imGroupService.analysisImUserId(imUserId)));
        }
        imGroup.setStudentIdList(studentIdList);

        ValidationKit.ignoreFields(bindingResult,"id");
        imGroup.setCreateBy(sysUserService.getUserId());
        imGroupService.create(imGroup);
        return succeed();
    }

    @ApiOperation("添加群成员")
    @PostMapping(value = "/addGroupMember/v2")
    public HttpResponseResult addGroupMemberV2(@Valid @RequestBody ImGroupWrapper.ImGroup imGroup,
                                               BindingResult bindingResult) throws Exception {
        // 将imUserId 转为userId
        Set<String> imUserIdList = imGroup.getImUserIdList();

        Set<Long> studentIdList = new HashSet<>();
        for (String imUserId : imUserIdList) {
            studentIdList.add(Long.parseLong(imGroupService.analysisImUserId(imUserId)));
        }
        imGroup.setStudentIdList(studentIdList);

        imGroupService.addGroupMember(imGroup.getGroupId(), imGroup.getStudentIdList());
        return succeed();
    }

    @ApiOperation("解散群聊")
    @PostMapping(value = "/dismiss/{groupId}")
    public HttpResponseResult dismiss(@ApiParam(value = "群编号", required = true) @PathVariable("groupId") String groupId) throws Exception {
        imGroupService.dismiss(groupId);
        return succeed();
    }

    @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.TEACHER, quit);
        return succeed();
    }

    @ApiOperation("获取群详情")
    @PostMapping(value = "/getDetail/{groupId}")
    public HttpResponseResult<ImGroup> getDetail(@ApiParam(value = "群编号", required = true) @PathVariable("groupId") String groupId) throws Exception {
        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.TEACHER);

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

    @ApiOperation("修改群信息")
    @PostMapping(value = "/update")
    public HttpResponseResult<Boolean> update(@Valid @RequestBody ImGroup imGroup) throws Exception {
        return succeed(imGroupService.updateImGroup(imGroup));
    }

    @ApiOperation("获取指定用户的群列表")
    @PostMapping(value = "/queryTeacherGroup")
    public HttpResponseResult<List<ImGroupResultDto>> queryTeacherGroup(@RequestBody ImGroupSearchDto imGroupSearchDto) throws Exception {
        if (StringUtils.isEmpty(imGroupSearchDto.getType())) {
            imGroupSearchDto.setType("FAN");
        }
        return succeed(imGroupService.queryTeacherFun(imGroupSearchDto));
    }

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

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

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

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

        return succeed(ImUserFriendVO.ImUserFriend.from(JSON.toJSONString(userFriend)));
    }

    @ApiOperation(value = "转让群主", notes = "转让群主- 传入 ImGroupVo.ImGroupOwner")
    @PostMapping("/changeGroupOwner")
    public R<Boolean> changeGroupOwner(@Validated @RequestBody ImGroupWrapper.ChangeGroupOwner changeGroupOwner) throws Exception {

        // 转让群主
        imGroupCoreService.changeGroupOwner(changeGroupOwner.getGroupId(), changeGroupOwner.getNewOwner(), changeGroupOwner.getOldOwner());

        return R.from(true);
    }

    @ApiOperation("群禁言")
    @PostMapping(value = "/muteAll")
    public HttpResponseResult<Boolean> muteAll(@Valid @RequestBody ImGroupWrapper.Mute mute) throws Exception {
        return succeed(imGroupService.muteAll(mute));
    }
}

