package com.gic.haoban.manage.service.service.out.impl;

import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gic.clerk.api.dto.ClerkDTO;
import com.gic.clerk.api.dto.ClerkQwDTO;
import com.gic.clerk.api.service.ClerkService;
import com.gic.commons.util.EntityUtil;
import com.gic.commons.util.GICMQClientUtil;
import com.gic.commons.util.ImageUtil;
import com.gic.haoban.app.customer.service.api.service.InnerApiService;
import com.gic.haoban.base.api.common.Constant;
import com.gic.haoban.base.api.common.ServiceResponse;
import com.gic.haoban.manage.api.dto.*;
import com.gic.haoban.manage.api.enums.*;
import com.gic.haoban.manage.api.service.*;
import com.gic.haoban.manage.api.util.notify.NoticeMessageUtil;
import com.gic.haoban.manage.service.config.Config;
import com.gic.haoban.manage.service.entity.*;
import com.gic.haoban.manage.service.service.*;
import com.gic.haoban.manage.service.service.chat.GroupChatService;
import com.gic.mq.sdk.GicMQClient;
import com.gic.redis.data.util.RedisUtil;
import com.gic.thirdparty.api.service.QQCloudPicService;
import com.gic.thirdparty.cloudfile.CloudFileUtil;
import com.gic.thirdparty.cloudfile.enums.CloudFileBusinessOptEnum;
import com.gic.thirdparty.cloudfile.enums.CloudFileTypeEnum;
import com.gic.thirdparty.cloudfile.pojo.CloudFileInfo;
import com.gic.wechat.api.dto.qywx.ItemDTO;
import com.gic.wechat.api.dto.qywx.QywxXcxSendMessageDTO;
import com.gic.wechat.api.dto.qywx.UserDTO;
import com.gic.wechat.api.service.qywx.QywxDepartmentApiService;
import com.gic.wechat.api.service.qywx.QywxSuiteApiService;
import com.gic.wechat.api.service.qywx.QywxUserApiService;
import com.google.common.collect.Sets;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 接收企业微信或者gic推送消息进行处理
 * Created by tgs on 2020/2/20.
 */
@Service("messageApiService")
public class MessageApiServiceImpl implements MessageApiService {
    private static final Logger log = LogManager.getLogger(MessageApiServiceImpl.class);
    /**
     * 自建
     */
    private static final String SELF_APP = "selfSuiteId";
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private StaffService staffService;
    @Autowired
    private StaffDepartmentRelatedService staffDepartmentRelatedService;
    @Autowired
    private StaffApiService staffApiService;
    @Autowired
    private Config config;
    @Autowired
    private QywxDepartmentApiService qywxDepartmentApiService;
    @Autowired
    private InnerApiService innerApiService;
    @Autowired
    private StaffClerkRelationApiService staffClerkRelationApiService;
    @Autowired
    private QywxSuiteApiService qywxSuiteApiService;
    @Autowired
    private WxEnterpriseService wxEnterpriseService;
    @Autowired
    private StaffDepartmentRelatedApiService staffDepartmentRelatedApiService;
    @Autowired
    private WxEnterpriseRelatedService wxEnterpriseRelatedService;
    @Autowired
    private ClerkService clerkService;
    @Autowired
    private SecretSettingService secretSettingService;
    @Autowired
    private WxApplicationService wxApplicationService;
    @Autowired
    private QywxUserApiService qywxUserApiService;
    @Autowired
    private HaobanCommonMQApiService haobanCommonMQApiService ;
    @Autowired
    private GroupChatService groupChatService;

    @Override
    public void wxMessageReceive(QywxCallBackDTO qywxCallBackDTO) {
        GicMQClient clientInstance = GICMQClientUtil.getClientInstance();
        try {
            log.info("发送消息到dealWxMessageMq，{}", JSON.toJSONString(qywxCallBackDTO));
            clientInstance.sendMessage("dealWxMessageMq", JSON.toJSONString(qywxCallBackDTO));
        } catch (Exception e) {
            log.error("发送失败：{}", e.getMessage());
        }
    }

    @Override
    public void dealWxMessage(String param) {
        QywxCallBackDTO dto = JSON.parseObject(param, QywxCallBackDTO.class);
        log.info("【成员部门同步回调处理】dto={}", JSON.toJSONString(param));
        String suiteId = dto.getSuiteId();
        if (!SELF_APP.equals(suiteId)) {
            log.info("通讯录只处理自建应用回调 dto={}", JSON.toJSONString(param));
            return;
        }
        //处理部门
        dealQywxDepartment(dto);
        //处理成员
        dealQywxUser(dto);
    }

