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

import com.alibaba.fastjson.JSON;
import com.aliyun.dingtalkattendance_1_0.Client;
import com.aliyun.dingtalkattendance_1_0.models.GetLeaveRecordsHeaders;
import com.aliyun.dingtalkattendance_1_0.models.GetLeaveRecordsResponse;
import com.aliyun.dingtalkattendance_1_0.models.GetLeaveRecordsResponseBody;
import com.aliyun.dingtalkworkflow_1_0.models.GetProcessInstanceResponse;
import com.aliyun.dingtalkworkflow_1_0.models.GetProcessInstanceResponseBody;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.*;
import com.dingtalk.api.response.*;
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> getPersonById(String id) {
        try {
            DingTalkClient client = getDingTalkClient("/topapi/v2/user/get");
            OapiV2UserGetRequest req = new OapiV2UserGetRequest();
            req.setUserid(id);   //用户id
            log.info("getPersonByID:{}",id);
            OapiV2UserGetResponse rsp = client.execute(req, getToken());
            log.info("钉钉返回用户信息:{}", rsp.getBody());
            if (rsp.getErrcode() == 0) {
                return Rest.ok("成功", rsp.getResult().getMobile());
            } 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());
        }
    }

    /**
     * 设置client的config参数
     * @return Client
     * @throws Exception
     */
    public com.aliyun.teaopenapi.models.Config setConfig() {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config();
        config.protocol = "http";
        config.regionId = "central";
        config.endpoint = oaUrl;
        return config;
    }

    @Override
    public Rest<GetProcessInstanceResponseBody.GetProcessInstanceResponseBodyResult> getOaRecordsById(String processInstanceId) {
        try {
            com.aliyun.dingtalkworkflow_1_0.Client client = new com.aliyun.dingtalkworkflow_1_0.Client(setConfig());
            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:8919");

            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());

        }
    }




    @Override
    public Rest<OapiAttendanceVacationQuotaListResponse.OapiLeaveQuotaUserListVo> getLeaveRecordByUserId(String user_id, String leave_code) {
        try {
            DingTalkClient client = getDingTalkClient("/topapi/attendance/vacation/quota/list");
            OapiAttendanceVacationQuotaListRequest req = new OapiAttendanceVacationQuotaListRequest();
            req.setLeaveCode(leave_code);
            req.setOpUserid(opUserId);
            req.setUserids(user_id);
            req.setOffset(0L);
            req.setSize(50L);
            OapiAttendanceVacationQuotaListResponse rsp = client.execute(req, getToken());
            log.info("假期余额:{}", JSON.toJSONString(rsp.getResult()));
            if (rsp.getErrcode() == 0) {
                return Rest.ok("成功", rsp.getResult());
            } else {
                return Rest.fail(String.format("code:%s,msg:%s", rsp.getErrcode(), rsp.getErrmsg()));
            }
        } catch (ApiException e) {
            e.printStackTrace();
            log.error("根据id查询假期余额异常", e);
            return Rest.fail(e.getMessage());
        }

    }
}
