package com.wecloud.im.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wecloud.im.entity.ImApplication;
import com.wecloud.im.entity.ImClient;
import com.wecloud.im.entity.ImConversationMembers;
import com.wecloud.im.mapper.ImConversationMapper;
import com.wecloud.im.mapper.ImConversationMembersMapper;
import com.wecloud.im.param.ApiImConversationMembersPageParam;
import com.wecloud.im.param.ApiImConversationMembersQueryVo;
import com.wecloud.im.param.ImConvMemeClientRemarkNameParam;
import com.wecloud.im.param.ListConversationMembersParam;
import com.wecloud.im.param.ImConversationMembersPageParam;
import com.wecloud.im.param.ImConversationMembersQueryVo;
import com.wecloud.im.param.SetAdminsParam;
import com.wecloud.im.param.add.ImConversationMemAttrUpdate;
import com.wecloud.im.service.ImApplicationService;
import com.wecloud.im.service.ImClientService;
import com.wecloud.im.service.ImConversationMembersService;
import com.wecloud.im.service.ImConversationService;
import com.wecloud.im.service.ImMessageService;
import com.wecloud.im.vo.ConversationMemberVo;
import com.wecloud.im.ws.sender.ChannelSender;
import com.wecloud.utils.JsonUtils;
import io.geekidea.springbootplus.framework.common.api.ApiResult;
import io.geekidea.springbootplus.framework.common.service.impl.BaseServiceImpl;
import io.geekidea.springbootplus.framework.core.pagination.PageInfo;
import io.geekidea.springbootplus.framework.core.pagination.Paging;
import io.geekidea.springbootplus.framework.shiro.jwt.JwtToken;
import io.geekidea.springbootplus.framework.shiro.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 会话成员表 服务实现类
 *
 * @author wei
 * @since 2021-05-07
 */
@Slf4j
@Service
public class ImConversationMembersServiceImpl extends BaseServiceImpl<ImConversationMembersMapper, ImConversationMembers> implements ImConversationMembersService {

    @Autowired
    private ChannelSender channelSender;

    @Autowired
    private ImConversationMapper imConversationMapper;

    @Autowired
    private ImConversationMembersService imConversationMembersService;

    @Autowired
    private ImConversationService imConversationService;

    @Autowired
    private ImClientService imClientService;

    @Autowired
    private ImApplicationService imApplicationService;

    @Autowired
    private ImMessageService imMessageService;

    @Autowired
    private ImConversationMembersMapper imConversationMembersMapper;

