package com.cm.common.dingding.service.impl;

import com.cm.common.base.AbstractService;
import com.cm.common.dingding.config.properties.DingDingAppProperties;
import com.cm.common.dingding.manager.app.DingDingAppManager;
import com.cm.common.dingding.service.IDingDingAppUserService;
import com.cm.common.dingding.service.IDingDingMessageService;
import com.cm.common.exception.SearchException;
import com.cm.common.result.SuccessResult;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiMessageCorpconversationAsyncsendV2Request;
import com.dingtalk.api.response.OapiMessageCorpconversationAsyncsendV2Response;
import com.taobao.api.ApiException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * When you feel like quitting. Think about why you started
 * 当你想要放弃的时候，想想当初你为何开始
 *
 * @ClassName: DingDingMessageService
 * @Description: 钉钉消息
 * @Author: WangGeng
 * @Date: 2020/9/24 13:39
 * @Version: 1.0
 **/
@Service
public class DingDingMessageService extends AbstractService implements IDingDingMessageService {

    @Autowired
    private DingDingAppProperties dingDingAppProperties;
    @Autowired
    private IDingDingAppUserService dingDingAppUserService;

    @Override
    public SuccessResult send(String phone, String content) throws SearchException {
        String userId = dingDingAppUserService.getUserIdByPhone(phone);
        if (StringUtils.isBlank(userId)) {
            throw new SearchException("获取钉钉用户ID失败");
        }
        sendMessage(userId, content);
        return new SuccessResult();
    }

    @Override
    public SuccessResult sendByPhones(List<String> phones, String content) throws SearchException {
        List<String> userIds = new ArrayList<>();
        for (String phone : phones) {
            String userId = dingDingAppUserService.getUserIdByPhone(phone);
            if (!StringUtils.isBlank(userId)) {
                continue;
            }
            userIds.add(userId);
        }
        if (userIds.isEmpty()) {
            return new SuccessResult();
        }
        int sendCount = userIds.size() / 100 + 1;
        for (int i = 0; i < sendCount; i++) {
            StringBuilder userIdSB = new StringBuilder();
            int lastUserLength = userIds.size() - i * 100;
            int userLength = lastUserLength > 100 ? 100 : lastUserLength;
            for (int j = 0; j < userLength; j++) {
                if (userIdSB.length() != 0) {
                    userIdSB.append(",");
                }
                userIdSB.append(userIds.get(i * 100 + j));
            }
            sendMessage(userIdSB.toString(), content);
        }
        return new SuccessResult();
    }

    /**
     * 发送消息
     *
     * @param userIds
     * @param content
     */
    private void sendMessage(String userIds, String content) {
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");
            OapiMessageCorpconversationAsyncsendV2Request oapiMessageCorpconversationAsyncsendV2Request = new OapiMessageCorpconversationAsyncsendV2Request();
            oapiMessageCorpconversationAsyncsendV2Request.setUseridList(userIds);
            oapiMessageCorpconversationAsyncsendV2Request.setAgentId(dingDingAppProperties.getAgentId());
            oapiMessageCorpconversationAsyncsendV2Request.setToAllUser(false);

            OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
            msg.setMsgtype("text");
            msg.setText(new OapiMessageCorpconversationAsyncsendV2Request.Text());
            msg.getText().setContent(content);
            oapiMessageCorpconversationAsyncsendV2Request.setMsg(msg);

            OapiMessageCorpconversationAsyncsendV2Response oapiMessageCorpconversationAsyncsendV2Response = client.execute(oapiMessageCorpconversationAsyncsendV2Request, DingDingAppManager.getInstance().getAccessToken());
            if (oapiMessageCorpconversationAsyncsendV2Response.getErrcode() != 0) {
                throw new SearchException(oapiMessageCorpconversationAsyncsendV2Response.getMsg());
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }
    }

}
