package com.artfess.integrate.persistence.manager.impl;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiDepartmentListRequest;
import com.dingtalk.api.request.OapiUserListbypageRequest;
import com.dingtalk.api.response.OapiDepartmentListResponse;
import com.dingtalk.api.response.OapiDepartmentListResponse.Department;
import com.dingtalk.api.response.OapiUserListbypageResponse;
import com.dingtalk.api.response.OapiUserListbypageResponse.Userlist;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.artfess.base.feign.UCFeignService;
import com.artfess.base.model.CommonResult;
import com.artfess.base.util.BeanUtils;
import com.artfess.base.util.HttpUtil;
import com.artfess.base.util.JsonUtil;
import com.artfess.base.util.StringUtil;
import com.artfess.integrate.consts.DingTalkConsts;
import com.artfess.integrate.model.WxUser;
import com.artfess.integrate.persistence.manager.IUserService;
import com.artfess.integrate.util.DingTalkHttpUtil;
import com.artfess.integrate.util.DingTalkTokenUtil;
import com.artfess.integrate.util.OrgConvertUtil;
import com.artfess.integrate.util.ThreadMessageUtil;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

/**
 * <pre>
 * 阿里钉钉，用户同步类
 * 日期：2019-12-03
 * @author Pangquan
 * </pre>
 */
@Component
public class DtUserService implements IUserService {

    @Resource
    UCFeignService uCFeignService;

    @Override
    public void create(ObjectNode user) throws IOException {
        String fullname = user.get("fullname").asText();

        WxUser wxUser = OrgConvertUtil.userToWxUser(user);
        if (BeanUtils.isEmpty(wxUser.getDepartment())) return;
        String resultJson = null;
        try {

            resultJson = DingTalkHttpUtil.sendHttpsRequest(DingTalkConsts.getCreateUserUrl(), wxUser.toString(), "POST");
        } catch (Exception e) {
            // TODO: handle exception
            throw e;
        }
        JsonNode result = JsonUtil.toJsonNode(resultJson);

        String errcode = result.get("errcode").asText();

        if ("0".equals(errcode)) {
            ObjectNode userUnite = JsonUtil.getMapper().createObjectNode();
            userUnite.set("userId", user.get("userId"));
            userUnite.set("dingtalkId", user.get("account"));
            uCFeignService.updateUserUnite(userUnite);
            return;
        }
        // 表示已经存在
        if ("60102".equals(errcode)) {
            ObjectNode userUnite = JsonUtil.getMapper().createObjectNode();
            userUnite.set("userId", user.get("userId"));
            userUnite.set("dingtalkId", user.get("account"));
            uCFeignService.updateUserUnite(userUnite);
            return;
        }
        //手机号存在
        if ("60104".equals(errcode)) {
            ObjectNode userUnite = JsonUtil.getMapper().createObjectNode();
            userUnite.set("userId", user.get("userId"));
            String errmsg = result.get("errmsg").asText();
            String userid = errmsg.substring(errmsg.indexOf(":") + 1);
            userUnite.put("dingtalkId", userid);
            uCFeignService.updateUserUnite(userUnite);
            return;
        }
        String account = user.get("account").asText();
        ThreadMessageUtil.addMapMsg(fullname + "[" + account + "]", result.get("errmsg").asText());
    }

    public boolean queryUser(ObjectNode user) throws IOException {
        String account = user.get("account").asText();
        //获取企业微信用户，判断是否存在
        String getUserUrl = DingTalkConsts.getUserUrl() + account;
        String resultJsonUser = HttpUtil.sendHttpsRequest(getUserUrl, "", "GET");
        JsonNode userJson = JsonUtil.toJsonNode(resultJsonUser);

        if ("0".equals(userJson.get("errcode").asText())) {
            return true;
        }
        return false;
    }

    @Override
    public void update(ObjectNode user) throws IOException {

    }

    @Override
    public void delete(String userId) {
        // TODO Auto-generated method stub

    }

    @Override
    public void deleteAll(String userIds) {
        // TODO Auto-generated method stub

    }

    @Override
    public void addAll(JsonNode users) throws IOException {
        for (JsonNode user : users) {
            ObjectNode node = (ObjectNode) user;
            String mobile = user.get("mobile").asText();
            if ("null".equals(mobile) || StringUtil.isEmpty(mobile))
                continue;

            this.create(node);
        }

    }

