package com.storlead.wecom.integration;

import com.storlead.framework.common.vo.user.UserVO;
import com.storlead.thirdparty.api.dto.ThirdPartyUserSyncDTO;
import com.storlead.thirdparty.api.enums.ThirdPartyChannel;
import com.storlead.thirdparty.spi.ThirdPartyUserSyncClient;
import com.storlead.wecom.service.CorpWeChatService;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 企业微信用户 openId（xworkUserId）/ 头像同步 SPI 实现。
 */
@Component
public class WecomThirdPartyUserSyncClient implements ThirdPartyUserSyncClient {

    @Resource
    private CorpWeChatService corpWeChatService;

    @Override
    public ThirdPartyChannel channel() {
        return ThirdPartyChannel.WECOM;
    }

    @Override
    public List<ThirdPartyUserSyncDTO> syncUserOpenId(List<ThirdPartyUserSyncDTO> users) {
        if (CollectionUtils.isEmpty(users)) {
            return Collections.emptyList();
        }
        List<UserVO> userVoList = new ArrayList<>(users.size());
        for (ThirdPartyUserSyncDTO user : users) {
            UserVO vo = new UserVO();
            vo.setId(user.getId());
            vo.setMobile(user.getMobile());
            vo.setXworkUserId(user.getXworkUserId());
            vo.setAvatar(user.getAvatar());
            userVoList.add(vo);
        }
        List<UserVO> synced = corpWeChatService.syncUserOpenIdFormTencent(userVoList);
        if (CollectionUtils.isEmpty(synced)) {
            return Collections.emptyList();
        }
        List<ThirdPartyUserSyncDTO> result = new ArrayList<>(synced.size());
        for (UserVO vo : synced) {
            ThirdPartyUserSyncDTO dto = new ThirdPartyUserSyncDTO();
            dto.setId(vo.getId());
            dto.setMobile(vo.getMobile());
            dto.setXworkUserId(vo.getXworkUserId());
            dto.setAvatar(vo.getAvatar());
            result.add(dto);
        }
        return result;
    }
}
