package com.artfess.third.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.artfess.base.annotation.ApiGroup;
import com.artfess.base.conf.DingdingConfig;
import com.artfess.base.constants.ApiGroupConsts;
import com.artfess.base.dingding.utils.DingCallbackCrypto;
import com.artfess.base.model.CommonResult;
import com.artfess.third.service.DingdingService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 钉钉相关接口
 *
 * @Author : min.wu
 * @Date: 2022/07/19 09:56
 */

@RestController
@Slf4j
@Api(tags = "钉钉")
@RequestMapping("/api/dingding/")
@ApiGroup(group = {ApiGroupConsts.DEVICE_BIZ})
public class DingdingController {

    @Autowired
    private DingdingService dingdingService;

    @Autowired
    private DingdingConfig dingdingConfig;

    /**
     * 获取钉钉配置
     * @return
     */
    @ApiOperation(value = "获取钉钉配置（企业id）")
    @GetMapping("/config")
    public CommonResult<String> getDingTalkConfig() {
        Map<String, String> configMap = new HashMap<>();
        configMap.put("corpId", dingdingConfig.getCorpId());
        return CommonResult.success(configMap, "获取成功");
    }


    @ApiOperation(value = "钉钉事件回调接口")
    @PostMapping("/callBack")
    public Map<String, String> callBack(
            @RequestParam(value = "msg_signature", required = false) String msg_signature,
            @RequestParam(value = "timestamp", required = false) String timeStamp,
            @RequestParam(value = "nonce", required = false) String nonce,
            @RequestBody(required = false) JSONObject json) {
        try {
            log.info("------------------------");
            // 1. 从http请求中获取加解密参数

            // 2. 使用加解密类型
            // Constant.OWNER_KEY 说明：
            // 1、开发者后台配置的订阅事件为应用级事件推送，此时OWNER_KEY为应用的APP_KEY。
            // 2、调用订阅事件接口订阅的事件为企业级事件推送，
            //      此时OWNER_KEY为：企业的appkey（企业内部应用）或SUITE_KEY（三方应用）

            //参数分别填写Token、Aes_key和应用信息中的AppKey
            DingCallbackCrypto callbackCrypto = new DingCallbackCrypto(dingdingConfig.getToken(), dingdingConfig.getAeskey(), dingdingConfig.getAppKey());
            String encryptMsg = json.getString("encrypt");
            String decryptMsg = callbackCrypto.getDecryptMsg(msg_signature, timeStamp, nonce, encryptMsg);

            // 3. 反序列化回调事件json数据
            JSONObject eventJson = JSON.parseObject(decryptMsg);
            log.info("回调事件响应数据:{}", eventJson);
            String eventType = eventJson.getString("EventType");

            // 4. 根据EventType分类处理
            if ("check_url".equals(eventType)) {
                // 测试回调url的正确性
                log.info("测试回调url的正确性");
            } else if ("user_add_org".equals(eventType)) {
                // 处理通讯录用户增加事件
                log.info("发生了：" + eventType + "事件");
            } else {
                // 添加其他已注册的
                log.info("发生了：" + eventType + "事件");
            }

            // 5. 返回success的加密数据
            Map<String, String> successMap = callbackCrypto.getEncryptedMap("success");
            return successMap;

        } catch (DingCallbackCrypto.DingTalkEncryptException e) {
            e.printStackTrace();
        }
        return null;
    }

//    /**
//     * 根据免登授权码, 获取登录用户身份
//     *
//     * @param authCode 免登授权码
//     * @return
//     */
//    @GetMapping("/login")
//    public CommonResult<String> login(@RequestParam(value = "authCode") String authCode) {
//
//        return CommonResult.success(dingdingService.getUserInfo(authCode),"获取用户信息成功");
//
//    }

//    /**
//     * 创建用户
//     * @param dingdingUser
//     * @return
//     * @throws ApiException
//     */
//    @PostMapping("/createUser")
//    public OapiV2UserCreateResponse createDingdingUser(@RequestBody OapiV2UserCreateRequest dingdingUser) throws ApiException {
//        String accessToken = AccessTokenUtil.getAccessToken(dingdingConfig.getAppKey(), dingdingConfig.getAppSecret());
//        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/create");
//        OapiV2UserCreateResponse rsp = client.execute(dingdingUser, accessToken);
//        log.info("创建用户结果:{}", JSON.toJSONString(rsp));
//        return rsp;
//    }
//
//    /**
//     * 更新用户
//     * @param req
//     * @return
//     * @throws ApiException
//     */
//    @PostMapping("/updateUser")
//    public OapiV2UserUpdateResponse updateUser(@RequestBody OapiV2UserUpdateRequest req) throws ApiException {
//        String accessToken = AccessTokenUtil.getAccessToken(dingdingConfig.getAppKey(), dingdingConfig.getAppSecret());
//        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/update");
//        OapiV2UserUpdateResponse rsp = client.execute(req, accessToken);
//        log.info("更新用户结果:{}", JSON.toJSONString(rsp));
//        return rsp;
//
//    }
//
//
//
//    /**
//     * 创建部门
//     * @param req
//     * @return
//     * @throws ApiException
//     */
//    @PostMapping("/createDept")
//    public OapiV2DepartmentCreateResponse createDept(@RequestBody OapiV2DepartmentCreateRequest req) throws ApiException {
//        String accessToken = AccessTokenUtil.getAccessToken(dingdingConfig.getAppKey(), dingdingConfig.getAppSecret());
//        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/create");
//        OapiV2DepartmentCreateResponse rsp = client.execute(req, accessToken);
//        log.info("创建部门结果:{}", JSON.toJSONString(rsp));
//        return rsp;
//    }
//
//    /**
//     * 更新部门
//     * @param req
//     * @return
//     * @throws ApiException
//     */
//    @PostMapping("/updateDept")
//    public OapiV2DepartmentUpdateResponse createDingdingUser(@RequestBody OapiV2DepartmentUpdateRequest req) throws ApiException {
//        String accessToken = AccessTokenUtil.getAccessToken(dingdingConfig.getAppKey(), dingdingConfig.getAppSecret());
//        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/update");
//        OapiV2DepartmentUpdateResponse rsp = client.execute(req, accessToken);
//        log.info("更新部门结果:{}", JSON.toJSONString(rsp));
//        return rsp;
//    }
//
//    /**
//     * 部门列表
//     * @param req
//     * @return
//     * @throws ApiException
//     */
//    @PostMapping("/deptList")
//    public OapiV2DepartmentListsubResponse deptList(@RequestBody OapiV2DepartmentListsubRequest req) throws ApiException {
//        String accessToken = AccessTokenUtil.getAccessToken(dingdingConfig.getAppKey(), dingdingConfig.getAppSecret());
//        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/listsub");
//        OapiV2DepartmentListsubResponse rsp = client.execute(req, accessToken);
//        req.setDeptId(1L);
//        req.setLanguage("zh_CN");
//        log.info("部门列表结果:{}", JSON.toJSONString(rsp));
//        return rsp;
//    }
}