    /**
     * desc: 鸿星尔克定制需求校验-后期可扩展为配置形式
     *
     * @param dto dto
     * @return : {@link boolean}
     * @author : YongEn
     * @date : 2022/1/25
     */
    private boolean checkErkeDeal(QywxCallBackDTO dto) {
        if (Objects.isNull(dto) || StringUtils.isEmpty(dto.getUserid())) {
            return false;
        }
        if (!"create_user".equals(dto.getChangeType())) {
            log.info("只处理新增用户, 非 create_user 类型不做处理 当前传入类型:{}", dto.getChangeType());
            return false;
        }
        String userid = dto.getUserid();
        // 只处理5开头的-不是5开头不同步
        return userid.startsWith("5");
    }

    private boolean checkSuitEnterpriseId(String wxEnterpriseId) {
        Set<String> wxSet = Sets.newHashSet(
                // 鸿星尔克
                "e034e2bd5d0b44d3bf553c9f8204094c",
                //润臣测试环境
                "ca66a01b79474c40b3e7c7f93daf1a3b",
                //尊兴
                "c0c2186a947440aa8c0afbdd869ec043",
                //金华悦行
                "ac451a350eed4a96958dd5c7377f8bd9"
        );
        return wxSet.contains(wxEnterpriseId);
    }

    /**
     * 处理同步导购(定制)
     *
     * @param dto
     * @param enterpriseId
     * @param secret
     */
    private void dealClerkUser(QywxCallBackDTO dto, String enterpriseId, String secret, String staffName) {
        ClerkQwDTO clerkQwDTO = new ClerkQwDTO();
        clerkQwDTO.setEnterpriseId(enterpriseId);
        String mainDeptId = dto.getMainDepartment();
        List<com.gic.wechat.api.dto.qywx.DepartmentDTO> departments = qywxDepartmentApiService.listSelfDepartment(dto.getAuthCorpId(), secret, Integer.valueOf(mainDeptId));
        if (CollectionUtils.isEmpty(departments)) {
            log.info("通过主部门查询部门列表为空 mainDeptId:{}", mainDeptId);
            return;
        }
        Map<Integer, com.gic.wechat.api.dto.qywx.DepartmentDTO> departmentIdMap = departments.stream()
                .collect(Collectors.toMap(com.gic.wechat.api.dto.qywx.DepartmentDTO::getId, Function.identity(), (a, b) -> a));
        com.gic.wechat.api.dto.qywx.DepartmentDTO mainDept = departmentIdMap.get(Integer.valueOf(mainDeptId));
        String deptName = mainDept.getName();
        clerkQwDTO.setStoreName(deptName);
        clerkQwDTO.setClerkCode(dto.getUserid());
        clerkQwDTO.setClerkName(staffName);
        String position = dto.getPosition();
        log.info("职务名称：position:{}", position);
        clerkQwDTO.setClerkType(StringUtils.isBlank(position) ? 0 : position.contains("店长") ? 1 : 0);
        clerkQwDTO.setClerkGener(dto.getGender());
        clerkQwDTO.setPhoneNumber(dto.getMobile());
        clerkQwDTO.setNationcode(dto.getTelephone());
        // 调用换导购接口逻辑
        clerkService.syncClerkForQw(clerkQwDTO);
    }

