//package com.gree.mall.manager.logic.tag;
//
//import com.alibaba.fastjson.JSONObject;
//import org.apache.commons.lang3.StringUtils;
//import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
//import com.gree.mall.manager.constant.Constant;
//import com.gree.mall.manager.logic.admin.ew.EnterpriseWechatWorkerLogic;
//import com.gree.mall.manager.logic.common.CommonLogic;
//import com.gree.mall.manager.logic.common.WorkWechatLogic;
//import com.gree.mall.manager.plus.entity.*;
//import com.gree.mall.manager.plus.service.EnterpriseWechatWorkerService;
//import com.gree.mall.manager.plus.service.ExternalUserService;
//import com.gree.mall.manager.plus.service.FollowUserService;
//import com.gree.mall.manager.plus.service.UserTagService;
//import com.gree.mall.manager.utils.DateUtils;
//import lombok.extern.slf4j.Slf4j;
//import me.chanjar.weixin.common.error.WxErrorException;
//import me.chanjar.weixin.common.error.WxRuntimeException;
//import me.chanjar.weixin.cp.bean.external.contact.ExternalContact;
//import me.chanjar.weixin.cp.bean.external.contact.FollowedUser;
//import me.chanjar.weixin.cp.bean.external.contact.WxCpExternalContactInfo;
//import org.springframework.beans.BeanUtils;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//
//import java.util.*;
//import java.util.concurrent.ExecutorService;
//import java.util.concurrent.Executors;
//import java.util.stream.Collectors;
//
//@Slf4j
//@Service
//public class AsyncWxTagLogic {
//    @Autowired
//    private WorkWechatLogic workWechatLogic;
//    @Autowired
//    CommonLogic commonLogic;
//    @Autowired
//    EnterpriseWechatWorkerLogic enterpriseWechatWorkerLogic;
//    @Autowired
//    private ExternalUserService externalUserService;
//    @Autowired
//    private UserTagService userTagService;
//    @Autowired
//    private FollowUserService followUserService;
//
//
//    public void syncWxUserData(String corpId,AdminCompanyWechat adminCompanyWechat) throws WxErrorException {
//        List<EnterpriseWechatWorker> userList = enterpriseWechatWorkerLogic.list(corpId);
//        if(CollectionUtils.isEmpty(userList)){
//            return;
//        }
//        this.requstCustomerData(userList,adminCompanyWechat);
//    }
//
//
//    private void requstCustomerData(List<EnterpriseWechatWorker> userList,AdminCompanyWechat adminCompanyWechat) throws WxErrorException, WxRuntimeException {
//
//        //外部联系人
//        List<ExternalUser> curExternalUserList = externalUserService.lambdaQuery()
//                .eq(ExternalUser::getAddType, true).list();
//        List<String> curExternalUnionidList = new ArrayList<>();
//        for(ExternalUser eu : curExternalUserList){
//            curExternalUnionidList.add(eu.getUserId() + eu.getExternalUserId());
//        }
//        //用户标签
//        List<UserTag> userTagList = userTagService.lambdaQuery()
//                .eq(UserTag::getAddType, true)
//                .list();
//        List<String> curUserTagIdList = userTagList.stream().map(o -> (o.getExternalUserId() + "_" + o.getTagId())).collect(Collectors.toList());
//        List<FollowUser> currFollowUsers = followUserService.list();
//        List<String> currFollowUserIds = currFollowUsers.stream().map(o -> (o.getExternalUserId() + "_" + o.getUserId())).collect(Collectors.toList());
//        for (EnterpriseWechatWorker wechatWorker : userList) {
//            String workUserId = wechatWorker.getWechatUserId();
//
//            //获取外部联系人id(获取客户列表)
//            List<String> externalUserIds  = workWechatLogic.getExternalUserIdByWorkUserId(workUserId,adminCompanyWechat);
//            if (CollectionUtils.isEmpty(externalUserIds)) {
//                continue;
//            }
//            for (String externalUserId : externalUserIds) {
//                //获取客户详情
//                WxCpExternalContactInfo wxCpExternalContactInfo =  workWechatLogic.getCustomerDetail(externalUserId,adminCompanyWechat);
//                if (wxCpExternalContactInfo == null) {
//                    continue;
//                }
//                //保存外部联系人
//                this.saveExternalUser(wxCpExternalContactInfo,curExternalUnionidList,workUserId,adminCompanyWechat.getCorpId());
//                //保存标签和添加了此客户的其他成员
//                this.saveCustomerData(wxCpExternalContactInfo, curUserTagIdList, currFollowUserIds,adminCompanyWechat);
//            }
//        }
//    }
//
//    /**
//     * 获取最新的外部联系人
//     */
//    public Map<String,Object> getLastExternalUser(String mobile,String lastExternalUserId) throws WxErrorException {
//
//        //广州售后服务的师傅
//        AdminCompanyWechat adminCompanyWechat = commonLogic.getAdminCompanyWechat(Constant.GD_COMPANY_WECHAT_ID);
//
//        EnterpriseWechatWorker one = enterpriseWechatWorkerLogic.getByMobile(mobile,adminCompanyWechat.getCorpId());
//        if(one == null){
//            return null;
//        }
//        String workUserId = one.getWechatUserId();
//        //查询外部联系人
//        List<ExternalUser> externalUsers = externalUserService.lambdaQuery()
//                .eq(ExternalUser::getExternalUserId, lastExternalUserId).list();
//        if(externalUsers.size() > 0){
//            ExternalUser externalUser = externalUsers.get(0);
//            Map<String,Object> map = new HashMap<>();
//            map.put("externalUserId",externalUser.getExternalUserId());
//            map.put("workUserId",workUserId);
//            map.put("avatar",externalUser.getAvatar());
//            map.put("name",externalUser.getName());
//            return map;
//        }
//
//        //所有外部联系人
//        List<String> externalUserIds  = workWechatLogic.miniApp(adminCompanyWechat).getExternalContactService().listExternalContacts(workUserId);
//        if(externalUserIds.size() == 0){
//            return null;
//        }
//        //查询当前所有外部联系人
//        List<ExternalUser> list = externalUserService.lambdaQuery().eq(ExternalUser::getUserId, workUserId)
//                .orderByDesc(ExternalUser::getCreateTime).list();
//        List<String> localUserIds = list.stream().map(ExternalUser::getExternalUserId).collect(Collectors.toList());
//        //最新的外部联系人
//        String lastUserId = "";
//        //过滤出最新的外部联系人
//        for(String externalUserId : externalUserIds){
//            if(localUserIds.contains(externalUserId)){
//                continue;
//            }
//            lastUserId = externalUserId;
//            break;
//        }
//        //没过滤出新的外部联系人，就拿最近5分钟最新的1个人
//        if(StringUtils.isBlank(lastUserId) && localUserIds.size() > 0){
//            if(list.get(0).getCreateTime().getTime() > DateUtils.getTimeByDay(new Date(),-5).getTime()) {
//                lastUserId = localUserIds.get(0);
//            }
//        }
//        if(StringUtils.isBlank(lastUserId)){
//            return null;
//        }
//        WxCpExternalContactInfo wxCpExternalContactInfo = workWechatLogic.getCustomerDetail(lastUserId,adminCompanyWechat);
//
//        //保存外部联系人
//        this.saveExternalUser(wxCpExternalContactInfo,null,workUserId,adminCompanyWechat.getCorpId());
//        //保存标签和添加了此客户的其他成员(交给定时器处理)
////            this.saveCustomerData(wxCpExternalContactInfo, curUserTagIdList, currFollowUserIds);
//
//        ExternalContact externalContact = wxCpExternalContactInfo.getExternalContact();
//        Map<String,Object> map = new HashMap<>();
//        map.put("externalUserId",externalContact.getExternalUserId());
//        map.put("workUserId",workUserId);
//        map.put("avatar",externalContact.getAvatar());
//        map.put("name",externalContact.getName());
//        return map;
//
//    }
//
//
//    /**
//     * 保存外部联系人所有信息(包含表钱)
//     * @param wxCpExternalContactInfo 外部联系人详情
//    //     * @param curExternalUnionidList 当前已同步到数据库的外部联系人id集合
//     * @param curUserTagIdList      当前已同步到数据库的标签id集合
//     * @param currFollowUserIds     添加了此外部联系员的成员id集合
//    //     * @param workUserId       当前成员id
//     */
//    private void saveCustomerData(WxCpExternalContactInfo wxCpExternalContactInfo,
//                                  List<String> curUserTagIdList, List<String> currFollowUserIds,
//                                  AdminCompanyWechat adminCompanyWechat) {
//
//        ExternalContact externalContact = wxCpExternalContactInfo.getExternalContact();
//
//        if (wxCpExternalContactInfo.getFollowedUsers() != null) {
//            List<UserTag> userTagList = new ArrayList<>();
//            List<FollowUser> followUserList = new ArrayList<>();
//
//
//            for (FollowedUser followedUser : wxCpExternalContactInfo.getFollowedUsers()) {
//                if(CollectionUtils.isNotEmpty(currFollowUserIds)
//                        && currFollowUserIds.contains(externalContact.getExternalUserId() + "_" + followedUser.getUserId())){
//                    continue;
//                }
//                FollowUser followUser = new FollowUser();
//                followUser.setCreateTime(new Date(followedUser.getCreateTime()*1000));
//                followUser.setUserId(followedUser.getUserId());
//                followUser.setExternalUserId(externalContact.getExternalUserId());
//                followUser.setDescription(followedUser.getDescription());
//                followUser.setRemark(followedUser.getRemark());
//                followUser.setRemarkMobiles(JSONObject.toJSONString(followedUser.getRemarkMobiles()));
//                followUser.setRemarkCorpName(followedUser.getRemarkCorpName());
//                followUser.setAddWay(followedUser.getAddWay());
//                followUser.setOperUserid(followedUser.getOperatorUserId());
//                followUser.setState(followedUser.getState());
//                currFollowUserIds.add(externalContact.getExternalUserId() + "_" + followedUser.getUserId());
//                followUserList.add(followUser);
//
//                //添加用户的标签
//                for (me.chanjar.weixin.cp.bean.external.contact.FollowedUser.Tag tag : followedUser.getTags()) {
//                    if(CollectionUtils.isNotEmpty(curUserTagIdList)
//                            && curUserTagIdList.contains(externalContact.getExternalUserId() + "_" + tag.getTagId())){
//                        continue;
//                    }
//                    UserTag userTag = new UserTag();
//                    userTag.setAddType(true);
//                    userTag.setCreateTime(new Date());
//                    userTag.setUnionId(externalContact.getUnionId());
//                    userTag.setExternalUserId(externalContact.getExternalUserId());
//                    userTag.setTagId(tag.getTagId());
//                    userTag.setUserid(followedUser.getUserId());
//                    userTag.setTagName(tag.getTagName());
//                    userTag.setTagType(tag.getType());
//                    userTag.setCompanyWechatId(adminCompanyWechat.getCompanyWechatId());
//                    userTag.setCompanyName(adminCompanyWechat.getCompanyName());
//                    curUserTagIdList.add(externalContact.getExternalUserId() + "_" + tag.getTagId());
//                    userTagList.add(userTag);
//                }
//            }
//
//            userTagService.saveBatch(userTagList);
//            followUserService.saveBatch(followUserList);
//        }
//
//    }
//
//
//
//    /**
//     * 保存外部联系人
//     * @param wxCpExternalContactInfo
//     * @param workUserId
//     */
//    private void saveExternalUser(WxCpExternalContactInfo wxCpExternalContactInfo,List<String> curExternalUnionidList,String workUserId,String corpId){
//        ExternalContact externalContact = wxCpExternalContactInfo.getExternalContact();
//        if(curExternalUnionidList == null){
//            curExternalUnionidList = new ArrayList<>();
//        }
//        if (CollectionUtils.isEmpty(curExternalUnionidList) || !curExternalUnionidList.contains(workUserId + externalContact.getExternalUserId())) {
//            curExternalUnionidList.add(workUserId + externalContact.getExternalUserId());
//            ExternalUser externalUser = new ExternalUser();
//            BeanUtils.copyProperties(externalContact, externalUser, "externalProfile");
//            externalUser.setExternalProfile(JSONObject.toJSONString(externalContact.getExternalProfile()));
//            externalUser.setCreateTime(new Date());
//            externalUser.setAddType(true);
//            externalUser.setCorpId(corpId);
//            externalUser.setUserId(workUserId);
//            externalUserService.save(externalUser);
//        }
//    }
//}
