package com.mortals.xhx.module.dingding.personal.service.impl;

import com.alibaba.fastjson.JSON;
import com.aliyun.dingtalkworkflow_1_0.models.GetProcessInstanceResponse;
import com.aliyun.dingtalkworkflow_1_0.models.GetProcessInstanceResponseBody;
import com.aliyun.tea.TeaException;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiMessageCorpconversationAsyncsendV2Request;
import com.dingtalk.api.request.OapiV2UserGetbymobileRequest;
import com.dingtalk.api.request.OapiV2UserGetuserinfoRequest;
import com.dingtalk.api.response.OapiMessageCorpconversationAsyncsendV2Response;
import com.dingtalk.api.response.OapiV2UserGetbymobileResponse;
import com.dingtalk.api.response.OapiV2UserGetuserinfoResponse;
import com.mortals.framework.common.Rest;
import com.mortals.xhx.module.dingding.AbstractDingTalkService;
import com.mortals.xhx.module.dingding.personal.model.req.workmsg.WorkMsgReq;
import com.mortals.xhx.module.dingding.personal.service.IDingPersonService;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.logging.Log;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;


@Service("dingPersonService")
@Slf4j
public class DingPersonServiceImpl extends AbstractDingTalkService implements IDingPersonService {


    @Override
    public Rest<String> getPersonByMobile(String mobile) {
        try {
            DingTalkClient client = getDingTalkClient("/topapi/v2/user/getbymobile");
            OapiV2UserGetbymobileRequest req = new OapiV2UserGetbymobileRequest();
            req.setMobile(mobile);
            log.info("getPersonByMobile:{}", mobile);
            OapiV2UserGetbymobileResponse rsp = client.execute(req, getToken());
            log.info("OapiV2UserGetbymobileResponse:{}", rsp.getBody());
            if (rsp.getErrcode() == 0) {
                return Rest.ok("成功", rsp.getResult().getUserid());
            } else {
                return Rest.fail(String.format("code:%s,msg:%s", rsp.getErrcode(), rsp.getErrmsg()));
            }
        } catch (ApiException e) {
            log.info("根据手机号码查询人员异常", e);
            return Rest.fail(e.getMessage());
        }
    }

    @Override
    public Rest<String> getPersonByCode(String code) {
        try {
            DingTalkClient client = getDingTalkClient("/topapi/v2/user/getuserinfo");
            OapiV2UserGetuserinfoRequest req = new OapiV2UserGetuserinfoRequest();
            req.setCode(code);
            log.info("getPersonByCode:{}", code);
            OapiV2UserGetuserinfoResponse rsp = client.execute(req, getToken());
            log.info("OapiV2UserGetuserinfoResponse:{}", rsp.getBody());
            if (rsp.getErrcode() == 0) {
                return Rest.ok("成功", rsp.getResult().getUserid());
            } else {
                return Rest.fail(String.format("code:%s,msg:%s", rsp.getErrcode(), rsp.getErrmsg()));
            }
        } catch (ApiException e) {
            log.info("根据code查询人员异常", e);
            return Rest.fail(e.getMessage());
        }
    }

    @Override
    public Rest<String> sendWorkMsg(WorkMsgReq workMsgReq) {
        try {
            DingTalkClient client = getDingTalkClient("/topapi/message/corpconversation/asyncsend_v2");
            OapiMessageCorpconversationAsyncsendV2Request req = new OapiMessageCorpconversationAsyncsendV2Request();
            req.setAgentId(agentId);
            req.setUseridList(workMsgReq.getUseridList());
            //.setMsg(JSON.toJSONString(workMsgReq.getMsg()));
            log.info("workMsgReq:{}", JSON.toJSONString(workMsgReq));
            OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();

            if ("link".equals(workMsgReq.getMsg().getMsgtype())) {
                OapiMessageCorpconversationAsyncsendV2Request.Link link = new OapiMessageCorpconversationAsyncsendV2Request.Link();
                link.setMessageUrl(workMsgReq.getMsg().getLink().getMessageUrl());
                link.setText(workMsgReq.getMsg().getLink().getText());
                link.setTitle(workMsgReq.getMsg().getLink().getTitle());

                link.setPicUrl("@lADOADmaWMzazQKA");
                msg.setLink(link);
                msg.setMsgtype("link");
            } else if ("text".equals(workMsgReq.getMsg().getMsgtype())) {
                OapiMessageCorpconversationAsyncsendV2Request.Text text = new OapiMessageCorpconversationAsyncsendV2Request.Text();
                text.setContent(workMsgReq.getMsg().getText().getContent());
                msg.setMsgtype("text");
                msg.setText(text);
            }
            req.setMsg(msg);
            //  workMsgReq.getMsg().getLink().setPicUrl("@lADOADmaWMzazQKA");
            log.info("sendWorkMsg:{}", JSON.toJSONString(req));
            OapiMessageCorpconversationAsyncsendV2Response rsp = client.execute(req, getToken());
            log.info("OapiMessageResponse:{}", rsp.getBody());
            if (rsp.getErrcode() == 0) {
                return Rest.ok(rsp.getMsg(), rsp.getRequestId());
            } else {
                return Rest.fail(String.format("code:%s,msg:%s", rsp.getErrcode(), rsp.getErrmsg()));
            }
        } catch (ApiException e) {
            log.info("根据用户id发送工作消息异常", e);
            return Rest.fail(e.getMessage());
        }
    }

    /**
     * 使用 Token 初始化账号Client
     *
     * @return Client
     * @throws Exception
     */
    public com.aliyun.dingtalkworkflow_1_0.Client createClient() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config();
        config.protocol = "https";
        config.regionId = "central";
       // config.endpoint = domain.replace("http://", "");
        return new com.aliyun.dingtalkworkflow_1_0.Client(config);
    }

    @Override
    public Rest<GetProcessInstanceResponseBody.GetProcessInstanceResponseBodyResult> getOaRecordsById(String processInstanceId) {
        try {
            com.aliyun.dingtalkworkflow_1_0.Client client = createClient();
            com.aliyun.dingtalkworkflow_1_0.models.GetProcessInstanceHeaders getProcessInstanceHeaders = new com.aliyun.dingtalkworkflow_1_0.models.GetProcessInstanceHeaders();
            getProcessInstanceHeaders.xAcsDingtalkAccessToken = getToken();
/*            HashMap<String, String> map = new HashMap<>();
            getProcessInstanceHeaders.setCommonHeaders(map);
            getProcessInstanceHeaders.getCommonHeaders().put("host", "172.15.28.113");
            getProcessInstanceHeaders.getCommonHeaders().put("port", "8918");
            getProcessInstanceHeaders.getCommonHeaders().put("protocol", "http");*/

            com.aliyun.dingtalkworkflow_1_0.models.GetProcessInstanceRequest getProcessInstanceRequest = new com.aliyun.dingtalkworkflow_1_0.models.GetProcessInstanceRequest()
                    .setProcessInstanceId(processInstanceId);
            log.info("processInstanceId:{}", processInstanceId);
            GetProcessInstanceResponse rsp = client.getProcessInstanceWithOptions(getProcessInstanceRequest, getProcessInstanceHeaders, new com.aliyun.teautil.models.RuntimeOptions());
            return Rest.ok("成功", rsp.getBody().getResult());
        } catch (Exception e) {
            log.error("根据用户查询审批详情失败", e);
            return Rest.fail(e.getMessage());

        }
    }
}
