package com.cm.common.plugin.oauth.service.user.impl;

import com.alibaba.fastjson.JSONArray;
import com.cm.common.base.AbstractService;
import com.cm.common.config.properties.ApiPathProperties;
import com.cm.common.constants.ISystemConstant;
import com.cm.common.plugin.IApiConsts;
import com.cm.common.plugin.oauth.service.department.IDepartmentService;
import com.cm.common.plugin.oauth.service.user.IUserImService;
import com.cm.common.plugin.oauth.service.user.IUserService;
import com.cm.common.plugin.oauth.token.ClientTokenManager;
import com.cm.common.plugin.pojo.bos.user.UserDepartmentResourceBO;
import com.cm.common.plugin.utils.RestTemplateUtil;
import com.cm.common.pojo.bos.UserInfoBO;
import com.cm.common.result.SuccessResultLayImData;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * When you feel like quitting. Think about why you started
 * 当你想要放弃的时候，想想当初你为何开始
 *
 * @ClassName: UserDepartmentServiceImpl
 * @Description: 用户即时消息
 * @Author: wanggeng
 * @Date: 2021/1/15 10:05 上午
 * @Version: 1.0
 */
@Service
public class UserImServiceImpl extends AbstractService implements IUserImService {

    @Autowired
    private IUserService userService;
    @Autowired
    private IDepartmentService departmentService;
    @Autowired
    private RestTemplateUtil restTemplateUtil;
    @Autowired
    private ApiPathProperties apiPathProperties;

    @Override
    public SuccessResultLayImData<SuccessResultLayImData.InitData> getInitData() {
        try {
            // 个人信息
            UserInfoBO currentUser = securityComponent.getCurrentUser();
            SuccessResultLayImData.User mine = new SuccessResultLayImData.User();
            mine.setId(currentUser.getUserId());
            mine.setUsername(StringUtils.equals(currentUser.getUserUsername(), ISystemConstant.ADMIN) ? "系统管理员" : currentUser.getUserName());
            if (StringUtils.isBlank(currentUser.getUserAvatar())) {
                mine.setAvatar(DEFAULT_USER_AVATAR);
            } else {
                mine.setAvatar(apiPathProperties.getUserCenter() + "/route/file/downloadfile/true/" + currentUser.getUserAvatar());
            }
            mine.setStatus("online");
            mine.setSign("暂无签名");

            Map<String, Object> params = getHashMap(2);
            // 用户所在部门集合
            Set<SuccessResultLayImData.Friend> userFriendSet = new HashSet<>();

            // 朋友
            List<SuccessResultLayImData.Friend> friends = listDepartmentUser(params);
            setFriends(currentUser, mine, friends, userFriendSet);

            // 用户组
            List<SuccessResultLayImData.Group> groups = new ArrayList<>();
            setGroups(currentUser, friends, groups, userFriendSet);

            SuccessResultLayImData.InitData initData = new SuccessResultLayImData.InitData();
            initData.setMine(mine);
            initData.setFriend(friends);
            initData.setGroup(groups);
            return new SuccessResultLayImData<>(0, "", initData);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return new SuccessResultLayImData<>(400, e.getMessage(), null);
        }
    }

    @Override
    public List<SuccessResultLayImData.Friend> listDepartmentUser(Map<String, Object> params) {
        params.put(IApiConsts.ACCESS_TOKEN, ClientTokenManager.getInstance().getClientToken().getAccessToken());
        String result = restTemplateUtil.doGetFormNormal(String.format(IApiConsts.LIST_LAYIM_DEPARTMENT_USER, apiPathProperties.getUserCenter()), params);
        searchResourceResult(result, "获取人员列表失败");
        return JSONArray.parseArray(result, SuccessResultLayImData.Friend.class);
    }

    @Override
    public SuccessResultLayImData<SuccessResultLayImData.MemberData> getMemberData(String departmentId) {
        try {
            List<String> departmentIds = new ArrayList<>();
            departmentIds.add(departmentId);
            List<UserDepartmentResourceBO> userDepartmentResourceBOS = userService.listUserDepartmentResourceByDepartmentIds(departmentIds);
            SuccessResultLayImData.MemberData memberData = new SuccessResultLayImData.MemberData();
            List<SuccessResultLayImData.User> list = new ArrayList<>();
            memberData.setList(list);
            for (UserDepartmentResourceBO userDepartmentResourceBO : userDepartmentResourceBOS) {
                SuccessResultLayImData.User user = new SuccessResultLayImData.User();
                user.setId(userDepartmentResourceBO.getUserId());
                user.setUsername(userDepartmentResourceBO.getUserName());
                user.setSign("暂无签名");
                if (StringUtils.isBlank(userDepartmentResourceBO.getUserAvatar())) {
                    user.setAvatar(DEFAULT_USER_AVATAR);
                } else {
                    user.setAvatar(apiPathProperties.getUserCenter() + "/route/file/downloadfile/true/" + userDepartmentResourceBO.getUserAvatar());
                }
                list.add(user);
            }
            // 添加管理员
            SuccessResultLayImData.User adminUser = getAdminUser();
            adminUser.setAvatar(DEFAULT_USER_AVATAR);
            list.add(adminUser);
            return new SuccessResultLayImData<>(0, "", memberData);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return new SuccessResultLayImData<>(400, e.getMessage(), null);
        }
    }

