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


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollUtil;
import com.gic.business.order.dto.ordermanage.OrderInfoDTO;
import com.gic.business.order.service.ordermanage.WebOrderManageApiService;
import com.gic.haoban.manage.api.service.hm.HmQrcodeApiService;
import com.gic.haoban.manage.service.service.hm.HmQrcodeService;
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 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.CommonMQDTO;
import com.gic.haoban.manage.api.dto.DepartmentDTO;
import com.gic.haoban.manage.api.dto.QywxCallBackDTO;
import com.gic.haoban.manage.api.dto.SecretSettingDTO;
import com.gic.haoban.manage.api.dto.StaffClerkRelationDTO;
import com.gic.haoban.manage.api.dto.StaffDTO;
import com.gic.haoban.manage.api.dto.WxEnterpriseQwDTO;
import com.gic.haoban.manage.api.dto.notify.qdto.NoticeMessageQDTO;
import com.gic.haoban.manage.api.enums.ChannelCodeEnum;
import com.gic.haoban.manage.api.enums.NoticeMessageTypeEnum;
import com.gic.haoban.manage.api.enums.SecretTypeEnum;
import com.gic.haoban.manage.api.enums.WxEditType;
import com.gic.haoban.manage.api.service.HaobanCommonMQApiService;
import com.gic.haoban.manage.api.service.MessageApiService;
import com.gic.haoban.manage.api.service.StaffApiService;
import com.gic.haoban.manage.api.service.StaffClerkRelationApiService;
import com.gic.haoban.manage.api.util.notify.NoticeMessageUtil;
import com.gic.haoban.manage.service.config.Config;
import com.gic.haoban.manage.service.entity.TabHaobanDepartment;
import com.gic.haoban.manage.service.entity.TabHaobanStaff;
import com.gic.haoban.manage.service.entity.TabHaobanStaffDepartmentRelated;
import com.gic.haoban.manage.service.entity.TabHaobanWxApplication;
import com.gic.haoban.manage.service.entity.TabHaobanWxEnterprise;
import com.gic.haoban.manage.service.entity.TabHaobanWxEnterpriseRelated;
import com.gic.haoban.manage.service.service.DepartmentService;
import com.gic.haoban.manage.service.service.MemberQueryService;
import com.gic.haoban.manage.service.service.SecretSettingService;
import com.gic.haoban.manage.service.service.StaffDepartmentRelatedService;
import com.gic.haoban.manage.service.service.StaffService;
import com.gic.haoban.manage.service.service.WxApplicationService;
import com.gic.haoban.manage.service.service.WxEnterpriseRelatedService;
import com.gic.haoban.manage.service.service.WxEnterpriseService;
import com.gic.haoban.manage.service.service.chat.GroupChatService;
import com.gic.member.api.dto.es.MemberDataDTO;
import com.gic.mq.sdk.GicMQClient;
import com.gic.redis.data.util.RedisUtil;
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.QywxNewUseridDTO;
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 cn.hutool.core.convert.Convert;

import javax.persistence.criteria.Order;

