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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.*;
import com.dingtalk.api.response.*;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.mortals.framework.annotation.UnAuth;
import com.mortals.framework.common.Rest;
import com.mortals.framework.exception.AppException;
import com.mortals.xhx.busiz.dingtalk.config.TalkConfiguration;
import com.mortals.xhx.busiz.dingtalk.req.DingTalkBaseReq;
import com.mortals.xhx.busiz.dingtalk.req.UserPageReq;
import com.mortals.xhx.busiz.req.MobileReq;
import com.mortals.xhx.busiz.req.ReviewSaveReq;
import com.mortals.xhx.common.code.YesNoEnum;
import com.mortals.xhx.common.pdu.ApiRespPdu;
import lombok.extern.apachecommons.CommonsLog;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import sun.security.krb5.internal.APOptions;

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());
            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());
            OapiV2UserGetbymobileResponse rsp = client.execute(req, dingToken);
            if(rsp.getErrcode() == 0){
                //根据获取到的userid去获取用户详情
                ApiRespPdu<OapiV2UserGetResponse.UserGetResponse> userRsp = getUserInfo(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/getUserInfo")
    @UnAuth
    public ApiRespPdu<OapiV2UserGetResponse.UserGetResponse> getUserInfo(@RequestBody String userid){
        ApiRespPdu<OapiV2UserGetResponse.UserGetResponse> apiRespPdu = new ApiRespPdu<>();
        try {
            DingTalkClient client = new DefaultDingTalkClient(talkConfiguration.getGetuserinfo());
            OapiV2UserGetRequest req = new OapiV2UserGetRequest();
            if(dingToken == null){
                dingToken = getToken().getData();
            }
            req.setUserid(userid);
            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;
    }
}
