package yangtz.cs.liu.dingding.utils;

import com.aliyun.dingtalkworkflow_1_0.models.*;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;
import com.ruoyi.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import yangtz.cs.liu.dingding.vo.DingHandleVo;
import yangtz.cs.liu.dingding.vo.DingProcessInstanceVo;
import yangtz.cs.liu.dingding.vo.DingTransferVo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 审批实例
 */
@Component
public class DingProcessInstanceUtils {

    @Value("${dd.agentId}")
    private Long agentId;

    private static Logger log = LoggerFactory.getLogger(DingProcessInstanceUtils.class);

    @Autowired
    private AccessTokenUtils accessTokenUtils;

    /**
     * 使用 Token 初始化账号Client
     * @return Client
     * @throws Exception
     */
    public com.aliyun.dingtalkworkflow_1_0.Client createClient()
    {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config();
        config.protocol = "https";
        config.regionId = "central";
        try {
            return new com.aliyun.dingtalkworkflow_1_0.Client(config);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 发送审批实例
     */
    public String sendProcessInstance(DingProcessInstanceVo instanceVo)
    {
        //获取access_token
        String token = accessTokenUtils.getToken();
        com.aliyun.dingtalkworkflow_1_0.Client client = createClient();
        com.aliyun.dingtalkworkflow_1_0.models.StartProcessInstanceHeaders startProcessInstanceHeaders = new com.aliyun.dingtalkworkflow_1_0.models.StartProcessInstanceHeaders();
        startProcessInstanceHeaders.xAcsDingtalkAccessToken = token;
        com.aliyun.dingtalkworkflow_1_0.models.StartProcessInstanceRequest startProcessInstanceRequest = new com.aliyun.dingtalkworkflow_1_0.models.StartProcessInstanceRequest();
        if (StringUtils.isNotEmpty(instanceVo.getCcPosition())){
            startProcessInstanceRequest.setCcPosition(instanceVo.getCcPosition());
        }
        if (StringUtils.isNotEmpty(instanceVo.getOriginatorUserId())){
            startProcessInstanceRequest.setOriginatorUserId(instanceVo.getOriginatorUserId());
        }
        if (StringUtils.isNotNull(instanceVo.getDeptId())){
            startProcessInstanceRequest.setDeptId(instanceVo.getDeptId());
        }
        if (StringUtils.isNotNull(instanceVo.getApprovers())){
            startProcessInstanceRequest.setApprovers(instanceVo.getApprovers());
        }
        if (StringUtils.isNotNull(instanceVo.getCcList())){
            startProcessInstanceRequest.setCcList(instanceVo.getCcList());
        }
        if (StringUtils.isNotNull(instanceVo.getTargetSelectActioners())){
            startProcessInstanceRequest.setTargetSelectActioners(instanceVo.getTargetSelectActioners());
        }
        if (StringUtils.isNotNull(instanceVo.getFormComponentValues())){
            startProcessInstanceRequest.setFormComponentValues(instanceVo.getFormComponentValues());
        }
        if (StringUtils.isNotEmpty(instanceVo.getProcessCode())){
            startProcessInstanceRequest.setProcessCode(instanceVo.getProcessCode());
        }
        startProcessInstanceRequest.setMicroappAgentId(agentId);
        try {
            StartProcessInstanceResponse startProcessInstanceResponse = client.startProcessInstanceWithOptions(startProcessInstanceRequest, startProcessInstanceHeaders, new RuntimeOptions());
            return startProcessInstanceResponse.getBody().getInstanceId();
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                log.info(err.code);
                log.info(err.message);
            }

        } 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.info(err.code);
                log.info(err.message);
            }

        }
        return "";
    }

    /**
     * 查询单个审批详情
     */
    public GetProcessInstanceResponseBody.GetProcessInstanceResponseBodyResult getProcessInstance(String processInstanceId)
    {
        //获取access_token
        String token = accessTokenUtils.getToken();
        com.aliyun.dingtalkworkflow_1_0.Client client = createClient();
        com.aliyun.dingtalkworkflow_1_0.models.GetProcessInstanceHeaders getProcessInstanceHeaders = new com.aliyun.dingtalkworkflow_1_0.models.GetProcessInstanceHeaders();
        getProcessInstanceHeaders.xAcsDingtalkAccessToken = token;
        com.aliyun.dingtalkworkflow_1_0.models.GetProcessInstanceRequest getProcessInstanceRequest = new com.aliyun.dingtalkworkflow_1_0.models.GetProcessInstanceRequest()
                .setProcessInstanceId(processInstanceId);
        try {
            GetProcessInstanceResponse processInstanceWithOptions = client.getProcessInstanceWithOptions(getProcessInstanceRequest, getProcessInstanceHeaders, new RuntimeOptions());
            return processInstanceWithOptions.getBody().getResult();
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                log.info(err.code);
                log.info(err.message);
            }

        } 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.info(err.code);
                log.info(err.message);
            }
        }
        return new GetProcessInstanceResponseBody.GetProcessInstanceResponseBodyResult();
    }

    /**
     * 撤销审批实例
     */
    public Boolean terminate(String processInstanceId, Boolean isSystem, String remark, String operatingUserId)
    {
        //获取access_token
        String token = accessTokenUtils.getToken();
        com.aliyun.dingtalkworkflow_1_0.Client client = createClient();
        com.aliyun.dingtalkworkflow_1_0.models.TerminateProcessInstanceHeaders terminateProcessInstanceHeaders = new com.aliyun.dingtalkworkflow_1_0.models.TerminateProcessInstanceHeaders();
        terminateProcessInstanceHeaders.xAcsDingtalkAccessToken = token;
        com.aliyun.dingtalkworkflow_1_0.models.TerminateProcessInstanceRequest terminateProcessInstanceRequest = new com.aliyun.dingtalkworkflow_1_0.models.TerminateProcessInstanceRequest();
        if(StringUtils.isNotNull(isSystem)){
            terminateProcessInstanceRequest.setIsSystem(isSystem);
        }
        if (StringUtils.isNotEmpty(processInstanceId)){
            terminateProcessInstanceRequest.setProcessInstanceId(processInstanceId);
        }
        if (StringUtils.isNotEmpty(remark)){
            terminateProcessInstanceRequest.setRemark(remark);
        }
        if (StringUtils.isNotEmpty(operatingUserId)){
            terminateProcessInstanceRequest.setOperatingUserId(operatingUserId);
        }
        try {
            TerminateProcessInstanceResponse terminateProcessInstanceResponse = client.terminateProcessInstanceWithOptions(terminateProcessInstanceRequest, terminateProcessInstanceHeaders, new RuntimeOptions());
            return terminateProcessInstanceResponse.getBody().getResult();
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                log.info(err.code);
                log.info(err.message);
            }

        } 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.info(err.code);
                log.info(err.message);
            }

        }
        return false;
    }

    /**
     * 获取表单schema
     */
    public QuerySchemaByProcessCodeResponseBody.QuerySchemaByProcessCodeResponseBodyResult getSchema(String processCode)
    {
        //获取access_token
        String token = accessTokenUtils.getToken();
        com.aliyun.dingtalkworkflow_1_0.Client client = createClient();
        com.aliyun.dingtalkworkflow_1_0.models.QuerySchemaByProcessCodeHeaders querySchemaByProcessCodeHeaders = new com.aliyun.dingtalkworkflow_1_0.models.QuerySchemaByProcessCodeHeaders();
        querySchemaByProcessCodeHeaders.xAcsDingtalkAccessToken = token;
        com.aliyun.dingtalkworkflow_1_0.models.QuerySchemaByProcessCodeRequest querySchemaByProcessCodeRequest = new com.aliyun.dingtalkworkflow_1_0.models.QuerySchemaByProcessCodeRequest()
                .setProcessCode(processCode);
        try {
            QuerySchemaByProcessCodeResponse querySchemaByProcessCodeResponse = client.querySchemaByProcessCodeWithOptions(querySchemaByProcessCodeRequest, querySchemaByProcessCodeHeaders, new RuntimeOptions());
            return querySchemaByProcessCodeResponse.getBody().getResult();
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                log.info(err.code);
                log.info(err.message);
            }

        } 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.info(err.code);
                log.info(err.message);
            }

        }
        return new QuerySchemaByProcessCodeResponseBody.QuerySchemaByProcessCodeResponseBodyResult();
    }

    /**
     * 获取审批单流程中的节点信息
     */
    public ProcessForecastResponseBody.ProcessForecastResponseBodyResult getForecast(DingProcessInstanceVo instanceVo)
    {
        //获取access_token
        String token = accessTokenUtils.getToken();
        com.aliyun.dingtalkworkflow_1_0.Client client = createClient();
        com.aliyun.dingtalkworkflow_1_0.models.ProcessForecastHeaders processForecastHeaders = new com.aliyun.dingtalkworkflow_1_0.models.ProcessForecastHeaders();
        processForecastHeaders.xAcsDingtalkAccessToken = token;
        com.aliyun.dingtalkworkflow_1_0.models.ProcessForecastRequest processForecastRequest = new com.aliyun.dingtalkworkflow_1_0.models.ProcessForecastRequest();
        if(StringUtils.isNotNull(instanceVo.getDeptId())){
            processForecastRequest.setDeptId(instanceVo.getDeptId().intValue());
        }
        if(StringUtils.isNotEmpty(instanceVo.getUserId())){
            processForecastRequest.setUserId(instanceVo.getUserId());
        }
        if (StringUtils.isNotEmpty(instanceVo.getProcessCode())){
            processForecastRequest.setProcessCode(instanceVo.getProcessCode());
        }
        if (StringUtils.isNotNull(instanceVo.getFormComponentValues1())){
            processForecastRequest.setFormComponentValues(instanceVo.getFormComponentValues1());
        }
        try {
            ProcessForecastResponse processForecastResponse = client.processForecastWithOptions(processForecastRequest, processForecastHeaders, new RuntimeOptions());
            return processForecastResponse.getBody().getResult();
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                log.info(err.code);
                log.info(err.message);
            }

        } 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.info(err.code);
                log.info(err.message);
            }

        }
        return new ProcessForecastResponseBody.ProcessForecastResponseBodyResult();
    }

    /**
     * 获取指定用户可见的审批表单列表
     */
    public ListUserVisibleBpmsProcessesResponseBody.ListUserVisibleBpmsProcessesResponseBodyResult getTemplates(String userId, Long maxResults, Long nextToken)
    {
        //获取access_token
        String token = accessTokenUtils.getToken();
        com.aliyun.dingtalkworkflow_1_0.Client client = createClient();
        com.aliyun.dingtalkworkflow_1_0.models.ListUserVisibleBpmsProcessesHeaders listUserVisibleBpmsProcessesHeaders = new com.aliyun.dingtalkworkflow_1_0.models.ListUserVisibleBpmsProcessesHeaders();
        listUserVisibleBpmsProcessesHeaders.xAcsDingtalkAccessToken = token;
        com.aliyun.dingtalkworkflow_1_0.models.ListUserVisibleBpmsProcessesRequest listUserVisibleBpmsProcessesRequest = new com.aliyun.dingtalkworkflow_1_0.models.ListUserVisibleBpmsProcessesRequest()
                .setUserId(userId)
                .setMaxResults(maxResults)
                .setNextToken(nextToken);
        try {
            ListUserVisibleBpmsProcessesResponse listUserVisibleBpmsProcessesResponse = client.listUserVisibleBpmsProcessesWithOptions(listUserVisibleBpmsProcessesRequest, listUserVisibleBpmsProcessesHeaders, new RuntimeOptions());
            return listUserVisibleBpmsProcessesResponse.getBody().getResult();
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                log.info(err.code);
                log.info(err.message);
            }

        } 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.info(err.code);
                log.info(err.message);
            }

        }
        return new ListUserVisibleBpmsProcessesResponseBody.ListUserVisibleBpmsProcessesResponseBodyResult();
    }

    /**
     * 获取当前企业所有可管理的表单
     */
    public List<GetManageProcessByStaffIdResponseBody.GetManageProcessByStaffIdResponseBodyResult> getManageTemplates(String userId)
    {
        //获取access_token
        String token = accessTokenUtils.getToken();
        com.aliyun.dingtalkworkflow_1_0.Client client = createClient();
        com.aliyun.dingtalkworkflow_1_0.models.GetManageProcessByStaffIdHeaders getManageProcessByStaffIdHeaders = new com.aliyun.dingtalkworkflow_1_0.models.GetManageProcessByStaffIdHeaders();
        getManageProcessByStaffIdHeaders.xAcsDingtalkAccessToken = token;
        com.aliyun.dingtalkworkflow_1_0.models.GetManageProcessByStaffIdRequest getManageProcessByStaffIdRequest = new com.aliyun.dingtalkworkflow_1_0.models.GetManageProcessByStaffIdRequest()
                .setUserId(userId);
        try {
            GetManageProcessByStaffIdResponse manageProcessByStaffIdWithOptions = client.getManageProcessByStaffIdWithOptions(getManageProcessByStaffIdRequest, getManageProcessByStaffIdHeaders, new RuntimeOptions());
            return manageProcessByStaffIdWithOptions.getBody().getResult();
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                log.info(err.code);
                log.info(err.message);
            }

        } 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.info(err.code);
                log.info(err.message);
            }
        }
        return new ArrayList<>();
    }

    /**
     * 同意或拒绝审批任务
     */
    public Map<String,Boolean> handleProcessInstance(DingHandleVo handleVo)
    {
        Map<String,Boolean> map = new HashMap<>();
        //获取access_token
        String token = accessTokenUtils.getToken();
        com.aliyun.dingtalkworkflow_1_0.Client client = createClient();
        com.aliyun.dingtalkworkflow_1_0.models.ExecuteProcessInstanceHeaders executeProcessInstanceHeaders = new com.aliyun.dingtalkworkflow_1_0.models.ExecuteProcessInstanceHeaders();
        executeProcessInstanceHeaders.xAcsDingtalkAccessToken = token;
        com.aliyun.dingtalkworkflow_1_0.models.ExecuteProcessInstanceRequest executeProcessInstanceRequest = new com.aliyun.dingtalkworkflow_1_0.models.ExecuteProcessInstanceRequest();
        if (StringUtils.isNotEmpty(handleVo.getRemark())){
            executeProcessInstanceRequest.setRemark(handleVo.getRemark());
        }
        if (StringUtils.isNotEmpty(handleVo.getResult())){
            executeProcessInstanceRequest.setResult(handleVo.getResult());
        }
        if (StringUtils.isNotEmpty(handleVo.getProcessInstanceId())){
            executeProcessInstanceRequest.setProcessInstanceId(handleVo.getProcessInstanceId());
        }
        if (StringUtils.isNotNull(handleVo.getTaskId())){
            executeProcessInstanceRequest.setTaskId(handleVo.getTaskId());
        }
        if (StringUtils.isNotEmpty(handleVo.getActionerUserId())){
            executeProcessInstanceRequest.setActionerUserId(handleVo.getActionerUserId());
        }
        try {
            ExecuteProcessInstanceResponse executeProcessInstanceResponse = client.executeProcessInstanceWithOptions(executeProcessInstanceRequest, executeProcessInstanceHeaders, new RuntimeOptions());
            Boolean result = executeProcessInstanceResponse.getBody().getResult();
            Boolean success = executeProcessInstanceResponse.getBody().getSuccess();
            map.put("result",result);
            map.put("success",success);
            return map;
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                log.info(err.code);
                log.info(err.message);
            }

        } 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.info(err.code);
                log.info(err.message);
            }

        }
        return map;
    }

    /**
     * 转交OA审批任务
     */
    public Boolean transferInstance(DingTransferVo transferVo)
    {
        //获取access_token
        String token = accessTokenUtils.getToken();
        com.aliyun.dingtalkworkflow_1_0.Client client = createClient();
        com.aliyun.dingtalkworkflow_1_0.models.RedirectWorkflowTaskHeaders redirectWorkflowTaskHeaders = new com.aliyun.dingtalkworkflow_1_0.models.RedirectWorkflowTaskHeaders();
        redirectWorkflowTaskHeaders.xAcsDingtalkAccessToken = token;
        com.aliyun.dingtalkworkflow_1_0.models.RedirectWorkflowTaskRequest redirectWorkflowTaskRequest = new com.aliyun.dingtalkworkflow_1_0.models.RedirectWorkflowTaskRequest();
        if (StringUtils.isNotEmpty(transferVo.getOperateUserId())){
            redirectWorkflowTaskRequest.setOperateUserId(transferVo.getOperateUserId());
        }
        if (StringUtils.isNotEmpty(transferVo.getRemark())){
            redirectWorkflowTaskRequest.setRemark(transferVo.getRemark());
        }
        if (StringUtils.isNotEmpty(transferVo.getToUserId())){
            redirectWorkflowTaskRequest.setToUserId(transferVo.getToUserId());
        }
        if (StringUtils.isNotEmpty(transferVo.getActionName())){
            redirectWorkflowTaskRequest.setActionName(transferVo.getActionName());
        }
        if (StringUtils.isNotNull(transferVo.getTaskId())){
            redirectWorkflowTaskRequest.setTaskId(transferVo.getTaskId());
        }
        try {
            RedirectWorkflowTaskResponse redirectWorkflowTaskResponse = client.redirectWorkflowTaskWithOptions(redirectWorkflowTaskRequest, redirectWorkflowTaskHeaders, new RuntimeOptions());
            return redirectWorkflowTaskResponse.getBody().getResult();
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                log.info(err.code);
                log.info(err.message);
            }

        } 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.info(err.code);
                log.info(err.message);
            }
        }
        return false;
    }

    /**
     * 获取用户待审批数量
     */
    public Integer getUserTodoTasksNumbers(String userId)
    {
        //获取access_token
        String token = accessTokenUtils.getToken();
        com.aliyun.dingtalkworkflow_1_0.Client client = createClient();
        com.aliyun.dingtalkworkflow_1_0.models.GetUserTodoTaskSumHeaders getUserTodoTaskSumHeaders = new com.aliyun.dingtalkworkflow_1_0.models.GetUserTodoTaskSumHeaders();
        getUserTodoTaskSumHeaders.xAcsDingtalkAccessToken = token;
        com.aliyun.dingtalkworkflow_1_0.models.GetUserTodoTaskSumRequest getUserTodoTaskSumRequest = new com.aliyun.dingtalkworkflow_1_0.models.GetUserTodoTaskSumRequest()
                .setUserId(userId);
        try {
            GetUserTodoTaskSumResponse userTodoTaskSumWithOptions = client.getUserTodoTaskSumWithOptions(getUserTodoTaskSumRequest, getUserTodoTaskSumHeaders, new RuntimeOptions());
            return userTodoTaskSumWithOptions.getBody().getResult();
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                log.info(err.code);
                log.info(err.message);
            }
        } 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.info(err.code);
                log.info(err.message);
            }
        }
        return 0;
    }
}
