package com.malk.service.dingtalk.impl;

import cn.hutool.core.util.ObjectUtil;
import com.malk.server.dingtalk.DDConf;
import com.malk.server.dingtalk.DDR;
import com.malk.server.dingtalk.DDR_New;
import com.malk.service.dingtalk.DDClient_Contacts;
import com.malk.service.dingtalk.DDClient_Workflow;
import com.malk.utils.UtilHttp;
import com.malk.utils.UtilMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * OA审批
 *
 * @apiNote https://open.dingtalk.com/document/orgapp/workflow-overview
 */
@Service
@Slf4j
public class DDImplClient_Workflow implements DDClient_Workflow {

    /**
     * 发起审批实例
     *
     * @apiNote https://open.dingtalk.com/document/orgapp-service/initiate-approval
     */
    @Override
    public String doProcessInstances(String access_token, String originatorUserId, String processCode, List formComponentValues, Map body_ext) {
        Map header = DDConf.initTokenHeader(access_token);
        Map body = UtilMap.map("originator_user_id, process_code, form_component_values", originatorUserId, processCode, formComponentValues);
        body.putAll(body_ext);
        DDR ddr = DDR.doPost("https://oapi.dingtalk.com/topapi/processinstance/create", header, DDConf.initTokenParams(access_token), body);
        return ddr.getProcessInstanceId();
    }

    /**
     * 获取单个审批实例详情
     *
     * @apiNote https://open.dingtalk.com/document/orgapp/obtains-the-details-of-a-single-approval-instance
     */
    @Override
    public Map getProcessInstanceId(String access_token, String processInstanceId) {
        Map header = DDConf.initTokenHeader(access_token);
        Map body = UtilMap.map("processInstanceId", processInstanceId);
        DDR_New ddr = DDR_New.doGet("https://api.dingtalk.com/v1.0/workflow/processInstances", header, body);
        return (Map) ddr.getResult();
    }

    /**
     * 撤销审批实例
     *
     * @apiNote https://open.dingtalk.com/document/orgapp-service/terminate-a-workflow-by-using-an-instance-id
     */
    @Override
    public boolean terminateRunningApprove(String access_token, String processInstanceId, boolean isSystem, String remark, String operatingUserId) {
        Map header = DDConf.initTokenParams(access_token);
        Map request = UtilMap.map("process_instance_id, is_system, remark, operating_userid", processInstanceId, isSystem, remark, operatingUserId);
        Map body = UtilMap.map("request", request);
        DDR r = (DDR) UtilHttp.doPost("https://oapi.dingtalk.com/topapi/process/instance/terminate", null, header, body, DDR.class);
        return (Boolean) r.getResult();
    }

    /**
     * 同意或拒绝审批任务
     *
     * @apiNote https://open.dingtalk.com/document/orgapp/approve-or-reject-the-approval-task
     */
    @Override
    public boolean executeRunningApprove(String access_token, String processInstanceId, String actionerUserId, String taskId, String result, String remark, Map file) {

        Map header = DDConf.initTokenHeader(access_token);
        Map body = UtilMap.map("processInstanceId, result, actionerUserId, taskId, file", processInstanceId, result, actionerUserId, taskId, file);
        UtilMap.putNotEmpty(body, "remark", remark);
        DDR_New r = DDR_New.doPost("https://api.dingtalk.com/v1.0/workflow/processInstances/execute", header, null, body);
        return (Boolean) r.getResult();
    }

    /**
     * 通知审批撤销
     *
     * @apiNote https://open.dingtalk.com/document/orgapp/notify-the-attendance-to-modify-the-punch-result-when-the
     **/
    @Override
    public boolean cancelRunningApprove(String access_token, String userid, String approve_id) {
        Map header = DDConf.initTokenParams(access_token);
        Map body = UtilMap.map("approve_id, userid", approve_id, userid);
        DDR r = (DDR) UtilHttp.doPost("https://oapi.dingtalk.com/topapi/attendance/approve/cancel", null, header, body, DDR.class);
        return (Boolean) r.getResult();
    }


    /**
     * 添加审批评论
     *
     * @apiNote https://open.dingtalk.com/document/orgapp-service/add-an-approval-comment
     */
    @Override
    public boolean commentApproveInstance(String access_token, String processInstanceId, File file, String
            text, String commentUserid) {
        Map header = DDConf.initTokenParams(access_token);
        Map body = UtilMap.map("process_instance_id, file, text, comment_userid", processInstanceId, file, text, commentUserid);
        Map req = UtilMap.map("request", body);
        DDR r = (DDR) UtilHttp.doPost("https://oapi.dingtalk.com/topapi/process/instance/comment/add", header, req, DDR.class);
        return (Boolean) r.getResult();
    }