    @Override
    public void syncUser(String[] lAryId) throws IOException {
        ArrayNode userList = JsonUtil.getMapper().createArrayNode();
//		iwxOrgService.syncAllOrg();//不同步组织结构，把用户都挂在顶级的组织上
        if (BeanUtils.isNotEmpty(lAryId)) {
            for (int i = 0; i < lAryId.length; i++) {
                ObjectNode user = (ObjectNode) uCFeignService.getUserById(lAryId[i]).getValue();
                if (user != null) userList.add(user);
            }
        } else {
            userList = (ArrayNode) uCFeignService.getUsersNotYetSyncDingtalk();
        }
        addAll(userList);

    }

    public void pullOrgAndUser(String orgId) throws Exception {
        //1、先拉取根部门用户
        this.pullUserByDepartmentId(orgId);
        //2、递归拉取子部门
        this.pullUser(orgId);
    }

    /**
     * 拉取组织和用户
     */
    @Override
    public void pullUser(String pOrgId) throws Exception {
        DingTalkClient client = new DefaultDingTalkClient(DingTalkConsts.getDepartmentListUrl());
        OapiDepartmentListRequest request = new OapiDepartmentListRequest();
        request.setId(pOrgId);
        request.setFetchChild(false);
        request.setHttpMethod("GET");
        OapiDepartmentListResponse response = client.execute(request, DingTalkTokenUtil.getToken());

        if (Long.valueOf(0).equals(response.getErrcode())) {
            List<Department> departmentList = response.getDepartment();
            for (Department o : departmentList) {
                String orgId = String.valueOf(o.getId());
                ObjectNode exist = uCFeignService.getOrgByIdOrCode(orgId);
                if (exist == null) {
                    exist = JsonUtil.getMapper().createObjectNode();
                    exist.put("id", o.getId());
                    exist.put("code", o.getId());
                    exist.put("name", o.getName());
                    exist.put("parentId", o.getParentid());
                    CommonResult<String> orgRsl = uCFeignService.addOrgFromExterUni(exist);
                    if (!orgRsl.getState()) {
                        throw new RuntimeException("写入组织架构失败：" + orgRsl.getMessage());
                    }
                }
                this.pullUser(orgId);
                this.pullUserByDepartmentId(orgId);
            }
        } else {
            throw new RuntimeException("获取钉钉通讯录的组织架构失败：" + response.getErrmsg());
        }
    }

    private void pullUserByDepartmentId(String orgId) throws Exception {
        DingTalkClient client = new DefaultDingTalkClient(DingTalkConsts.getUsersByDepartmentId());
        OapiUserListbypageRequest request = new OapiUserListbypageRequest();

        //分页查询
        Long offset = 0L;
        Long size = 100L;
        boolean hasNextData = true;
        while (hasNextData) {
            request.setDepartmentId(Long.valueOf(orgId));
            request.setHttpMethod("GET");
            request.setOffset(offset);
            request.setSize(size);
            request.setOrder("entry_desc");
            OapiUserListbypageResponse execute = client.execute(request, DingTalkTokenUtil.getToken());
            List<Userlist> userlist = execute.getUserlist();
            if (userlist == null || userlist.size() == 0) {
                hasNextData = false;
            }
            if (BeanUtils.isNotEmpty(userlist)) {
                for (Userlist o : userlist) {
                    String mobile = o.getMobile();
                    if (StringUtil.isNotEmpty(mobile)) {
                        CommonResult<JsonNode> userexist = uCFeignService.getUserByMobile(mobile);
                        if (BeanUtils.isEmpty(userexist) || !userexist.getState()) {
                            //创建用户
                            ObjectNode newUser = JsonUtil.getMapper().createObjectNode();
                            //最好使用手机号最为eip系统的账号，钉钉通讯录很多用户的userid都是很长一串数字，可读性差
                            newUser.put("account", mobile);
                            newUser.put("mobile", mobile);
                            newUser.put("fullname", o.getName());
                            newUser.put("password", "123456");

                            JsonNode persistent = uCFeignService.addUserFromExterUni(newUser);
                            //保存用户与部门的关系
                            uCFeignService.addUsersForOrg(orgId, mobile);

                            //绑定关系
                            ObjectNode userUnite = JsonUtil.getMapper().createObjectNode();
                            userUnite.set("userId", persistent.get("id"));
                            userUnite.put("dingtalkId", o.getUserid());
                            uCFeignService.updateUserUnite(userUnite);
                        } else {
                            //绑定关系
                            ObjectNode userUnite = JsonUtil.getMapper().createObjectNode();
                            userUnite.set("userId", userexist.getValue().get("id"));
                            userUnite.put("dingtalkId", o.getUserid());
                            uCFeignService.updateUserUnite(userUnite);
                        }
                    }
                }
            }
            offset++;
        }

    }

}