    /**
     * 处理企业通讯录成员
     *
     * @param qywxCallBackDTO
     */
    private void dealQywxUser(QywxCallBackDTO qywxCallBackDTO) {
        String userid = qywxCallBackDTO.getUserid();
        log.info("成员同步开始：userid:{}", userid);
        if (StringUtils.isBlank(userid)) {
            log.info("成员为空");
            return;
        }
        String corpId = qywxCallBackDTO.getAuthCorpId();
        TabHaobanWxApplication wxApplication = wxApplicationService.selectByCorpId(corpId);
        if (Objects.isNull(wxApplication)) {
            log.info("授权企业不存在，{}", corpId);
            return;
        }
        String wxEnterpriseId = wxApplication.getWxEnterpriseId();
        String changeType = qywxCallBackDTO.getChangeType();

        if (changeType.equals(WxEditType.ADD_USER.getCode())) {
            log.info("成员同步新增，userid:{}", userid);
            //新增
            ServiceResponse serviceResponse = this.staffApiService.wxGetAdd(userid, wxEnterpriseId);
            // 校验适用企业-定制
            boolean suitWxEnterpriseIid = checkSuitEnterpriseId(wxEnterpriseId);
            if (suitWxEnterpriseIid) {
                String staffName = Convert.toStr(serviceResponse.getResult());
                //鸿星尔克定制
                dealErKe(qywxCallBackDTO, wxEnterpriseId, staffName);
            }
        } else if (changeType.equals(WxEditType.UPDATE_USER.getCode())) {
            log.info("成员同步修改，userid:{}", userid);
            //修改
            TabHaobanStaff oldStaff = this.staffService.selectByUserIdAndEnterpriseId(userid, wxEnterpriseId);
            if (oldStaff == null) {
                log.error("成员同步更新失败，无历史员工数据：userid:{},wxEnterpriseId:{}", userid, wxEnterpriseId);
                return;
            }
            TabHaobanStaff staff = new TabHaobanStaff();
            staff.setStaffId(oldStaff.getStaffId());
            staff.setPhoneNumber(qywxCallBackDTO.getMobile());
            staff.setNickName(qywxCallBackDTO.getAlias());
            staff.setSex(qywxCallBackDTO.getGender());
            staff.setStaffName(qywxCallBackDTO.getUserName());
            staff.setPostion(qywxCallBackDTO.getPosition());
            if (StringUtils.isNotBlank(qywxCallBackDTO.getAvatar())) {
                staff.setHeadImg(changeHeaderImageUrl(qywxCallBackDTO.getAvatar()));
            }
            staff.setNationCode("86");
            //激活状态
            if (qywxCallBackDTO.getStatus() != null && qywxCallBackDTO.getStatus() == 1) {
                staff.setActiveFlag(1);
            }
            String[] departArr = qywxCallBackDTO.getDepartment();
            StringBuilder departmentIds = new StringBuilder();
            //部门修改了
            if (departArr != null) {
                for (String s : departArr) {
                    TabHaobanDepartment department = this.departmentService.getByWxId(s, wxEnterpriseId);
                    if (department == null) {
                        log.info("成员同步，部门不存在");
                        Map<String,Object> map = new HashMap<>() ;
                        map.put("staffId", staff.getStaffId()) ;
                        CommonMQDTO dto = new CommonMQDTO();
                        dto.setType(2);
                        dto.setParams(map);
                        this.haobanCommonMQApiService.putCommonDelayMessage(dto, 180);
                        continue;
                    }
                    departmentIds.append(department.getDepartmentId()).append(",");
                }
                if (departmentIds.length() > 0) {
                    departmentIds = new StringBuilder(departmentIds.substring(0, departmentIds.length() - 1));
                }
            } else {
                //部门没有修改
                List<TabHaobanStaffDepartmentRelated> list = staffDepartmentRelatedService.listStaffDepartmentByStaffId(staff.getStaffId());
                if (CollectionUtils.isNotEmpty(list)) {
                    for (TabHaobanStaffDepartmentRelated tabHaobanStaffDepartmentRelated : list) {
                        departmentIds.append(tabHaobanStaffDepartmentRelated.getDepartmentId()).append(",");
                    }
                    if (departmentIds.length() > 0) {
                        departmentIds = new StringBuilder(departmentIds.substring(0, departmentIds.length() - 1));
                    }
                }
            }
            StaffDTO staffDTO = EntityUtil.changeEntityByJSON(StaffDTO.class, staff);
            staffApiService.staffEdit(staffDTO, departmentIds.toString());
        } else if (changeType.equals(WxEditType.DELETE_USER.getCode())) {
            log.info("成员同步删除，userid:{}", userid);
            SecretSettingDTO secretSetting = secretSettingService.getSecretSetting(wxEnterpriseId, SecretTypeEnum.CUSTOMIZED_APP.getVal());
            if (null == secretSetting || secretSetting.getCheckFlag() == 0) {
                log.info("没有配置secret,wxEnterpriseId:{}", wxEnterpriseId);
                return;
            }

            UserDTO user = qywxUserApiService.getSelfWorkWxUser(corpId, secretSetting.getSecretVal(), userid);
            if (null != user) {
                Integer status = user.getStatus();
                // 1=已激活，2=已禁用，4=未激活，5=退出企业。
                log.info("企业微信用户状态：{}", status);
                if (status == 1) {
                    log.info("企业微信用户存在，并且已激活无需删除:{}:{}", wxEnterpriseId, userid);
                    return;
                }
            }
            //删除
            TabHaobanStaff oldStaff = this.staffService.selectByUserIdAndEnterpriseId(userid, wxEnterpriseId);
            if (oldStaff == null) {
                log.info("微信成员同步删除的门店不存在，{}", userid);
                return;
            }
            String staffId = oldStaff.getStaffId();
            //销毁卡券
            innerApiService.delCardByStaffId(staffId);
            //删除导购好友关联关系表
            this.staffDepartmentRelatedService.delByStaffid(staffId);
            //员工解绑
            List<StaffClerkRelationDTO> staffClerkRelationDTOS = staffClerkRelationApiService.listByStaffId(wxEnterpriseId, staffId);
            if (CollectionUtils.isNotEmpty(staffClerkRelationDTOS)) {
                for (StaffClerkRelationDTO staffClerkRelationDTO : staffClerkRelationDTOS) {
                    staffClerkRelationApiService.unbindByStaffAndClerkId(staffId, staffClerkRelationDTO.getClerkId(), ChannelCodeEnum.ADMIN_UNBIND.getCode(),wxEnterpriseId);
                }
            }
            //群状态刷新
            this.groupChatService.ownerDimission(staffId);
            //删除员工表-注意顺序
            this.staffService.delByStaffId(staffId);
        }
        log.error("成员同步结束");
    }

