package com.malk.mcli.controller;

import com.malk.server.common.McR;
import com.malk.service.aliwork.YDClient;
import com.malk.service.dingtalk.DDClient;
import com.malk.service.dingtalk.DDClient_Contacts;
import com.malk.service.dingtalk.DDClient_Workflow;
import com.malk.utils.UtilDateTime;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.Date;

/**
 * 错误抛出与拦截详见CatchException
 */
@Slf4j
@RestController
@RequestMapping("/ly")
public class LYControl {

    @Autowired
    private YDClient ydClient;

    @Autowired
    private DDClient ddClient;

    @Autowired
    private DDClient_Contacts ddClient_contacts;

    @Autowired
    private DDClient_Workflow ddClient_workflow;


    /**
     * 0723
     * 后端授权登录：
     * 1 获取授权authCode，非jsapi授权码，不适用：
     * api：https://open.dingtalk.com/document/orgapp/obtain-identity-credentials
     * 2.通过回调到url下是授权码，获取用户token
     * api：https://open.dingtalk.com/document/orgapp/obtain-user-token
     * 3.基于用户token，调用钉钉新版本个人待办，支持任务完成，接口会返回taskId
     * api：https://open.dingtalk.com/document/isvapp/api-createpersonaltodotask
     *  效果：脱离钉钉容器，实现用户信息获取进行单点登录；jsapi未容器内用户无感知授权
     * 问题：查询不到创建的个人待办的进展
     * <p>
     * 3个待办
     * - 旧版本，不支持完成任务
     * - 新版本，支持完成任务，但查询不到进展
     * - TB自由任务，创建后需要预期才会到待办里面显示
     */
    @GetMapping("todo")
    McR todo(@RequestParam String code) {

        // code: https://login.dingtalk.com/oauth2/auth?redirect_uri=https%3A%2F%2Fmc.cloudpure.cn%2F&response_type=code&client_id=dinghbynhnd2dbgypmsa&scope=095358016629044412 ding321c72787fffc78b35c2f4657eb6378f&prompt=consent
        String userToken = ddClient.getUserAccessToken(false, code);
        ddClient_workflow.createPersonalTodo(ddClient.getAccessToken(), userToken, UtilDateTime.formatDateTime(new Date()), Arrays.asList("095358016629044412"), null);

        return McR.success();
    }

    @GetMapping("test")
    McR test() {

        return McR.success();
    }
}