    @Override
    public ApiResult<List<ApiImConversationMembersQueryVo>> getRestApiImConversationMembersList(ApiImConversationMembersPageParam apiImConversationMembersPageParam, ImApplication imApplication) {

        List<ApiImConversationMembersQueryVo> restApiImConversationMembersList = imConversationMembersMapper.getRestApiImConversationMembersList(apiImConversationMembersPageParam.getConversationId());
        return ApiResult.ok(restApiImConversationMembersList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ApiResult<Boolean> saveOrUpdateClientRemarkName(ImConvMemeClientRemarkNameParam imConvMemeClientRemarkNameParam) {

        // shiro线程中获取当前token
        JwtToken curentJwtToken = JwtUtil.getCurentJwtToken();
        //  根据appKey查询application
        ImApplication imApplication = imApplicationService.getCacheAppByAppKey(curentJwtToken.getAppKey());

        ImClient imClientSender = imClientService.getCurentClient();

        // 查询该成员
        ImConversationMembers imConversationMember = imConversationMembersService.getOne(
                new QueryWrapper<ImConversationMembers>().lambda()
                        .eq(ImConversationMembers::getFkAppid, imApplication.getId())
                        .eq(ImConversationMembers::getFkConversationId, imConvMemeClientRemarkNameParam.getConversationId())
                        .eq(ImConversationMembers::getFkClientId, imClientSender.getId())
        );

        if (imConversationMember == null) {
            return ApiResult.fail();
        }


//        // 查询该会话所有成员
//        List<ImConversationMembers> membersList = imConversationMembersService.list(
//                new QueryWrapper<ImConversationMembers>().lambda()
//                        .eq(ImConversationMembers::getFkAppid, imApplication.getId())
//                        .eq(ImConversationMembers::getFkConversationId, imConversationAttrUpdate.getConversationId())
//                        .notIn(ImConversationMembers::getId, imClientSender.getId())
//        );


        imConversationMember.setClientRemarkName(imConvMemeClientRemarkNameParam.getClientRemarkName());


        boolean b = imConversationMembersService.updateById(imConversationMember);
        if (b) {

            //TODO ws下发群成员备注变动事件

            return ApiResult.ok();

        } else {
            return ApiResult.fail();
        }

    }

    @Override
    public List<ConversationMemberVo> getImConversationMembersList(ListConversationMembersParam param) {
        return imConversationMembersMapper.getImConversationMembersList(param);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ApiResult<Boolean> saveOrUpdateAttr(ImConversationMemAttrUpdate imConversationMemAttrUpdate) {

        // shiro线程中获取当前token
        JwtToken curentJwtToken = JwtUtil.getCurentJwtToken();
        //  根据appKey查询application
        ImApplication imApplication = imApplicationService.getCacheAppByAppKey(curentJwtToken.getAppKey());

        ImClient imClientSender = imClientService.getCurentClient();

        // 查询该成员
        ImConversationMembers imConversationMember = imConversationMembersService.getOne(
                new QueryWrapper<ImConversationMembers>().lambda()
                        .eq(ImConversationMembers::getFkAppid, imApplication.getId())
                        .eq(ImConversationMembers::getFkConversationId, imConversationMemAttrUpdate.getConversationId())
                        .eq(ImConversationMembers::getId, imClientSender.getId())
        );

        if (imConversationMember == null) {
            return ApiResult.fail();
        }


//        // 查询该会话所有成员
//        List<ImConversationMembers> membersList = imConversationMembersService.list(
//                new QueryWrapper<ImConversationMembers>().lambda()
//                        .eq(ImConversationMembers::getFkAppid, imApplication.getId())
//                        .eq(ImConversationMembers::getFkConversationId, imConversationAttrUpdate.getConversationId())
//                        .notIn(ImConversationMembers::getId, imClientSender.getId())
//        );

        String attributes = JsonUtils.encodeJson(imConversationMemAttrUpdate.getAttributes());
        imConversationMember.setAttributes(attributes);


        boolean b = imConversationMembersService.updateById(imConversationMember);
        if (b) {

            //TODO ws下发群成员属性变动事件

            return ApiResult.ok();

        } else {
            return ApiResult.fail();
        }

    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean saveImConversationMembers(ImConversationMembers imConversationMembers) throws Exception {
        return super.save(imConversationMembers);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateImConversationMembers(ImConversationMembers imConversationMembers) throws Exception {
        return super.updateById(imConversationMembers);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteImConversationMembers(Long id) throws Exception {
        return super.removeById(id);
    }

    @Override
    public ImConversationMembersQueryVo getImConversationMembersById(Long id) throws Exception {
        return imConversationMembersMapper.getImConversationMembersById(id);
    }

    @Override
    public Paging<ImConversationMembersQueryVo> getImConversationMembersPageList(ImConversationMembersPageParam imConversationMembersPageParam) throws Exception {
        Page<ImConversationMembersQueryVo> page = new PageInfo<>(imConversationMembersPageParam, OrderItem.desc(getLambdaColumn(ImConversationMembers::getCreateTime)));
        IPage<ImConversationMembersQueryVo> iPage = imConversationMembersMapper.getImConversationMembersPageList(page, imConversationMembersPageParam);
        return new Paging<ImConversationMembersQueryVo>(iPage);
    }

    @Override
    public List<Long> findThousandGroupsByClientId(Long clientId) {
        return imConversationMembersMapper.findThousandGroupsByClientId(clientId);
    }

    /**
     * 批量设置群成员
     * @param param
     * @param fkClientIds
     */
    @Override
    public void setAdminsForConversation(SetAdminsParam param, List<Long> fkClientIds) {
        Integer role = param.getOperateType() == 1 ? 2 : 1;
        imConversationMembersMapper.setAdminsForConversation(param.getConversationId(), fkClientIds, role);
    }

}