/**
 * 接收企业微信或者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 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;
    @Autowired
    private MemberQueryService memberQueryService ;
    @Autowired
    private WebOrderManageApiService webOrderManageApiService ;
    @Autowired
    private HmQrcodeService hmQrcodeService;
    @Autowired
    private HmQrcodeApiService hmQrcodeApiService;


    @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;
        }
        TabHaobanWxApplication wxApplication = wxApplicationService.selectByCorpId(dto.getAuthCorpId());
        if (Objects.isNull(wxApplication)) {
            log.info("授权企业不存在，{}", dto.getAuthCorpId());
            return;
        }
        String wxEnterpriseId = wxApplication.getWxEnterpriseId();
        WxEnterpriseQwDTO qwDTO = this.wxEnterpriseService.getQwInfo(wxEnterpriseId) ;
        if(qwDTO.isSelf() && dto.getSelfCallback()==0) {
            log.info("非自建应用回调");
            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",
                // 润臣测试环境
                "b18ffdc9d0644912865a248859914d80",
                // 尊兴
                "fb40256db41142a196b21ccf03e58507",
                // 金华悦行
                "ac451a350eed4a96958dd5c7377f8bd9");
        return wxSet.contains(wxEnterpriseId);
    }

    /**
     * 处理同步导购(定制)
     *
     * @param dto
     * @param enterpriseId
     * @param secret
     */
    private void dealClerkUser(QywxCallBackDTO dto, String enterpriseId, String secret, String staffName ,  WxEnterpriseQwDTO qwDTO) {
       log.info("鸿星尔克={}",JSONObject.toJSONString(dto));
        ClerkQwDTO clerkQwDTO = new ClerkQwDTO();
        clerkQwDTO.setEnterpriseId(enterpriseId);
        String mainDeptId = dto.getMainDepartment();
        List<com.gic.wechat.api.dto.qywx.DepartmentDTO> departments = qywxDepartmentApiService
                .listSelfDepartment(qwDTO.getDkCorpid(), secret, Integer.valueOf(mainDeptId),qwDTO.getUrlHost());
        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();
        TabHaobanWxEnterprise  wxEnterprise = this.wxEnterpriseService.getEnterpriseBycorpId(corpId);
        if (Objects.isNull(wxEnterprise)) {
            log.info("授权企业不存在，{}", corpId);
            return;
        }
        String wxEnterpriseId = wxEnterprise.getWxEnterpriseId();
        String changeType = qywxCallBackDTO.getChangeType();
        WxEnterpriseQwDTO qwDTO = this.wxEnterpriseService.getQwInfo(wxEnterpriseId);
        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,qwDTO);
            }
        } else if (changeType.equals(WxEditType.UPDATE_USER.getCode())) {
            log.info("成员同步修改，userid:{}", userid);
            // 修改
            TabHaobanStaff oldStaff = this.staffService.selectByUserIdAndEnterpriseId(userid, wxEnterpriseId);
            if (oldStaff == null) {
                //员工可能修改userId，需要拿到openUserId再去查询一次
                if (qwDTO != null && (qwDTO.getWxSecurityType() == 1 || qwDTO.getWxSecurityType() == 3)){
                    String openUserid = getOpenUserid(userid, qwDTO);
                    if (StringUtils.isNotBlank(openUserid)){
                        oldStaff = this.staffService.selectByUserIdAndEnterpriseId(openUserid, wxEnterpriseId);
                    }
                }
            }
            if (oldStaff == null){
                log.error("成员同步更新失败，无历史员工数据：userid:{},wxEnterpriseId:{}", userid, wxEnterpriseId);
                return;
            }
            TabHaobanStaff staff = new TabHaobanStaff();
            if (!userid.equals(oldStaff.getWxUserId())){
                //userId可能也会更新
                staff.setWxUserId(userid);
            }
            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 ,qwDTO.getUrlHost());
            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);
            //活码删除
            List<Long> hmIdList = hmQrcodeService.queryByStaffIdAndOverFlag(staffId, wxEnterpriseId, 1);
            if(CollUtil.isNotEmpty(hmIdList)){
                for (Long hmId : hmIdList){
                    hmQrcodeApiService.delById(hmId,ChannelCodeEnum.ADMIN_UNBIND.getCode(),null);
                }
            }
        }
        log.error("成员同步结束");
    }
    private String getOpenUserid(String userId,WxEnterpriseQwDTO qwDTO) {
        List<QywxNewUseridDTO> list = qywxUserApiService.useridToOpenuserid(qwDTO.getThirdCorpid(), config.getWxSuiteid(), Collections.singletonList(userId));
        log.info("明文userId转密文={},{}", userId, JSON.toJSONString(list));
        if (CollectionUtils.isEmpty(list)) {
            return "";
        }
        return list.get(0).getOpen_userid();
    }

    /**
     * 处理部门
     *
     * @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();
        WxEnterpriseQwDTO qwDTO = this.wxEnterpriseService.getQwInfo(wxEnterpriseId) ;
        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 , qwDTO.getUrlHost());
            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(),qwDTO.getUrlHost());
            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));
    }

    public void updateForSyncStaff(String wxEnterpriseId, String staffName ,  WxEnterpriseQwDTO qwDTO , String qwUserId , String mainDeptId , String position ,
                                    Integer gender, String mobile , String nationcode ) {
        boolean suitWxEnterpriseIid = checkSuitEnterpriseId(wxEnterpriseId);
        if (suitWxEnterpriseIid) {
            QywxCallBackDTO qwUser = new QywxCallBackDTO() ;
            qwUser.setUserid(qwUserId);
            qwUser.setChangeType("create_user");
            qwUser.setMainDepartment(mainDeptId);
            qwUser.setPosition(position);
            qwUser.setGender(gender);
            qwUser.setMobile(mobile);
            qwUser.setTelephone(nationcode);
            // 鸿星尔克定制
            dealErKe(qwUser, wxEnterpriseId, staffName,qwDTO);
        }
    }
    /**
     * 处理鸿星尔克定制需求
     *
     * @param qywxCallBackDTO
     * @param wxEnterpriseId
     */
    private void dealErKe(QywxCallBackDTO qywxCallBackDTO, String wxEnterpriseId, String staffName ,  WxEnterpriseQwDTO qwDTO) {
        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,qwDTO);
        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;
        }
    }

    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 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
    @Deprecated
    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(qwDTO.getHbWxaAppid());
        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(), qwDTO.getSelf3thSecret(), messageDTO,qwDTO.isSelf(),qwDTO.getUrlHost());
        return com.gic.api.base.commons.ServiceResponse.success();
    }

    @Override
    public com.gic.api.base.commons.ServiceResponse<Void> sendOrderMessage(String enterpriseId,
            NoticeMessageTypeEnum noticeType, String relationId, String refundStoreId, String clerkId, String memberId,
            List<String> valueList) {
        log.info("订单消息通知={},{},{},refundStoreId={}", memberId, clerkId, relationId, refundStoreId);
        List<NoticeMessageQDTO> list = new ArrayList<>();
        if (StringUtils.isAnyBlank(enterpriseId, clerkId, memberId)) {
            return com.gic.api.base.commons.ServiceResponse.failure("9999", "必传参数没传");
        }
        NoticeMessageTypeEnum messageTypeEnum = NoticeMessageTypeEnum.getByType(noticeType.getType());
        if (messageTypeEnum == null) {
            return com.gic.api.base.commons.ServiceResponse.failure("9999", "消息类型不存在");
        }
        ClerkDTO clerkDTO = this.clerkService.getclerkById(clerkId);
        if (null == clerkDTO) {
            return com.gic.api.base.commons.ServiceResponse.failure("9999", "导购查不到");
        }
        String storeId = clerkDTO.getStoreId();
        // 如果是退款收货/核销门店
        if (StringUtils.isNotEmpty(refundStoreId) && !refundStoreId.equals(clerkDTO.getStoreId())) {
            log.info("收货门店不是归属门店,store={},{}", refundStoreId, clerkDTO.getStoreId());
            storeId = refundStoreId;
            ClerkDTO dz = this.clerkService.getClerkLeaderByStoreId(storeId);
            clerkId = dz.getClerkId();
        }
        Map<String, Object> extendContent = new HashMap<>();
        if (messageTypeEnum.equals(NoticeMessageTypeEnum.ORDER_PAY)) {
            extendContent.put("currentTab", 0);
        } else {
            extendContent.put("currentTab", 1);
        }
        // 如果是自提
        if (messageTypeEnum.equals(NoticeMessageTypeEnum.ORDER_TAKE)) {
            com.gic.api.base.commons.ServiceResponse<OrderInfoDTO> orderResp = this.webOrderManageApiService.getBaseOrderInfo(enterpriseId,relationId) ;
            OrderInfoDTO order = orderResp.getResult() ;
            if(null != order) {
                if(order.getBusinessType()==1) {
                    extendContent.put("currentTab", 1);
                }else if(order.getBusinessType()==2) {
                    extendContent.put("currentTab", 0);
                }else if(order.getBusinessType()==3) {
                    extendContent.put("currentTab", 2);
                }
            }else {
                log.info("订单未查到={}",relationId);
            }
        }
        Map<String, String> map = this.toMapValue(enterpriseId,memberId, valueList);
        NoticeMessageQDTO qdto = this.getDTO(enterpriseId, clerkId, relationId, noticeType, map, extendContent);
        list.add(qdto);
        ClerkDTO dz = this.clerkService.getClerkLeaderByStoreId(storeId);
        if (null != dz && !dz.getClerkId().equals(clerkId)) {
            NoticeMessageQDTO dzQdto = this.getDTO(enterpriseId, dz.getClerkId(), relationId, noticeType, map,
                    extendContent);
            list.add(dzQdto);
        }
        NoticeMessageUtil.sendNoticeMessageBatch(list);
        return com.gic.api.base.commons.ServiceResponse.success();
    }

    private NoticeMessageQDTO getDTO(String enterpriseId, String clerkId, String orderId,
            NoticeMessageTypeEnum noticeType, Map<String, String> map, Map<String, Object> extendContent) {
        NoticeMessageQDTO qdto = new NoticeMessageQDTO();
        qdto.setEnterpriseId(enterpriseId);
        qdto.setClerkId(clerkId);
        qdto.setMessageType(noticeType.getType());
        qdto.setContentMap(map);
        qdto.setOptTargetId(orderId);
        qdto.setCheckFlag(true);
        qdto.setExtendContent(extendContent);
        return qdto;
    }

    private Map<String, String> toMapValue(String enterpriseId ,String memberId, List<String> valueList) {
        Map<String, String> map = new HashMap<>();
        if (CollectionUtils.isNotEmpty(valueList)) {
            for (int i = 0; i < valueList.size(); i++) {
                String key = "" + (i + 1);
                map.put(key, valueList.get(i));
                if (key.equals("1")) {
                    map.put("goodsName", valueList.get(i));
                }
            }
        }
        MemberDataDTO member = this.findMember(enterpriseId,memberId);
        map.put("memberName", member.getName());
        return map;
    }
    
    private MemberDataDTO findMember(String enterpriseId, String memberId) {
        String returnFields = "memberId,mainStoreId,mainClerkId,openStoreId,openClerkId,name,nickName,phoneNumber,photoUrl,cardNo";
        JSONObject memberObj = this.memberQueryService.queryDataSingle(enterpriseId, memberId, returnFields);
        if (null == memberObj) {
            return new MemberDataDTO();
        }
        MemberDataDTO memberDataDTO = memberObj.toJavaObject(MemberDataDTO.class);
        if (StringUtils.isEmpty(memberDataDTO.getName())) {
            memberDataDTO.setName(memberDataDTO.getNickName());
        }
        return memberDataDTO;
    }

}