    /**
     * 处理部门
     *
     * @param qywxCallBackDTO
     */
    private void dealQywxDepartment(QywxCallBackDTO qywxCallBackDTO) {
        log.info("处理部门start:{}", JSON.toJSONString(qywxCallBackDTO));
        Integer wxDeptId = qywxCallBackDTO.getId();
        if (wxDeptId == null) {
            log.info("部门为空");
            return;
        }
        String authCorpId = qywxCallBackDTO.getAuthCorpId();
        DepartmentDTO departmentDTO = new DepartmentDTO();
        departmentDTO.setIsStore(0);
        TabHaobanWxApplication wxApplication = wxApplicationService.selectByCorpId(authCorpId);
        if (Objects.isNull(wxApplication)) {
            log.info("授权企业不存在，{}", qywxCallBackDTO.getAuthCorpId());
            return;
        }
        String wxEnterpriseId = wxApplication.getWxEnterpriseId();
        SecretSettingDTO secretSetting = secretSettingService.getSecretSetting(wxEnterpriseId, SecretTypeEnum.CUSTOMIZED_APP.getVal());
        if (null == secretSetting || secretSetting.getCheckFlag() == 0) {
            log.info("没有配置secret：{}", wxEnterpriseId);
            return;
        }
        String secret = secretSetting.getSecretVal();
        TabHaobanDepartment parentDepartment = new TabHaobanDepartment();
        if (qywxCallBackDTO.getParentId() != null) {
            parentDepartment = this.departmentService.getByWxId(qywxCallBackDTO.getParentId() + "", wxEnterpriseId);
        } else {
            TabHaobanDepartment oldDepartment = this.departmentService.getByWxId(wxDeptId + "", wxEnterpriseId);
            if (oldDepartment != null) {
                parentDepartment = departmentService.selectById(oldDepartment.getParentDepartmentId());
            }
        }
        String changeType = qywxCallBackDTO.getChangeType();
        if (!changeType.equals(WxEditType.DELETE_DEPART.getCode())) {
            if (parentDepartment == null) {
                log.info("企微同步父部门不存在");
                return;
            }
            com.gic.wechat.api.dto.qywx.DepartmentDTO deptDetail = qywxDepartmentApiService.getSelfDepartmentById(authCorpId, secret, wxDeptId);
            departmentDTO.setDepartmentName(deptDetail.getName());
            departmentDTO.setParentDepartmentId(parentDepartment.getDepartmentId());
            departmentDTO.setChainId(parentDepartment.getChainId() + Constant.ID_SEPARATOR + parentDepartment.getDepartmentId());
            departmentDTO.setChainName(parentDepartment.getChainName() + parentDepartment.getChainName());
            departmentDTO.setLevel(parentDepartment.getLevel() + 1);
        }
        departmentDTO.setWxEnterpriseId(wxEnterpriseId);
        departmentDTO.setWxDepartmentId(wxDeptId + "");
        if (qywxCallBackDTO.getParentId() != null) {
            List<com.gic.wechat.api.dto.qywx.DepartmentDTO> list = this.qywxDepartmentApiService.listSelfDepartment(authCorpId, secret, qywxCallBackDTO.getParentId());
            if (CollectionUtils.isNotEmpty(list)) {
                for (com.gic.wechat.api.dto.qywx.DepartmentDTO wxDepartmentDTO : list) {
                    if (Convert.toStr(wxDepartmentDTO.getId()).equals(departmentDTO.getDepartmentId())) {
                        departmentDTO.setSort(qywxCallBackDTO.getOrder());
                    } else {
                        TabHaobanDepartment tab = this.departmentService.getByWxId(wxDepartmentDTO.getId() + "", wxEnterpriseId);
                        if (tab != null) {
                            tab.setSort(wxDepartmentDTO.getOrder());
                            this.departmentService.edit(EntityUtil.changeEntityByJSON(DepartmentDTO.class, tab));
                        }
                    }
                }
            }
        }
        if (changeType.equals(WxEditType.ADD_DEPART.getCode())) {
            log.info("企微新增部门同步");
            this.departmentService.add(departmentDTO);
        } else if (changeType.equals(WxEditType.UPDATE_DEPART.getCode())) {
            log.info("企微修改部门同步");
            TabHaobanDepartment department = this.departmentService.getByWxId(wxDeptId + "", wxEnterpriseId);
            if (department == null) {
                String response = this.departmentService.add(departmentDTO);
                log.info("企微同步新增部门：{}", JSON.toJSONString(response));
            } else {
                departmentDTO.setIsStore(department.getIsStore());
                departmentDTO.setDepartmentId(department.getDepartmentId());
                this.departmentService.edit(departmentDTO);
                log.info("企微修改部门同步完成");
            }
        } else if (changeType.equals(WxEditType.DELETE_DEPART.getCode())) {
            log.info("企微删除部门同步");
            TabHaobanDepartment department = this.departmentService.getByWxId(wxDeptId + "", wxEnterpriseId);
            if (department == null) {
                log.info("企微同步删除部门不存在");
            } else {
                this.departmentService.del(department.getDepartmentId());
                log.info("企微删除部门同步完成");
            }
        }
        RedisUtil.delLocalCache("department-list-cache-" + wxEnterpriseId);
        log.info("处理部门end:{}", JSON.toJSONString(qywxCallBackDTO));
    }

