package cn.iocoder.yudao.module.system.service.dingtalk;

import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.module.system.api.dingtalk.DingtalkSendApi;
import cn.iocoder.yudao.module.system.api.dingtalk.dto.send.NotifySendResponse;
import cn.iocoder.yudao.module.system.service.dingtalk.vo.DingTalkMsgParams;
import com.alibaba.fastjson.JSON;
import com.aliyun.dingtalkoauth2_1_0.Client;
import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest;
import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenResponse;
import com.aliyun.teaopenapi.models.Config;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiMessageCorpconversationAsyncsendV2Request;
import com.dingtalk.api.request.OapiV2UserGetbymobileRequest;
import com.dingtalk.api.response.OapiMessageCorpconversationAsyncsendV2Response;
import com.dingtalk.api.response.OapiV2UserGetbymobileResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * 钉钉消息 Service 发送的实现
 *
 * @author suiyy
 */
@Service
@Slf4j
public class DingtalkSendServiceImpl implements DingtalkSendApi {

    @Value("${dingtalk.APP_KEY}")
    private String appKey;

    @Value("${dingtalk.APP_SECRET}")
    private String appSecret;

    @Value("${dingtalk.AGENT_ID}")
    private String agentId;

    @Value("${dingtalk.URL_GET_SEND_MESSAGE}")
    private String sendMsgUrl;

    @Value("${dingtalk.URL_GET_USERINFO_BYMOBILE}")
    private String getUserInfoByMobile;
    @Value("${system.url}")
    private String systemUrl;

    @Override
    public NotifySendResponse send(String sendAccount, String sendContent, String type, String jumpUrl, String title) {
        NotifySendResponse notifySendResponse = new NotifySendResponse();
        notifySendResponse.setSendContent(sendContent);
        notifySendResponse.setStatus(1);
        // 发送
        try {
            // 获取应用访问凭证accessToken
            Config config = new Config();
            config.protocol = "https";
            config.regionId = "central";
            Client client = new Client(config);
            GetAccessTokenRequest accessTokenRequest = new GetAccessTokenRequest();
            accessTokenRequest.setAppKey(appKey);
            accessTokenRequest.setAppSecret(appSecret);
            GetAccessTokenResponse accessTokenResponse = client.getAccessToken(accessTokenRequest);
            String accessToken = accessTokenResponse.getBody().getAccessToken();
            DingTalkClient dingTalkClient = new DefaultDingTalkClient(sendMsgUrl);
            OapiMessageCorpconversationAsyncsendV2Request req = new OapiMessageCorpconversationAsyncsendV2Request();
            req.setAgentId(Long.valueOf(agentId));
            // 优先取发送账号、然后是部门、然后是所有人
            if (StrUtil.isNotEmpty(sendAccount)) {
                // 根据手机号获取钉钉userid
                DingTalkClient dingTalkClientUser = new DefaultDingTalkClient(getUserInfoByMobile);
                OapiV2UserGetbymobileRequest phoneReq = new OapiV2UserGetbymobileRequest();
                phoneReq.setMobile(sendAccount);
                OapiV2UserGetbymobileResponse rsp = dingTalkClientUser.execute(phoneReq, accessToken);
                String userId = rsp.getResult().getUserid();
                req.setUseridList(userId);
                req.setToAllUser(Boolean.FALSE);
            }
            DingTalkMsgParams dingTalkMsgParams = new DingTalkMsgParams();
            dingTalkMsgParams.setMessageUrl(jumpUrl);
            dingTalkMsgParams.setTitle(title);
            dingTalkMsgParams.setPicUrl(systemUrl + "images/logo.png");
            OapiMessageCorpconversationAsyncsendV2Request.Msg msg = this.createOapiMessageMsg(dingTalkMsgParams, sendContent, type);
            req.setMsg(msg);
            OapiMessageCorpconversationAsyncsendV2Response rsp = dingTalkClient.execute(req, accessToken);
            notifySendResponse.setStatus(0 == rsp.getErrcode() ? 1 : 0);
            notifySendResponse.setResultContent(JSON.toJSONString(rsp));
        } catch (Exception e) {
            notifySendResponse.setStatus(0);
            notifySendResponse.setResultContent(e.toString());
        }
        return notifySendResponse;
    }

    /**
     * 构建钉钉发送消息
     *
     * @param msgParams 消息参数
     * @return
     */
    private OapiMessageCorpconversationAsyncsendV2Request.Msg createOapiMessageMsg(DingTalkMsgParams msgParams, String content, String type) {
        OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
        msg.setMsgtype(type);
        switch (msg.getMsgtype()) {
            case "text":
                msg.setText(new OapiMessageCorpconversationAsyncsendV2Request.Text());
                msg.getText().setContent(content);
                break;
            case "link":
                msg.setLink(new OapiMessageCorpconversationAsyncsendV2Request.Link());
                msg.getLink().setTitle(msgParams.getTitle());
                msg.getLink().setText(content);
                msg.getLink().setMessageUrl(msgParams.getMessageUrl());
                msg.getLink().setPicUrl(msgParams.getPicUrl());
                break;
            case "markdown":
                msg.setMarkdown(new OapiMessageCorpconversationAsyncsendV2Request.Markdown());
                msg.getMarkdown().setText(content);
                msg.getMarkdown().setTitle(msgParams.getTitle());
                break;
            default:
                break;
        }
        return msg;
    }

}
