package com.malk.aiwei.delegate;

import com.alibaba.fastjson.JSONObject;
import com.malk.aiwei.service.AWClint;
import com.malk.delegate.TBEvent;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * OA审批事件 [主项目也有实现, 添加 @Primary 优先注入主项目实现]
 * -
 * 取消方案: 撤销和拒绝流程不继续执行连接器, 因此不使用连接器与轮询审批记录方案 [低效而且占用较高钉钉api调次数];
 * 优化方案: 通过事件订阅实现实时同步所有审批状态, 定时查询钉钉回调失败记录 [配置钉钉事件Delegate, 添加定时任务]
 */
@Slf4j
@Service
@Primary
public class TBDelegate implements TBEvent {

    @Autowired
    private AWClint awClint;

    @Async
    @Override
    @SneakyThrows
    public void callBackTask(JSONObject eventJson) {
        String eventName = eventJson.getString("event");
        log.info("callBackTask, {}, {}", eventName, eventJson);

        if ("v3.task.taskflowstatus.update".equals(eventName)) {
            JSONObject data = eventJson.getJSONObject("data");
            awClint.taskLevelValidate(data);
            awClint.doApprove(data, false);
        } else if ("v3.task.customfield.update".equals(eventName)) {
            JSONObject data = eventJson.getJSONObject("data");
            System.out.println("1" + JSONObject.toJSONString(data));
            awClint.custFieldUpdate(data);
        }
    }

    @Async
    @Override
    @SneakyThrows
    public void callBackProject(JSONObject eventJson) {
        String eventName = eventJson.getString("event");
        log.info("callBackProject, {}", eventJson);
    }

}