    @Override
    public List<UserDepartmentResourceBO> listUserDepartmentResource(List<String> departmentIds) {
        List<UserDepartmentResourceBO> userDepartmentResourceBOS = userService.listUserDepartmentResourceByDepartmentIds(departmentIds);
        // 添加系统管理员
        UserDepartmentResourceBO userDepartmentResourceBO = new UserDepartmentResourceBO();
        userDepartmentResourceBO.setUserId("1");
        userDepartmentResourceBO.setUserUsername(ISystemConstant.ADMIN);
        userDepartmentResourceBO.setUserName("系统管理员");
        userDepartmentResourceBO.setUserAvatar(DEFAULT_USER_AVATAR);
        userDepartmentResourceBOS.add(userDepartmentResourceBO);
        return userDepartmentResourceBOS;
    }

    /**
     * 设置朋友列表
     *
     * @param currentUser
     * @param mine
     * @param friends
     */
    private void setFriends(UserInfoBO currentUser, SuccessResultLayImData.User mine, List<SuccessResultLayImData.Friend> friends, Set<SuccessResultLayImData.Friend> userFriendSet) {
        // 非管理员添加系统管理员
        if (!StringUtils.equals(ISystemConstant.ADMIN, currentUser.getUserUsername())) {
            // 加载管理员
            SuccessResultLayImData.Friend adminFriend = new SuccessResultLayImData.Friend();
            adminFriend.setId("admin");
            adminFriend.setGroupname("管理员");
            List<SuccessResultLayImData.User> users = new ArrayList<>();
            users.add(getAdminUser());
            adminFriend.setList(users);
            friends.add(adminFriend);
        }
        for (int i = 0; i < friends.size(); i++) {
            SuccessResultLayImData.Friend friend = friends.get(i);
            for (int j = 0; j < friend.getList().size(); j++) {
                SuccessResultLayImData.User user = friend.getList().get(j);
                // 删除自己
                if (StringUtils.equals(user.getId(), mine.getId())) {
                    userFriendSet.add(friend);
                    friend.getList().remove(j);
                    j--;
                    continue;
                }
                if (StringUtils.isBlank(user.getAvatar())) {
                    user.setAvatar(DEFAULT_USER_AVATAR);
                } else {
                    user.setAvatar(apiPathProperties.getUserCenter() + "/route/file/downloadfile/true/" + user.getAvatar());
                }
                // 默认离线
                user.setStatus("offline");
                user.setSign("暂无签名");
            }
            // 删除用户为空的朋友组
            if (friend.getList().isEmpty()) {
                friends.remove(i);
                i--;
            }
        }
    }

    /**
     * 系统管理员
     *
     * @return
     */
    private SuccessResultLayImData.User getAdminUser() {
        SuccessResultLayImData.User user = new SuccessResultLayImData.User();
        user.setId("1");
        user.setStatus("offline");
        user.setUsername("系统管理员");
        return user;
    }

    /**
     * 设置组
     *
     * @param currentUser
     * @param friends
     * @param groups
     * @param userFriendIdSet
     */
    private void setGroups(UserInfoBO currentUser, List<SuccessResultLayImData.Friend> friends, List<SuccessResultLayImData.Group> groups, Set<SuccessResultLayImData.Friend> userFriendSet) {
        // 管理员添加所有组
        if (StringUtils.equals(ISystemConstant.ADMIN, currentUser.getUserUsername())) {
            for (SuccessResultLayImData.Friend friend : friends) {
                SuccessResultLayImData.Group group = new SuccessResultLayImData.Group();
                group.setId(friend.getId());
                group.setGroupname(friend.getGroupname());
                group.setAvatar(DEFAULT_GROUP_AVATAR);
                groups.add(group);
            }
            return;
        }
        // 非管理员添加自己所在部门
        for (SuccessResultLayImData.Friend friend : userFriendSet) {
            SuccessResultLayImData.Group group = new SuccessResultLayImData.Group();
            group.setId(friend.getId());
            group.setGroupname(friend.getGroupname());
            group.setAvatar(DEFAULT_GROUP_AVATAR);
            groups.add(group);
        }
    }
}
