package com.shulead.datasync.manager;

import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenResponseBody;
import com.aliyun.dingtalkyida_1_0.models.*;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiV2UserGetbymobileRequest;
import com.dingtalk.api.response.OapiV2UserGetbymobileResponse;
import com.taobao.api.ApiException;
import jakarta.annotation.Resource;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Classname YiDaManager
 * @Description TODO
 * @Version 1.0.0
 * @Date 2024/5/7 10:39
 * @Created by liuxiangshun
 */
@Slf4j
@Component
public class YiDaManager {
    @Resource
    private com.aliyun.dingtalkyida_1_0.Client yiDaClient;

    @Resource
    private com.aliyun.dingtalkoauth2_1_0.Client authClient;

    public YiDaResponse createOrUpdateInstance(String formUuId, String searchCondition, String instance) {
        CreateOrUpdateFormDataHeaders createOrUpdateFormDataHeaders = new CreateOrUpdateFormDataHeaders();
        createOrUpdateFormDataHeaders.xAcsDingtalkAccessToken = getAccessToken();
        CreateOrUpdateFormDataRequest createOrUpdateFormDataRequest = new CreateOrUpdateFormDataRequest()
                .setNoExecuteExpression(false)
                .setFormUuid(formUuId)
                .setSearchCondition(searchCondition)
                .setAppType("APP_VCTRP6227CC8368NDOID")
                .setFormDataJson(instance)
                .setSystemToken("5H9662C1X8XJLFFCE841M5VBEBQ73DM5IBPULPI3")
                .setUserId("332051151139376769");
        try {
            yiDaClient.createOrUpdateFormDataWithOptions(createOrUpdateFormDataRequest, createOrUpdateFormDataHeaders, new RuntimeOptions());
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                YiDaResponse yiDaResponse = new YiDaResponse();
                yiDaResponse.setOk(false);
                yiDaResponse.setCode(err.getCode());
                yiDaResponse.setMessage(err.getMessage());
                return yiDaResponse;
            }

        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                YiDaResponse yiDaResponse = new YiDaResponse();
                yiDaResponse.setOk(false);
                yiDaResponse.setCode(err.getCode());
                yiDaResponse.setMessage(err.getMessage());
                return yiDaResponse;
            }
        }
        YiDaResponse yiDaResponse = new YiDaResponse();
        yiDaResponse.setOk(true);
        return yiDaResponse;
    }

    public String getAccessToken() {
        com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest getAccessTokenRequest = new com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest()
                .setAppKey("dingwnds0gg0vpbu44cd")
                .setAppSecret("B7tDWb3hPjP4rksRd_PqOsOVBv6QWY6F9gvn1X2aIoAIMFchRGw69aDeHly-6XXn");
        try {
            GetAccessTokenResponseBody body = authClient.getAccessToken(getAccessTokenRequest).getBody();
            return body.getAccessToken();
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                log.error("code:{}, message:{}", err.getCode(), err.getMessage());
            }

        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                log.error("code:{}, message:{}", err.getCode(), err.getMessage());
            }

        }
        return null;
    }

    public String getUserIdByPhone(String phone) {
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/getbymobile");
            OapiV2UserGetbymobileRequest req = new OapiV2UserGetbymobileRequest();
            req.setMobile(phone);
            OapiV2UserGetbymobileResponse rsp = client.execute(req, getAccessToken());
            OapiV2UserGetbymobileResponse.UserGetByMobileResponse result = rsp.getResult();
            if (null != result) {
                return result.getUserid();
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return null;
    }

    public YiDaResponse getFormInstanceById(String formUuid, String formInstanceId) {
        BatchGetFormDataByIdListHeaders batchGetFormDataByIdListHeaders = new BatchGetFormDataByIdListHeaders();
        batchGetFormDataByIdListHeaders.xAcsDingtalkAccessToken = getAccessToken();
        BatchGetFormDataByIdListRequest batchGetFormDataByIdListRequest = new BatchGetFormDataByIdListRequest()
                .setFormUuid(formUuid)
                .setAppType("APP_VCTRP6227CC8368NDOID")
                .setSystemToken("5H9662C1X8XJLFFCE841M5VBEBQ73DM5IBPULPI3")
                .setFormInstanceIdList(java.util.Arrays.asList(
                        formInstanceId
                ))
                .setNeedFormInstanceValue(true)
                .setUserId("332051151139376769");
        YiDaResponse yiDaResponse = new YiDaResponse();
        yiDaResponse.setOk(true);
        try {
            BatchGetFormDataByIdListResponse response = yiDaClient.batchGetFormDataByIdListWithOptions(batchGetFormDataByIdListRequest, batchGetFormDataByIdListHeaders, new RuntimeOptions());
            List<BatchGetFormDataByIdListResponseBody.BatchGetFormDataByIdListResponseBodyResult> result = response.getBody().getResult();
            if (CollectionUtils.isNotEmpty(result)) {
                yiDaResponse.setData(result.getFirst().getInstanceValue());
            }
            return yiDaResponse;
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                yiDaResponse.setOk(false);
                yiDaResponse.setCode(err.getCode());
                yiDaResponse.setMessage(err.getMessage());
                return yiDaResponse;
            }

        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                yiDaResponse.setOk(false);
                yiDaResponse.setCode(err.getCode());
                yiDaResponse.setMessage(err.getMessage());
                return yiDaResponse;
            }
        }
        return yiDaResponse;
    }

    @Data
    public static class YiDaResponse {
        private Boolean ok;
        private String code;
        private String message;
        private Object data;
    }
}