    /**
     * 处理鸿星尔克定制需求
     *
     * @param qywxCallBackDTO
     * @param wxEnterpriseId
     */
    private void dealErKe(QywxCallBackDTO qywxCallBackDTO, String wxEnterpriseId, String staffName) {
        log.info("成员同步定制化开始");
        // 处理定制-目前鸿星尔克用
        boolean checkErkeDeal = checkErkeDeal(qywxCallBackDTO);
        if (!checkErkeDeal) {
            log.info("不符合鸿星尔克需求,返回");
            return;
        }
        List<TabHaobanWxEnterpriseRelated> relatedList = wxEnterpriseRelatedService.getByWxEnterpriseId(wxEnterpriseId);
        if (CollectionUtils.isEmpty(relatedList)) {
            log.info("未查询到企业关联企业 wxEnt");
            return;
        }
        SecretSettingDTO secretSetting = secretSettingService.getSecretSetting(wxEnterpriseId, SecretTypeEnum.CUSTOMIZED_APP.getVal());
        if (null == secretSetting || secretSetting.getCheckFlag() == 0) {
            log.info("没有配置secret：{}", wxEnterpriseId);
            return;
        }
        dealClerkUser(qywxCallBackDTO, relatedList.get(0).getEnterpriseId(), secretSetting.getSecretVal(), staffName);
        log.info("成员同步定制化结束");
    }

