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

import com.artfess.base.feign.UCFeignService;
import com.artfess.base.model.CommonResult;
import com.artfess.base.service.PropertyService;
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.WeChatWorkConsts;
import com.artfess.integrate.model.WxUser;
import com.artfess.integrate.persistence.manager.IUserService;
import com.artfess.integrate.persistence.manager.IWXOrgService;
import com.artfess.integrate.util.OrgConvertUtil;
import com.artfess.integrate.util.ThreadMessageUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

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

/**
 * 企业微信-用户同步service类
 *
 * @author Administrator
 */
@Component
public class WxUserService implements IUserService {
    private final Log logger = LogFactory.getLog(WxUserService.class);
    @Resource
    UCFeignService uCFeignService;
    @Resource
    IWXOrgService iwxOrgService;
    @Resource
    PropertyService propertyService;

    @Override
    public void create(ObjectNode user) throws IOException {
        String fullname = user.get("fullname").asText();
        //获取用户的主部门
        ArrayNode department = uCFeignService.getOrgListByUserId(user.get("userId").asText());
        if (department == null || BeanUtils.isEmpty(department)) {
            user.put("department", "1");
        } else {
            List<String> arr = new ArrayList<>();
            for (JsonNode node : department) {
                ObjectNode dept = (ObjectNode) node;
                arr.add(dept.get("id").asText());
            }
            user.put("department", StringUtil.join(arr, ","));
        }

        WxUser wxUser = OrgConvertUtil.userToWxUser(user);
        if (BeanUtils.isEmpty(wxUser.getDepartment())) return;
        String resultJson = null;
        try {
            resultJson = HttpUtil.sendHttpsRequest(WeChatWorkConsts.getCreateUserUrl(), wxUser.toString(), "POST");
        } catch (Exception e) {
            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("wxWorkId", user.get("account"));
            uCFeignService.updateUserUnite(userUnite);
            return;
        }
        // 表示已经存在
        if ("60102".equals(errcode)) {
            ObjectNode userUnite = JsonUtil.getMapper().createObjectNode();
            userUnite.set("userId", user.get("userId"));
            userUnite.set("wxWorkId", 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("wxWorkId", userid);
            uCFeignService.updateUserUnite(userUnite);
            return;
        }
        String account = user.get("account").asText();
        ThreadMessageUtil.addMapMsg(fullname + "[" + account + "]", result.get("errmsg").asText());
    }

    @Override
    public void update(ObjectNode user) throws IOException {
        WxUser wxUser = OrgConvertUtil.userToWxUser(user);

        //验证存在，即可更新
        String url = WeChatWorkConsts.getUpdateUserUrl();
        String resultJson = HttpUtil.sendHttpsRequest(url, wxUser.toString(), "POST");
        JsonNode result = JsonUtil.toJsonNode(resultJson);

        if (!"0".equals(result.get("errcode").asText())) {
            throw new RuntimeException(wxUser.getName() + "更新微信通讯录失败 ： " + result.get("errmsg").asText());
        }

    }

    @Override
    public void delete(String userId) throws IOException {
        String url = WeChatWorkConsts.getDeleteUserUrl() + userId;
        String resultJson = HttpUtil.sendHttpsRequest(url, "", "POST");
        JsonNode result = JsonUtil.toJsonNode(resultJson);
        if ("0".equals(result.get("errcode").asText())) return;

        throw new RuntimeException(userId + "删除微信通讯录失败 ： " + result.get("errmsg").asText());
    }

    @Override
    public void deleteAll(String userIds) throws IOException {

    }

    @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);
        }
    }

    public void invite(String wxUserId) throws IOException {
        ObjectNode inviteData = JsonUtil.getMapper().createObjectNode();
        inviteData.put("userid", wxUserId);
        inviteData.put("invite_tips", propertyService.getProperty("wx.invite_tips", "宏天流程业务平台邀请您关注！"));
        String resultJson = HttpUtil.sendHttpsRequest(WeChatWorkConsts.getInviteUserUrl(), inviteData.toString(), "POST");
        JsonNode result = JsonUtil.toJsonNode(resultJson);
        if ("0".equals(result.get("errcode").asText())) return;
        logger.error("微信邀请失败！" + result.get("errmsg").asText());
    }

    public boolean queryUser(ObjectNode user) throws IOException {
        //获取企业微信用户，判断是否存在
        String getUserUrl = WeChatWorkConsts.getUserUrl() + user.get("account").asText();

        String resultJsonUser = HttpUtil.sendHttpsRequest(getUserUrl, "", "POST");
        JsonNode userJson = JsonUtil.toJsonNode(resultJsonUser);

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

    @Override
    public void syncUser(String[] lAryId) throws IOException {
        iwxOrgService.syncAllOrg();
        ArrayNode userList = (ArrayNode) uCFeignService.getUsersNotYetSyncWxWork();
        addAll(userList);
    }

    /**
     * 拉取通讯录
     */
    @Override
    public void pullUser(String pOrgId) throws IOException {
        String url = WeChatWorkConsts.getDepartmentListUrl(pOrgId);
        String resultJson = HttpUtil.sendHttpsRequest(url, "", "GET");
        JsonNode result = JsonUtil.toJsonNode(resultJson);
        String errcode = result.get("errcode").asText();
        if ("0".equals(errcode)) {
            JsonNode departmentList = result.get("department");
            for (JsonNode o : departmentList) {
                ObjectNode node = (ObjectNode) o;
                String orgId = node.get("id").asText();
                ObjectNode exist = uCFeignService.getOrgByIdOrCode(orgId);
                if (exist == null) {
                    exist = JsonUtil.getMapper().createObjectNode();
                    exist.put("id", node.get("id").asText());
                    exist.put("code", node.get("id").asText());
                    exist.put("name", node.get("name").asText());
                    exist.put("parentId", node.get("parentid").asText());
                    exist.put("orderNo", node.get("order").asText());
                    CommonResult<String> orgRsl = uCFeignService.addOrgFromExterUni(exist);
                    if (!orgRsl.getState()) {
                        throw new RuntimeException("写入组织架构失败：" + orgRsl.getMessage());
                    }
                }
                this.pullUserByDepartmentId(orgId);
            }
        } else {
            throw new RuntimeException("获取企业微信通讯录的组织架构失败：" + result.get("errmsg").asText());
        }
    }

    /**
     * 拉取人员
     *
     * @param orgId
     * @throws IOException
     */
    private void pullUserByDepartmentId(String orgId) throws IOException {
        String url = WeChatWorkConsts.getUsersByDepartmentId(orgId, "0");
        String resultJson = HttpUtil.sendHttpsRequest(url, "", "GET");
        JsonNode result = JsonUtil.toJsonNode(resultJson);
        String errcode = result.get("errcode").asText();
        if ("0".equals(errcode)) {
            JsonNode userlist = result.get("userlist");
            for (JsonNode o : userlist) {
                ObjectNode wxWorkUser = (ObjectNode) o;
                String userid = BeanUtils.isNotEmpty(wxWorkUser.get("userid")) ? wxWorkUser.get("userid").asText() : "";
                String mobile = BeanUtils.isNotEmpty(wxWorkUser.get("mobile")) ? wxWorkUser.get("mobile").asText() : "";
                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.set("fullname", wxWorkUser.get("name"));
                        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("wxWorkId", userid);
                        uCFeignService.updateUserUnite(userUnite);
                    } else {
                        //绑定关系
                        ObjectNode userUnite = JsonUtil.getMapper().createObjectNode();
                        userUnite.set("userId", userexist.getValue().get("id"));
                        userUnite.put("wxWorkId", userid);
                        uCFeignService.updateUserUnite(userUnite);
                    }
                }
            }
        } else {
            throw new RuntimeException("获取部门id[" + orgId + "]的成员失败：" + result.get("errmsg").asText());
        }
    }

}
