package com.zfire.mall.manager.utils;

import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.*;
import com.dingtalk.api.response.*;
import com.taobao.api.ApiException;
import com.zfire.mall.manager.constant.DingURLConstant;
import lombok.extern.slf4j.Slf4j;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 钉钉Utils工具类
 */
@Slf4j
public class DingDingOAUtils {


    /**
     * 获得钉钉accessToken
     *
     * @param appKey appSecret
     * @return AccessToken
     */
    public static String getAccessToken(String appKey, String appSecret) throws ApiException {
        try {
            DingTalkClient client = new DefaultDingTalkClient(DingURLConstant.URL_GET_TOKKEN);
            OapiGettokenRequest req = new OapiGettokenRequest();
            req.setAppkey(appKey);
            req.setAppsecret(appSecret);
            req.setHttpMethod("GET");
            OapiGettokenResponse rsp = client.execute(req);
            JSONObject jsonObject = JSON.parseObject(rsp.getBody());
            return Convert.toStr(jsonObject.get("access_token"));
        } catch (ApiException e) {
            e.printStackTrace();
            log.info(e.getMessage());
        }
        return null;
    }

    /**
     * 获得钉钉部门
     *
     * @param accessToken deptId
     * @return List<OapiV2DepartmentListsubResponse.DeptBaseResponse>
     */
    public static List<OapiV2DepartmentListsubResponse.DeptBaseResponse> getDept(String accessToken, Long deptId) {
        try {
            DingTalkClient client = new DefaultDingTalkClient(DingURLConstant.URL_GET_DEPARTMENT);
            OapiV2DepartmentListsubRequest req = new OapiV2DepartmentListsubRequest();
            req.setDeptId(deptId);
            OapiV2DepartmentListsubResponse rsp = client.execute(req, accessToken);
            List<OapiV2DepartmentListsubResponse.DeptBaseResponse> result = rsp.getResult();
            return result;
        } catch (ApiException e) {
            e.printStackTrace();
            log.info(e.getMessage());
        }
        return null;
    }

    /**
     * 获得钉钉部门下的成员userId
     *
     * @param accessToken deptId
     * @return List<String>
     */
    public static List<String> getDeptUser(String accessToken, Long deptId) {
        try {
            DingTalkClient clientUser = new DefaultDingTalkClient(DingURLConstant.URL_GET_DEPARTMENT_USER);
            OapiUserListidRequest reqUser = new OapiUserListidRequest();
            reqUser.setDeptId(deptId);
            OapiUserListidResponse rspUser = clientUser.execute(reqUser, accessToken);
            OapiUserListidResponse.ListUserByDeptResponse result = rspUser.getResult();
            if (result == null || CollectionUtils.isEmpty(result.getUseridList()))
                return null;
            return result.getUseridList();
        } catch (ApiException e) {
            e.printStackTrace();
            log.info(e.getMessage());
        }
        return null;
    }

    /**
     * 获得钉钉成员详情
     *
     * @param userId accessToken
     * @return OapiV2UserGetResponse.UserGetResponse
     */
    public static OapiV2UserGetResponse.UserGetResponse getDeptUserDetails(String userId, String accessToken) {
        try {
            DingTalkClient clientName = new DefaultDingTalkClient(DingURLConstant.URL_GET_DEPARTMENT_USER_DATEILS);
            OapiV2UserGetRequest reqName = new OapiV2UserGetRequest();
            reqName.setUserid(userId);
            OapiV2UserGetResponse rspName = null;
            rspName = clientName.execute(reqName, accessToken);
            OapiV2UserGetResponse.UserGetResponse result = rspName.getResult();
            return result;
        } catch (ApiException e) {
            e.printStackTrace();
            log.info(e.getMessage());
        }
        return null;

    }


    /**
     * 发起审批
     *
     * @param processCode userId deptId map accessToken
     * @return Boolean
     */
    public static Boolean pushApproval(String processCode, String userId, Long deptId, Map<String, String> map, String accessToken) throws ApiException {
        try {
            DingTalkClient client = new DefaultDingTalkClient(DingURLConstant.URL_PROCESSINSTANCE_START);
            OapiProcessinstanceCreateRequest req = new OapiProcessinstanceCreateRequest();
            req.setProcessCode(processCode);
            req.setOriginatorUserId(userId);
            req.setDeptId(deptId);
            List<OapiProcessinstanceCreateRequest.FormComponentValueVo> formComponentValueVolum = new ArrayList<>();
            for (Map.Entry<String, String> stringStringEntry : map.entrySet()) {
                OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo = new OapiProcessinstanceCreateRequest.FormComponentValueVo();
                formComponentValueVo.setValue(stringStringEntry.getValue());
                formComponentValueVo.setName(stringStringEntry.getKey());
                formComponentValueVolum.add(formComponentValueVo);
            }
            req.setFormComponentValues(formComponentValueVolum);
            OapiProcessinstanceCreateResponse rsp = client.execute(req, accessToken);
            System.out.println(rsp);
        } catch (ApiException e) {
            e.printStackTrace();
            log.info(e.getMessage());
            return false;
        }
        return true;
    }


    /**
     * 调起钉盘空间信息
     *
     * @param userId accessToken
     * @return String
     */
    public static String pushContent(String userId, String accessToken) throws ApiException {
        try {
            DingTalkClient client = new DefaultDingTalkClient(DingURLConstant.URL_GET_DEPARTMENT_CSPACE_INFO);
            OapiProcessinstanceCspaceInfoRequest req = new OapiProcessinstanceCspaceInfoRequest();
            req.setUserId(userId);
            OapiProcessinstanceCspaceInfoResponse rsp = client.execute(req, accessToken);
            return rsp.getBody();
        } catch (ApiException e) {
            e.printStackTrace();
            log.info(e.getMessage());
        }
        return null;
    }


    /**
     * 获得实例详情
     *
     * @param processInstanceId accessToken
     * @return ProcessInstanceTopVo
     */
    public static OapiProcessinstanceGetResponse.ProcessInstanceTopVo processinstance(String processInstanceId, String accessToken) throws ApiException {
        try {
            DingTalkClient client = new DefaultDingTalkClient(DingURLConstant.URL_PROCESSINSTANCE_GET);
            OapiProcessinstanceGetRequest req = new OapiProcessinstanceGetRequest();
            req.setProcessInstanceId(processInstanceId);
            OapiProcessinstanceGetResponse rsp = client.execute(req, accessToken);
            return rsp.getProcessInstance();
        } catch (ApiException e) {
            e.printStackTrace();
            log.info(e.getMessage());
        }
        return null;
    }
}
