package com.mortals.xhx.busiz.dingtalk.api;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.*;
import com.dingtalk.api.response.*;
import com.mortals.framework.annotation.UnAuth;
import com.mortals.xhx.busiz.dingtalk.config.TalkConfiguration;
import com.mortals.xhx.busiz.dingtalk.req.UserPageReq;
import com.mortals.xhx.busiz.dingtalk.req.CodeReq;
import com.mortals.xhx.busiz.dingtalk.req.LinkMessageReq;
import com.mortals.xhx.busiz.dingtalk.req.MobileReq;
import com.mortals.xhx.common.pdu.ApiRespPdu;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 钉钉相关外部接口
 *
 * @Author:
 */
@RestController
@Slf4j
public class TalkApiController {

    @Autowired
    private TalkConfiguration talkConfiguration;

    private String dingToken;

    /**
     * 获取token
     *
     * @return
     */
    @PostMapping("/dingtalk/gettoken")
    @UnAuth
    public ApiRespPdu<String> getToken() {
        ApiRespPdu<String> apiRespPdu = new ApiRespPdu<>();
        try {
            DingTalkClient client = new DefaultDingTalkClient(talkConfiguration.getGetTokneUrl());
            OapiGettokenRequest req = new OapiGettokenRequest();
            req.setAppkey(talkConfiguration.getAppKey());
            req.setAppsecret(talkConfiguration.getAppSecret());
            req.setHttpMethod("GET");
            OapiGettokenResponse rsp = client.execute(req);
            log.info("gettoken rsp:" + rsp.getBody());
            if (rsp.getErrcode() == 0) {
                dingToken = rsp.getAccessToken();
                apiRespPdu.setCode(0);
                apiRespPdu.setData(rsp.getAccessToken());
                apiRespPdu.setMsg(rsp.getMsg());
            } else {
                apiRespPdu.setCode(-1);
                apiRespPdu.setData("");
                apiRespPdu.setMsg(rsp.getMsg());
            }

        } catch (Exception e) {
            log.error("异常", e);
            apiRespPdu.setCode(-1);
            apiRespPdu.setData("");
            apiRespPdu.setMsg(e.toString());
        }
        return apiRespPdu;
    }

