package com.zfire.mall.manager.logic.dingding;

import cn.hutool.core.convert.Convert;
import com.dingtalk.api.response.OapiV2DepartmentListsubResponse;
import com.dingtalk.api.response.OapiV2UserGetResponse;
import com.taobao.api.ApiException;
import com.zfire.mall.manager.plus.entity.DingdingUser;
import com.zfire.mall.manager.plus.service.DingdingUserService;
import com.zfire.mall.manager.utils.DingDingOAUtils;
import com.zfire.mall.manager.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author change
 */
@Service
public class DingDingLogic {

    @Autowired
    DingdingUserService dingdingUserService;
    
    @Autowired
    RedisUtil redisUtil;

    public String getAccessToken() {
        String dingi0uynjvfsw95ouqq = null;
        try {
            dingi0uynjvfsw95ouqq = DingDingOAUtils.getAccessToken("dingi0uynjvfsw95ouqq", "p49mWRQeCExryH_ZESKBxrSsYUGpTeDITN5ws-3gyuD15VzQlmYhY2800Ve1y7z6");
        } catch (ApiException e) {
            e.printStackTrace();
        }
        redisUtil.set("dingTalkRedis",dingi0uynjvfsw95ouqq,7200);
        return dingi0uynjvfsw95ouqq;
    }

    public void saveUserInfo() {
        List<OapiV2DepartmentListsubResponse.DeptBaseResponse> dingTalkRedis = DingDingOAUtils.getDept((String) redisUtil.get("dingTalkRedis"), null);
        List<DingdingUser> dingdingUser = new ArrayList<>();
        for (OapiV2DepartmentListsubResponse.DeptBaseResponse deptBaseResponse : dingTalkRedis) {
            List<String> deptUser = DingDingOAUtils.getDeptUser((String) redisUtil.get("dingTalkRedis"),deptBaseResponse.getDeptId());
            for (String s : deptUser) {
                OapiV2UserGetResponse.UserGetResponse deptUserDetails = DingDingOAUtils.getDeptUserDetails(s,(String) redisUtil.get("dingTalkRedis"));
                DingdingUser dingdingUser1 = new DingdingUser();
                dingdingUser1.setUserId(s);
                dingdingUser1.setUserName(deptUserDetails.getName());
                dingdingUser1.setDeptId(Convert.toStr(deptBaseResponse.getDeptId()));
                dingdingUser.add(dingdingUser1);
            }
        }
        dingdingUserService.saveBatch(dingdingUser);
    }
}
