package com.zjty.tynotes.attendance.task;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiDepartmentListRequest;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.request.OapiUserGetDeptMemberRequest;
import com.dingtalk.api.request.OapiUserGetRequest;
import com.dingtalk.api.response.OapiDepartmentListResponse;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.dingtalk.api.response.OapiUserGetDeptMemberResponse;
import com.dingtalk.api.response.OapiUserGetResponse;
import com.taobao.api.ApiException;
import com.zjty.tynotes.attendance.dao.DingUserDao;
import com.zjty.tynotes.attendance.entity.DingUser;
import com.zjty.tynotes.pas.dao.PasUserDao;
import com.zjty.tynotes.pas.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

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

/**
 * @Author gwj
 * @create 2020/3/24 10:07
 */
@Component
public class MyInit implements CommandLineRunner {
    private static final Logger logger = LoggerFactory.getLogger(MyInit.class);

    @Value("${ding.tokenUrl}")
    private String tokenUrl;
    @Value("${ding.departmentListUrl}")
    private String departmentListUrl;
    @Value("${ding.departmentMenberUrl}")
    private String departmentMenberUrl;
    @Value("${ding.userDetailsUrl}")
    private String userDetailsUrl;

    @Autowired
    private PasUserDao pasUserDao;
    @Autowired
    private DingUserDao dingUserDao;

    public String token;

    public List<Long> dingDepartmentIds = new ArrayList<>();

    //从钉钉获取的所有人员的id
    public List<String> userIds = new ArrayList<>();

    //根据丁丁的人员名单与本地的人员名单作对比后需要绑定的人员
    public List<DingUser> dingUserList = new ArrayList<>();

    @Override
    public void run(String... args) throws Exception {
        getToken();
        getDepartmentList();
        getUserList();
        List<User> users = pasUserDao.findAll();
        List<DingUser> dingUsers = dingUserDao.findAll();
        for (String dingsuerId : userIds) {
            getUserDetails(dingsuerId,users,dingUsers);
        }
        dingUserDao.saveAll(dingUserList);
    }

    /**
     * 钉钉获取token接口
     * @return
     */
    public void getToken(){
        DefaultDingTalkClient client = new DefaultDingTalkClient(tokenUrl);
        OapiGettokenRequest request = new OapiGettokenRequest();
        request.setAppkey("dingpzurwgv19x9uzpgd");
        request.setAppsecret("PgRC88Q8ML4S_tabbg5Oxne2fE43eemrHE4mFutcFcnPur4jbs3HshN-cpJAkF7-");
        request.setHttpMethod("GET");
        try {
            OapiGettokenResponse response = client.execute(request);
            token = response.getAccessToken();
            System.out.println(token);
        } catch (ApiException e) {
            logger.error("获取钉钉token失败");
        }
    }

    /**
     * 获取部门列表
     * @return
     */
    public void getDepartmentList(){
        DingTalkClient client = new DefaultDingTalkClient(departmentListUrl);
        OapiDepartmentListRequest request = new OapiDepartmentListRequest();
        request.setHttpMethod("GET");
        try {
            OapiDepartmentListResponse response = client.execute(request, token);
            List<OapiDepartmentListResponse.Department> departments = response.getDepartment();
            if(departments!=null){
                for (OapiDepartmentListResponse.Department department : departments) {
                    dingDepartmentIds.add(department.getId());
                }
            }
        } catch (ApiException e) {
            logger.error("获取钉钉部门列表失败");
        }
    }

    /**
     * 获取用户列表
     * @return
     */
    public void getUserList(){
        DingTalkClient client = new DefaultDingTalkClient(departmentMenberUrl);
        OapiUserGetDeptMemberRequest req = new OapiUserGetDeptMemberRequest();
        req.setHttpMethod("GET");
        OapiUserGetDeptMemberResponse rsp = null;
        for (Long l : dingDepartmentIds) {
            req.setDeptId(""+l);
            try {
                rsp = client.execute(req,token);
                if(rsp!=null){
                    List<String> userIdList = rsp.getUserIds();
                    userIdList.forEach(str-> {
                        if (!userIds.contains(str)) {
                            userIds.add(str);
                        }
                    });
                }
            } catch (ApiException e) {
                logger.error("获取钉钉用户列表失败");
            }
        }
    }

    /**
     * 获取用户详情
     * @param userId
     * @param users
     * @param dingUsers
     */
    public void getUserDetails(String userId, List<User> users,List<DingUser> dingUsers){
        DingTalkClient client = new DefaultDingTalkClient(userDetailsUrl);
        OapiUserGetRequest request = new OapiUserGetRequest();
        request.setUserid(userId);
        request.setHttpMethod("GET");
        try {
            List<String> dingsuerIds = new ArrayList<>();
            if(dingUsers!=null){
                for (DingUser dingUser : dingUsers) {
                    dingsuerIds.add(dingUser.getDingUserId());
                }
            }
            OapiUserGetResponse user = client.execute(request, token);
            if(user!=null){
                if(!dingsuerIds.contains(user.getUserid())){
                    for (User user1 : users) {
                        if(user.getName().equals(user1.getUsername())){
                            logger.error(user.getUserid());
                            dingUserList.add(new DingUser(null,user1.getId(),user.getUserid()));
                        }
                    }
                }else{
                    DingUser dingUser2 = null;
                    if(dingUsers!=null){
                        for (DingUser dingUser : dingUsers) {
                            if(dingUser.getDingUserId().equals(user.getUserid())){
                                dingUser2 = dingUser;
                            }
                        }
                    }

                    for (User user1 : users) {
                        if(user.getName().equals(user1.getUsername())){
                            dingUser2.setDingUserId(user.getUserid());
                            dingUser2.setUserId(user1.getId());
                            logger.error("错误加入集合");
                            dingUserList.add(dingUser2);
                        }
                    }
                }
            }
        } catch (ApiException e) {
            logger.error("获取钉钉用户详情信息失败");
        }
    }

    /**
     * 每过一个小时准时获取一次token，因为钉钉的token会过期
     */
    @Scheduled(cron = "0 0 0/1 * * ? ")
    public void setToken(){
        getToken();
    }


}