    /**
     * 获取审批实例ID列表
     *
     * @apiNote https://open.dingtalk.com/document/orgapp/obtain-an-approval-list-of-instance-ids
     */
    @Override
    public Map getInstanceIds(String access_token, String processCode, long startTime, long endTime, Map body_ext) {
        Map header = DDConf.initTokenHeader(access_token);
        Map body = UtilMap.map("processCode, startTime, endTime", processCode, startTime, endTime);
        if (ObjectUtil.isNotNull(body_ext)) {
            body.putAll(body_ext);
        }
        if (!body.containsKey("maxResults")) {
            body.put("maxResults", 20);
        }
        if (!body.containsKey("nextToken")) {
            body.put("nextToken", 0);
        }
        DDR_New ddr_new = DDR_New.doPost("https://api.dingtalk.com/v1.0/workflow/processes/instanceIds/query", header, null, body);
        return (Map) ddr_new.getResult();
    }

    /**
     * 获取审批实例ID列表_全部
     */
    @Override
    public List<String> getInstanceIds_all(String access_token, String processCode, long startTime,
                                           long endTime, Map extInfo) {
        return _getInstanceIds_all(access_token, processCode, startTime, endTime, extInfo, new ArrayList());
    }

    // 递归查询
    private List<String> _getInstanceIds_all(String access_token, String processCode, long startTime,
                                             long endTime, Map extInfo, List dataList) {
        Map rsp = getInstanceIds(access_token, processCode, startTime, endTime, extInfo);
        dataList.addAll(((List) rsp.get("list")));
        if (rsp.containsKey("nextToken")) {
            extInfo.put("nextToken", rsp.get("nextToken"));
            _getInstanceIds_all(access_token, processCode, startTime, endTime, extInfo, dataList);
        }
        return dataList;
    }

    @Autowired
    private DDClient_Contacts ddClient_contacts;

    /**
     * 创建钉钉待办任务
     *
     * @apiNote https://open.dingtalk.com/document/isvapp/add-dingtalk-to-do-task
     */
    @Override
    public DDR_New createTBTask(String access_token, String createUserId, String subject, String description,
                                long dueTime, List<String> executorIds, List<String> participantIds, Map detailUrl,
                                boolean isOnlyShowExecutor, int priority, Map notifyConfigs) {
        String unionId = String.valueOf(ddClient_contacts.getUserInfoById(access_token, createUserId).get("unionid"));
        Map param = new HashMap();
        param.put("operatorId", unionId);
        Map body = new HashMap();
        body.put("subject", subject);
        if (StringUtils.isNotBlank(description)) body.put("description", description);
        if (dueTime > 0) body.put("dueTime", dueTime);
        if (ObjectUtil.isNotNull(executorIds)) {
            List<String> executorUnionIds = new ArrayList<>();
            for (String userId : executorIds) {
                executorUnionIds.add(String.valueOf(ddClient_contacts.getUserInfoById(access_token, userId).get("unionid")));
            }
            body.put("executorIds", executorUnionIds);
        }
        if (ObjectUtil.isNotNull(participantIds)) {
            List<String> participantUnionIds = new ArrayList<>();
            for (String userId : participantIds) {
                participantUnionIds.add(String.valueOf(ddClient_contacts.getUserInfoById(access_token, userId).get("unionid")));
            }
            body.put("participantIds", participantUnionIds);
        }
        if (ObjectUtil.isNotNull(detailUrl)) body.put("detailUrl", detailUrl);
        body.put("isOnlyShowExecutor", isOnlyShowExecutor);
        body.put("priority", priority);
        if (ObjectUtil.isNotNull(detailUrl)) body.put("notifyConfigs", notifyConfigs);
        return DDR_New.doPost("https://api.dingtalk.com/v1.0/todo/users/" + unionId + "/tasks", DDConf.initTokenHeader(access_token), param, body);
    }

    /**
     * 创建钉钉个人待办任务
     **/
    @Override
    public DDR_New createPersonalTodo(String access_token, String user_token, String subject, List<String> executorIds, Map extInfo) {

        // 转换 unionid
        executorIds = executorIds.stream()
                .map(userId -> UtilMap.getString(ddClient_contacts.getUserInfoById(access_token, userId), "unionid"))
                .collect(Collectors.toList());
        if (ObjectUtil.isNotNull(extInfo) && extInfo.containsKey("participantIds")) {
            List<String> participantIds = (List<String>) extInfo.get("participantIds");
            participantIds = participantIds.stream()
                    .map(userId -> UtilMap.getString(ddClient_contacts.getUserInfoById(access_token, userId), "unionid"))
                    .collect(Collectors.toList());
            extInfo.put("participantIds", participantIds);
        }
        // 创建钉钉待办, 不带 detailurl 地址
        Map body = UtilMap.map("subject, executorIds", subject, executorIds);
        UtilMap.putAll(body, extInfo);
        return DDR_New.doPost("https://api.dingtalk.com/v1.0/todo/users/me/personalTasks", DDConf.initTokenHeader(user_token), null, body);
    }
}