    /**
     * 获取部门列表
     * @return
     */
    @PostMapping("/dingtalk/getSubList")
    @UnAuth
    public ApiRespPdu<List<OapiV2DepartmentListsubResponse.DeptBaseResponse>> getSubList(){
        ApiRespPdu<List<OapiV2DepartmentListsubResponse.DeptBaseResponse>> apiRespPdu = new ApiRespPdu<>();
        try {
            DingTalkClient client = new DefaultDingTalkClient(talkConfiguration.getGetSubList());
            OapiV2DepartmentListsubRequest req = new OapiV2DepartmentListsubRequest();
            if(dingToken == null){
                dingToken = getToken().getData();
            }
            OapiV2DepartmentListsubResponse rsp = client.execute(req, dingToken);
            if(rsp.getErrcode() == 0){
                apiRespPdu.setCode(0);
                apiRespPdu.setData(rsp.getResult());
                apiRespPdu.setMsg(rsp.getMsg());
            }else {
                if(getToken().getCode() == 0){
                    getSubList();
                }else {
                    apiRespPdu.setCode(-1);
                    apiRespPdu.setData(null);
                    apiRespPdu.setMsg("获取token失败");
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            apiRespPdu.setCode(-1);
            apiRespPdu.setData(null);
            apiRespPdu.setMsg(e.toString());
        }

        return apiRespPdu;
    }


    /**
     * 根据部门id查询该部门下所有用户完整信息
     * @return
     */
    @PostMapping("/dingtalk/getUserList")
    @UnAuth
    public ApiRespPdu<OapiV2UserListResponse.PageResult> getUserList(@RequestBody UserPageReq res){
        ApiRespPdu<OapiV2UserListResponse.PageResult> apiRespPdu = new ApiRespPdu<>();
        try {
            DingTalkClient client = new DefaultDingTalkClient(talkConfiguration.getGetuserlist());
            OapiV2UserListRequest req = new OapiV2UserListRequest();
            if(dingToken == null){
                dingToken = getToken().getData();
            }
            req.setDeptId(res.getDeptid());   //部门id
            req.setCursor(res.getCursor());   //起始页游标
            req.setSize(res.getSize());    //分页条数
            OapiV2UserListResponse rsp = client.execute(req, dingToken);
            if(rsp.getErrcode() == 0){
                apiRespPdu.setCode(0);
                apiRespPdu.setData(rsp.getResult());
                apiRespPdu.setMsg(rsp.getMsg());
            }else {
                if(getToken().getCode() == 0){
                    getUserList(res);
                }else {
                    apiRespPdu.setCode(-1);
                    apiRespPdu.setData(null);
                    apiRespPdu.setMsg("获取token失败");
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            apiRespPdu.setCode(-1);
            apiRespPdu.setData(null);
            apiRespPdu.setMsg(e.toString());
        }

        return apiRespPdu;
    }

    /**
     * 根据手机号查询用户
     * @return
     */
    @GetMapping("/dingtalk/getByMobile")
    @UnAuth
    public ApiRespPdu<OapiV2UserGetResponse.UserGetResponse> getByMobile(@RequestBody MobileReq mobile){
        ApiRespPdu<OapiV2UserGetResponse.UserGetResponse> apiRespPdu = new ApiRespPdu<>();
        try {
            DingTalkClient client = new DefaultDingTalkClient(talkConfiguration.getGetbymobile());
            OapiV2UserGetbymobileRequest req = new OapiV2UserGetbymobileRequest();
            if(dingToken == null){
                dingToken = getToken().getData();
            }
            req.setMobile(mobile.getMobile());   //用户手机号
            //先根据手机号去获取userid  再通过userid获取详情    钉钉没有直接根据电话获取用户详情的接口
            OapiV2UserGetbymobileResponse rsp = client.execute(req, dingToken);
            if(rsp.getErrcode() == 0){
                //根据获取到的userid去获取用户详情
                ApiRespPdu<OapiV2UserGetResponse.UserGetResponse> userRsp = getUserInfoByUserId(rsp.getResult().getUserid());
                if(userRsp.getCode() == 0){
                    apiRespPdu.setCode(userRsp.getCode());
                    apiRespPdu.setData(userRsp.getData());
                    apiRespPdu.setMsg(userRsp.getMsg());
                }else {
                    apiRespPdu.setCode(-1);
                    apiRespPdu.setData(null);
                    apiRespPdu.setMsg(userRsp.getMsg());
                }
            }else {
                if(getToken().getCode() == 0){
                    getByMobile(mobile);
                }else {
                    apiRespPdu.setCode(-1);
                    apiRespPdu.setData(null);
                    apiRespPdu.setMsg("获取token失败");
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            apiRespPdu.setCode(-1);
            apiRespPdu.setData(null);
            apiRespPdu.setMsg(e.toString());
        }

        return apiRespPdu;
    }

    /**
     * 根据userid查询用户详情
     * @return
     */
    @GetMapping("/dingtalk/getUserInfoByUserId")
    @UnAuth
    public ApiRespPdu<OapiV2UserGetResponse.UserGetResponse> getUserInfoByUserId(@RequestBody String userid){
        ApiRespPdu<OapiV2UserGetResponse.UserGetResponse> apiRespPdu = new ApiRespPdu<>();
        try {
            DingTalkClient client = new DefaultDingTalkClient(talkConfiguration.getGetuserinfobyuserid());
            OapiV2UserGetRequest req = new OapiV2UserGetRequest();
            if(dingToken == null){
                dingToken = getToken().getData();
            }
            req.setUserid(userid);   //用户id
            OapiV2UserGetResponse rsp = client.execute(req, dingToken);

            apiRespPdu.setCode(0);
            apiRespPdu.setData(rsp.getResult());
            apiRespPdu.setMsg(rsp.getMsg());
        } catch (Exception e) {
            e.printStackTrace();
            apiRespPdu.setCode(-1);
            apiRespPdu.setData(null);
            apiRespPdu.setMsg(e.toString());
        }

        return apiRespPdu;
    }


    /**
     * 推送链接类钉钉工作消息
     * @return
     */
    @PostMapping("/dingtalk/sendLinkMessage")
    @UnAuth
    public ApiRespPdu<String> sendLinkMessage(@RequestBody LinkMessageReq linkMessageReq){
        ApiRespPdu<String> apiRespPdu = new ApiRespPdu<>();
        try {
            DingTalkClient client = new DefaultDingTalkClient(talkConfiguration.getSendmessage());
            if(dingToken == null){
                dingToken = getToken().getData();
            }
            OapiMessageCorpconversationAsyncsendV2Request req = new OapiMessageCorpconversationAsyncsendV2Request();
            req.setAgentId(Long.valueOf(talkConfiguration.getGetAgentId()));
            req.setUseridList(linkMessageReq.getUserIdList());

            OapiMessageCorpconversationAsyncsendV2Request.Msg obj1 = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
            obj1.setMsgtype("link");   //type为链接类消息
            OapiMessageCorpconversationAsyncsendV2Request.Link obj2 = new OapiMessageCorpconversationAsyncsendV2Request.Link();
            obj2.setPicUrl(linkMessageReq.getPicUrl());    //消息图片地址
            obj2.setMessageUrl(linkMessageReq.getMessageUrl());  //跳转链接地址
            obj2.setText(linkMessageReq.getText());    //消息描述
            obj2.setTitle(linkMessageReq.getTitle());   //消息title
            obj1.setLink(obj2);
            req.setMsg(obj1);

            OapiMessageCorpconversationAsyncsendV2Response rsp = client.execute(req, dingToken);
            if(rsp.getErrcode() == 0){
                apiRespPdu.setCode(0);
                apiRespPdu.setData(rsp.getBody());
                apiRespPdu.setMsg(rsp.getMsg());
            }else {
                apiRespPdu.setCode(-1);
                apiRespPdu.setData(rsp.getBody());
                apiRespPdu.setMsg(rsp.getMsg());

            }

        } catch (Exception e) {
            e.printStackTrace();
            apiRespPdu.setCode(-1);
            apiRespPdu.setData("");
            apiRespPdu.setMsg(e.toString());
        }

        return apiRespPdu;
    }


    /**
     * 根据免登码查询用户详情
     * @return
     */
    @GetMapping("/dingtalk/getUserInfoByCode")
    @UnAuth
    public ApiRespPdu<OapiV2UserGetuserinfoResponse.UserGetByCodeResponse> getUserInfoByCode(@RequestBody CodeReq codeReq){
        ApiRespPdu<OapiV2UserGetuserinfoResponse.UserGetByCodeResponse> apiRespPdu = new ApiRespPdu<>();
        try {
            DingTalkClient client = new DefaultDingTalkClient(talkConfiguration.getGetuserinfobycode());
            OapiV2UserGetuserinfoRequest req = new OapiV2UserGetuserinfoRequest();
            if(dingToken == null){
                dingToken = getToken().getData();
            }
            req.setCode(codeReq.getCode());    //前端js获取到的免登码  用免登码获取用户信息
            OapiV2UserGetuserinfoResponse rsp = client.execute(req, dingToken);

            apiRespPdu.setCode(0);
            apiRespPdu.setData(rsp.getResult());
            apiRespPdu.setMsg(rsp.getMsg());
        } catch (Exception e) {
            e.printStackTrace();
            apiRespPdu.setCode(-1);
            apiRespPdu.setData(null);
            apiRespPdu.setMsg(e.toString());
        }

        return apiRespPdu;
    }
}