    private String changeHeaderImageUrl(String headImgUrl) {
        try {
            log.info("图片headImgUrl:{}", headImgUrl);
            if (StringUtils.isBlank(headImgUrl)) {
                return headImgUrl;
            }
            byte[] data = ImageUtil.getImgbyte(headImgUrl);
//            PicUploadResDTO uploadPic = qqCloudPicService.uploadPic(GlobalVar.ctxPropertiesMap.get(GlobalInfo.QQPIC_KEY_ENTERPRISE), data);
            //默认后缀为jpg,企业factoryCode取gic内部使用的factoryCode
            String suffix="jpg";
            String factoryCode="gic_inner";
            CloudFileTypeEnum cloudFileTypeEnum = CloudFileTypeEnum.IMAGE;
            CloudFileInfo cloudFileInfo =  CloudFileUtil.uploadFile(data, suffix, cloudFileTypeEnum,factoryCode, CloudFileBusinessOptEnum.HAOBAN_COMMON);
            log.info("腾讯云万象优图返回" + JSON.toJSONString(cloudFileInfo));
            return cloudFileInfo.getOrgFileUrl();
        } catch (Exception e) {
            log.info("上传腾讯云万象优图返回失败了：{}", e.getMessage());
            return headImgUrl;
        }
    }

    @Override
    public Boolean sendFaceMessage(String clerkId, String memberId, String memberName, String arrivalTime, String storeId) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("memberId", memberId);
        jsonObject.put("storeId", storeId);
        String data = jsonObject.toJSONString();
        String pageUrl = staffDepartmentRelatedApiService.getPageUrl(AppPageType.FACE_ARRIVAL.getCode(), data);
        StaffClerkRelationDTO relation = staffClerkRelationApiService.getByClerkId(clerkId);
        if (relation == null) {
            log.info("clerkId未绑定:clerkId={}", clerkId);
            return false;
        }
        WxEnterpriseQwDTO qwDTO = this.wxEnterpriseService.getQwInfo(relation.getWxEnterpriseId());
        if (qwDTO == null) {
            log.info("企业为空");
            return false;
        }
        StaffDTO staffDTO = staffApiService.selectById(relation.getStaffId());
        String corpid = qwDTO.getThirdCorpid();
        String wxUserId = "";
        if (qwDTO.needOpenUserId3th()) {
            wxUserId = staffDTO.getWxOpenUseId();
        } else {
            wxUserId = staffDTO.getWxUserId();
        }
        QywxXcxSendMessageDTO messageDTO = new QywxXcxSendMessageDTO();
        Map<String, String> map = new HashMap<>();
        map.put("事件", "人脸匹配");
        map.put("会员", memberName);
        map.put("到店时间", arrivalTime);
        List<ItemDTO> items = getItemsList(map);
        ArrayList<String> list = new ArrayList<>();
        list.add(wxUserId);
        messageDTO.setAppid(config.getAppid());
        messageDTO.setUserIds(list);
        messageDTO.setPage(pageUrl);
        messageDTO.setTitle("我的顾客通知");
        messageDTO.setItems(items);
        return qywxSuiteApiService.sendMessage(corpid, config.getWxSuiteid(), messageDTO);
    }

    private List<ItemDTO> getItemsList(Map<String, String> map) {
        List<ItemDTO> items = new ArrayList();
        map.keySet().forEach(key -> {
            String value = map.get(key);
            ItemDTO dto = new ItemDTO();
            dto.setKey(key);
            dto.setValue(value);
            items.add(dto);
        });
        return items;
    }

    @Override
    public Boolean sendPerfectRemarkMessage(String clerkId, String memberId, String memberName, String customerTime, String orderId, String storeId) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("memberId", memberId);
        jsonObject.put("storeId", storeId);
        jsonObject.put("currentTab", 1);
        StaffClerkRelationDTO relation = staffClerkRelationApiService.getByClerkId(clerkId);
        if (relation == null) {
            log.info("clerkId未绑定:clerkId={}", clerkId);
            return false;
        }
        WxEnterpriseDTO wxEnterprise = wxEnterpriseService.selectById(relation.getWxEnterpriseId());
        if (wxEnterprise == null) {
            log.info("企业为空");
            return false;
        }
        StaffDTO staffDTO = staffApiService.selectById(relation.getStaffId());
        if (staffDTO == null) {
            return false;
        }
        Map<String, String> params = new HashMap<>();
        params.put("memberName", memberName);
        params.put("orderId", orderId);
        params.put("customerTime", customerTime);

        NoticeMessageUtil.sendNoticeMessage(relation.getEnterpriseId(), relation.getClerkId(), NoticeMessageTypeEnum.MEMBER_FACE.getType(), null, params, jsonObject);
        return true;

    }

    @Override
    public void sendWxMessage(String param) {
        log.info("发送企业微信消息：{}", param);
        if (StringUtils.isBlank(param)) {
            log.info("param参数为空");
            return;
        }
        JSONObject jsonObject = JSON.parseObject(param);
        String wxEnterpriseId = jsonObject.getString("wxEnterpriseId");
        String wxUserId = jsonObject.getString("wxUserId");
        String pageUrl = jsonObject.getString("pageUrl");
        String title = jsonObject.getString("title");
        String content = jsonObject.getString("content");
        String memberName = jsonObject.getString("memberName");
        WxEnterpriseQwDTO qwDTO = this.wxEnterpriseService.getQwInfo(wxEnterpriseId);
        if (qwDTO == null) {
            log.info("企业为空");
            return;
        }
        QywxXcxSendMessageDTO messageDTO = new QywxXcxSendMessageDTO();
        //后续map加判断可加参数
        Map<String, String> map = new HashMap<>();
        map.put("接收事件", content);
        map.put("接收人", memberName);
        List<ItemDTO> items = getItemsList(map);
        List<String> userList = new ArrayList<>();
        userList.add(wxUserId);
        messageDTO.setAppid(config.getAppid());
        messageDTO.setUserIds(userList);
        messageDTO.setPage(pageUrl);
        messageDTO.setTitle(title);
        messageDTO.setItems(items);
        qywxSuiteApiService.sendMessage(qwDTO.getThirdCorpid(), config.getWxSuiteid(), messageDTO);
    }

    @Override
    public String getNewWxUserIdByStaffId(String wxEnterpriseId, String staffId) {
        log.info("请求wxEnterpriseId:{},staffId:{}", wxEnterpriseId, staffId);
        WxEnterpriseQwDTO qwDTO = this.wxEnterpriseService.getQwInfo(wxEnterpriseId);
        if (qwDTO == null) {
            return "";
        }
        TabHaobanStaff tabHaobanStaff = staffService.selectById(staffId);
        if (tabHaobanStaff == null) {
            return "";
        }
        return qwDTO.needOpenUserId3th() ? tabHaobanStaff.getWxOpenUseId() : tabHaobanStaff.getWxUserId();
    }
    
    @Override
    public com.gic.api.base.commons.ServiceResponse<Void> sendPreMessage(String enterpriseId ,String storeId, String message) {
        log.info("线下预约通知,storeId={}",storeId);
        ClerkDTO clerkDTO = this.clerkService.getClerkLeaderByStoreId(storeId) ;
        if(null == clerkDTO) {
            log.info("店长查不到");
            return com.gic.api.base.commons.ServiceResponse.success() ;
        }
        String clerkId = clerkDTO.getClerkId() ;
        StaffClerkRelationDTO dto = this.staffClerkRelationApiService.getOneByClerkId(clerkId) ;
        if(null == dto) {
            log.info("导购成员未关联");
            return com.gic.api.base.commons.ServiceResponse.success() ;
        }
        String eid = dto.getEnterpriseId() ;
        if(!enterpriseId.equals(eid)) {
            log.info("导购成员关联多个");
            return com.gic.api.base.commons.ServiceResponse.success() ;
        }
        String wxEnterpriseId = dto.getWxEnterpriseId() ;
        String staffId = dto.getStaffId() ;
        WxEnterpriseQwDTO qwDTO = this.wxEnterpriseService.getQwInfo(wxEnterpriseId);
        if (qwDTO == null) {
            log.info("企业为空");
            return com.gic.api.base.commons.ServiceResponse.success() ;
        }
        StaffDTO staff = this.staffApiService.selectById(staffId) ;
        QywxXcxSendMessageDTO messageDTO = new QywxXcxSendMessageDTO();
        String wxUserId = staff.getWxUserId() ;
        if(qwDTO.needOpenUserId3th()) {
            wxUserId = staff.getWxOpenUseId() ;
        }
        messageDTO.setAppid(config.getAppid());
        messageDTO.setUserIds(Arrays.asList(wxUserId));
        messageDTO.setPage(NoticeMessageTypeEnum.OFFLINE_PRE.getPageUrl()+NoticeMessageTypeEnum.OFFLINE_PRE.getPageType());
        messageDTO.setTitle(NoticeMessageTypeEnum.OFFLINE_PRE.getName());
        Map<String, String> map = new HashMap<>();
        map.put("事件", message);
        List<ItemDTO> items = getItemsList(map);
        messageDTO.setItems(items);
        qywxSuiteApiService.sendMessage(qwDTO.getThirdCorpid(), config.getWxSuiteid(), messageDTO);
        return com.gic.api.base.commons.ServiceResponse.success() ;
    }

}
