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

import com.alibaba.fastjson.JSON;
import com.gic.api.base.commons.JSONResponse;
import com.gic.api.base.commons.Page;
import com.gic.commons.util.UniqueIdUtils;
import com.gic.haoban.common.utils.StringUtil;
import com.gic.haoban.manage.api.dto.WxEnterpriseQwDTO;
import com.gic.haoban.manage.api.dto.welcome.dto.WelcomeRemoveCheckDTO;
import com.gic.haoban.manage.api.dto.welcome.qdto.QueryWelcomeQDTO;
import com.gic.haoban.manage.api.enums.FriendSettingTypeEnum;
import com.gic.haoban.manage.api.enums.WelcomeMediaTypeEnum;
import com.gic.haoban.manage.api.enums.WelcomeRelationStatusEnum;
import com.gic.haoban.manage.api.enums.WelcomeSuitTypeEnum;
import com.gic.haoban.manage.api.enums.hm.HmWelcomeReferType;
import com.gic.haoban.manage.api.enums.hm.HmWelcomeType;
import com.gic.haoban.manage.service.dao.mapper.StaffDepartmentRelatedMapper;
import com.gic.haoban.manage.service.dao.mapper.TabHaobanFriendSettingMapper;
import com.gic.haoban.manage.service.dao.mapper.TabHaobanWelcomeMapper;
import com.gic.haoban.manage.service.dao.mapper.TabHaobanWelcomeMediaMapper;
import com.gic.haoban.manage.service.dao.mapper.TabHaobanWelcomeSuitRangMapper;
import com.gic.haoban.manage.service.dao.mapper.TabMiniprogramSettingMapper;
import com.gic.haoban.manage.service.entity.TabHaobanFriendSetting;
import com.gic.haoban.manage.service.entity.TabHaobanStaffDepartmentRelated;
import com.gic.haoban.manage.service.entity.TabHaobanWelcomeMedia;
import com.gic.haoban.manage.service.entity.TabHaobanWelcomeSuitRang;
import com.gic.haoban.manage.service.entity.TabMiniprogramSetting;
import com.gic.haoban.manage.service.entity.TabWelcome;
import com.gic.haoban.manage.service.pojo.bo.hm.HmLinkBO;
import com.gic.haoban.manage.service.pojo.bo.hm.HmQrcodeBO;
import com.gic.haoban.manage.service.pojo.bo.hm.HmWelcomeRelationBO;
import com.gic.haoban.manage.service.pojo.bo.welcome.FriendSettingDetailBO;
import com.gic.haoban.manage.service.pojo.bo.welcome.SaveFriendSettingBO;
import com.gic.haoban.manage.service.pojo.bo.welcome.SaveWelcomeBO;
import com.gic.haoban.manage.service.pojo.bo.welcome.SaveWelcomeMediaBO;
import com.gic.haoban.manage.service.pojo.bo.welcome.WelcomeDetailBO;
import com.gic.haoban.manage.service.pojo.bo.welcome.WelcomeListBO;
import com.gic.haoban.manage.service.pojo.bo.welcome.WelcomeMediaBO;
import com.gic.haoban.manage.service.pojo.bo.welcome.WelcomeReferBO;
import com.gic.haoban.manage.service.pojo.bo.welcome.WelcomeSuitDepartmentBO;
import com.gic.haoban.manage.service.pojo.bo.welcome.WelcomeSuitStaffBO;
import com.gic.haoban.manage.service.pojo.qo.WelcomeInfoQO;
import com.gic.haoban.manage.service.pojo.qo.WelcomeRelationQO;
import com.gic.haoban.manage.service.service.WelcomeService;
import com.gic.haoban.manage.service.service.WelcomeSuitRangService;
import com.gic.haoban.manage.service.service.WxEnterpriseService;
import com.gic.haoban.manage.service.service.hm.HmLinkService;
import com.gic.haoban.manage.service.service.hm.HmQrcodeService;
import com.gic.haoban.manage.service.service.hm.WelcomeRelationService;
import com.gic.wechat.api.enums.QywxMediaTypeEnum;
import com.gic.wechat.api.service.qywx.QywxSuiteApiService;
import com.github.pagehelper.PageHelper;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * desc：欢迎语接口服务实现
 *
 * @author: YongEn
 * @date: 2022/2/9
 **/
@Service
public class WelcomeServiceImpl implements WelcomeService {

    private static final Logger logger = LoggerFactory.getLogger(WelcomeServiceImpl.class);

    @Autowired
    private TabHaobanWelcomeMapper welcomeMapper;
    @Autowired
    private TabHaobanWelcomeMediaMapper welcomeMediaMapper;
    @Autowired
    private TabHaobanFriendSettingMapper friendSettingMapper;
    @Autowired
    private WelcomeSuitRangService welcomeSuitRangService;
    @Autowired
    private TabHaobanWelcomeSuitRangMapper welcomeSuitRangMapper;
    @Autowired
    private StaffDepartmentRelatedMapper staffDepartmentRelatedMapper;
    @Autowired
    private TabMiniprogramSettingMapper miniprogramSettingMapper;
    @Autowired
    private WelcomeRelationService welcomeRelationService;
    @Autowired
    private HmLinkService linkService;
    @Autowired
    private HmQrcodeService qrcodeService;
    @Autowired
    private QywxSuiteApiService qywxSuiteApiService ;
    @Autowired
    private WxEnterpriseService wxEnterpriseService ;
    private static final int WELCOME_LIMIT = 100;
    private static final int DEPARTMENT_NUM_LIMIT = 10000;
    private static final int STAFF_NUM_LIMIT = 2000;
    private static final int MEDIA_NUM_LIMIT = 9;

    @Override
    public Boolean saveWelcome(SaveWelcomeBO bo) {
        // 校验参数和阈值
        String checkString = saveWelcomeCheck(bo);
        if (StringUtils.isNotEmpty(checkString)) {
            throw new RuntimeException(checkString);
        }
        // 校验新增或更新
        TabWelcome welcome = checkAddOrUpdate(bo);
        if (Objects.isNull(welcome)) {
            // 新增欢迎语
            TabWelcome addWelcome = addWelcome(bo);
            // 新增欢迎语媒体
            addWelcomeMedia(addWelcome.getWelcomeId(), bo);
            // 新增适用部门
            welcomeSuitRangService.addSuitDepartment(addWelcome.getWelcomeId(), bo.getWxEnterpriseId(), bo.getSuitDepartmentAddList());
            // 新增适用员工
            welcomeSuitRangService.addSuitStaff(addWelcome.getWelcomeId(), bo.getWxEnterpriseId(), bo.getSuitStaffAddList());
            return Boolean.TRUE;
        }
        // 更新欢迎语
        TabWelcome updateWelcome = updateWelcome(welcome, bo);
        // 删除欢迎语所有媒体
        welcomeMediaMapper.removeByWelcomeId(updateWelcome.getWelcomeId());
        // 新增欢迎语媒体
        addWelcomeMedia(updateWelcome.getWelcomeId(), bo);
        // 新增适用部门
        welcomeSuitRangService.addSuitDepartment(updateWelcome.getWelcomeId(), bo.getWxEnterpriseId(), bo.getSuitDepartmentAddList());
        // 新增适用员工
        welcomeSuitRangService.addSuitStaff(updateWelcome.getWelcomeId(), bo.getWxEnterpriseId(), bo.getSuitStaffAddList());
        // 删除适用部门
        welcomeSuitRangService.deleteSuitDepartment(updateWelcome.getWelcomeId(), bo.getWxEnterpriseId(), bo.getSuitDepartmentDeleteList());
        // 删除适用员工
        welcomeSuitRangService.deleteSuitStaff(updateWelcome.getWelcomeId(), bo.getWxEnterpriseId(), bo.getSuitStaffDeleteList());
        return Boolean.TRUE;
    }

    private String saveWelcomeCheck(SaveWelcomeBO bo) {
        // 校验欢迎语数量、适用部门、适用员工数量
        if(null == bo.getWelcomeId()) {
            long count = welcomeMapper.countByWxEnterpriseId(bo.getWxEnterpriseId(), bo.getType());
            if (count >= WELCOME_LIMIT) {
                if (HmWelcomeType.NORMAL.getCode().equals(bo.getType())){
                    return "普通欢迎语最多可创建"+WELCOME_LIMIT+"条";
                }
                if (HmWelcomeType.SPECIAL.getCode().equals(bo.getType())){
                      return "特殊欢迎语最多可创建"+WELCOME_LIMIT+"条";
                }
                return "欢迎语条目超过限制";
            }
        }
        List<WelcomeSuitDepartmentBO> suitDepartmentList = bo.getSuitDepartmentAddList();
        if (CollectionUtils.isNotEmpty(suitDepartmentList)) {
            if (suitDepartmentList.size() > DEPARTMENT_NUM_LIMIT) {
                return "适用部门数量超过限制";
            }
        }
        List<WelcomeSuitStaffBO> suitStaffList = bo.getSuitStaffAddList();
        if (CollectionUtils.isNotEmpty(suitStaffList)) {
            if (suitStaffList.size() > STAFF_NUM_LIMIT) {
                return "适用员工数量超过限制";
            }
        }
        List<SaveWelcomeMediaBO> welcomeMediaList = bo.getWelcomeMediaList();
        if (CollectionUtils.isNotEmpty(welcomeMediaList) && welcomeMediaList.size() > MEDIA_NUM_LIMIT) {
            return "欢迎语附件数目超过限制";
        }
        return "";
    }

    private TabWelcome checkAddOrUpdate(SaveWelcomeBO bo) {
        String welcomeId = bo.getWelcomeId();
        if (StringUtils.isEmpty(welcomeId)) {
            return null;
        }
        return welcomeMapper.selectByPrimaryKey(bo.getWelcomeId());
    }

    private TabWelcome addWelcome(SaveWelcomeBO bo) {
        if (bo.getDefaultWelcomeFlag() == 1 && this.existDefaultWelcome(bo.getWxEnterpriseId())) {
            throw new RuntimeException("已存在全体成员欢迎语, 无法新增多条全员欢迎语");
        }
        TabWelcome welcome = new TabWelcome();
        welcome.setWelcomeId(StringUtil.randomUUID());
        welcome.setWxEnterpriseId(bo.getWxEnterpriseId());
        welcome.setTitle(bo.getTitle());
        welcome.setWelcomeContent(bo.getWelcomeContent());
        welcome.setOpenFlag(1);
        welcome.setStatusFlag(1);
        welcome.setCreateTime(new Date());
        welcome.setUpdateTime(new Date());
        welcome.setOperatorId(bo.getOperatorId());
        welcome.setOperatorName(bo.getOperatorName());
        welcome.setCreatorId(bo.getCreatorId());
        welcome.setCreatorName(bo.getCreatorName());
        welcome.setModifierId(bo.getModifierId());
        welcome.setModifierName(bo.getModifierName());
        welcome.setDefaultWelcomeFlag(bo.getDefaultWelcomeFlag());
        welcome.setType(bo.getType());
        welcomeMapper.insert(welcome);
        return welcome;
    }

    private TabWelcome updateWelcome(TabWelcome welcome, SaveWelcomeBO bo) {
        // 校验是否非全员欢迎语更新为全员欢迎语
        Integer defaultWelcomeFlag = welcome.getDefaultWelcomeFlag();
        Boolean existDefaultWelcome = this.existDefaultWelcome(bo.getWxEnterpriseId());
        // 不允许更新：当前更新的欢迎语非全员欢迎语并且存在全员欢迎语
        boolean notAllowUpdate = defaultWelcomeFlag == 0 && existDefaultWelcome && bo.getDefaultWelcomeFlag() == 1;
        if (notAllowUpdate) {
            throw new RuntimeException("禁止更新, 已存在全员欢迎语, 当前欢迎语不允许更新为全员欢迎语");
        }
        welcome.setTitle(bo.getTitle());
        welcome.setWelcomeContent(bo.getWelcomeContent());
        welcome.setUpdateTime(new Date());
        welcome.setOperatorId(bo.getOperatorId());
        welcome.setOperatorName(bo.getOperatorName());
        welcome.setDefaultWelcomeFlag(bo.getDefaultWelcomeFlag());
        welcome.setModifierId(bo.getModifierId());
        welcome.setModifierName(bo.getModifierName());
        welcomeMapper.updateByPrimaryKeySelective(welcome);
        return welcome;
    }

    private void addWelcomeMedia(String welComeId, SaveWelcomeBO bo) {
        if (CollectionUtils.isEmpty(bo.getWelcomeMediaList())) {
            return;
        }
        String wxEnterpriseId = bo.getWxEnterpriseId() ;
        WxEnterpriseQwDTO qwDTO = this.wxEnterpriseService.getQwInfo(wxEnterpriseId) ;
        boolean selfFlag = qwDTO.isSelf() ;
        List<TabHaobanWelcomeMedia> mediaList = bo.getWelcomeMediaList().stream().map(one -> {
            TabHaobanWelcomeMedia media = new TabHaobanWelcomeMedia();
            media.setWelcomeMediaId(UniqueIdUtils.uniqueLong());
            media.setWxEnterpriseId(bo.getWxEnterpriseId());
            media.setWelcomeId(welComeId);
            media.setMediaTitle(StringUtils.isEmpty(one.getMediaTitle()) ? "-1" : one.getMediaTitle());
            media.setMediaType(one.getMediaType());
            media.setMediaUrl(one.getMediaUrl());
            media.setMiniProgramPage(StringUtils.isEmpty(one.getMiniProgramPage()) ? "-1" : one.getMiniProgramPage());
            media.setMediaSize(one.getMediaSize());
            media.setMiniProgramId(one.getMiniprogramSettingId());
            media.setCreateTime(new Date());
            media.setDeleteFlag(0);
            if(5 == media.getMediaType() && StringUtils.isNotBlank(media.getMediaUrl())) {
                JSONResponse jp = qywxSuiteApiService.uploadMedia(qwDTO.getThirdCorpid(), qwDTO.getSelf3thSecret(), media.getMediaUrl(), "image", QywxMediaTypeEnum.IMAGE.getCode(),selfFlag,qwDTO.getUrlHost());
                if (jp.getErrorCode() == 0) {
                    media.setMediaId(jp.getResult().toString());
                    media.setMediaTime(new Date());
                } else {
                    throw new RuntimeException("处理图片异常");
                }
            }
            return media;
        }).collect(Collectors.toList());
        // 批量新增
        mediaList.forEach(one -> welcomeMediaMapper.insert(one));
    }

    @Override
    public Boolean removeWelcome(String welcomeId) {
        TabWelcome tabWelcome = new TabWelcome();
        tabWelcome.setWelcomeId(welcomeId);
        tabWelcome.setStatusFlag(0);
        int i = welcomeMapper.updateByPrimaryKeySelective(tabWelcome);
        return i > 0;
    }

    @Override
    public List<WelcomeListBO> listWelcome(String wxEnterpriseId, String title) {
        // 查询所有类型 默认 非默认
        List<TabWelcome> welcomeList = welcomeMapper.listByWxEnterpriseId(wxEnterpriseId, title, null);
        if (CollectionUtils.isEmpty(welcomeList)) {
            return Collections.emptyList();
        }
        // 组装数据, 转换数据
        return convertWelcomeInfoList(welcomeList);
    }

    private List<WelcomeListBO> convertWelcomeInfoList(List<TabWelcome> welcomeList) {
        return welcomeList.stream().map(one -> {
            WelcomeListBO bo = new WelcomeListBO();
            bo.setCreatorId(one.getCreatorId());
            bo.setCreatorName(one.getCreatorName());
            bo.setModifierId(one.getModifierId());
            bo.setModifierName(one.getModifierName());
            bo.setWelcomeId(one.getWelcomeId());
            bo.setWxEnterpriseId(one.getWxEnterpriseId());
            bo.setTitle(one.getTitle());
            bo.setWelcomeContent(one.getWelcomeContent());
            bo.setOpenFlag(one.getOpenFlag());
            bo.setUpdateTime(one.getUpdateTime());
            bo.setOperatorId(one.getOperatorId());
            bo.setOperatorName(one.getOperatorName());
            bo.setDefaultWelcomeFlag(one.getDefaultWelcomeFlag());
            bo.setType(one.getType());
            // 媒体列表
            bo.setWelcomeMediaList(
                    convertWelcomeMedia(welcomeMediaMapper.listByWelcomeId(one.getWelcomeId()))
            );
            // 适用部门列表
            TabHaobanWelcomeSuitRang deptRangQuery = new TabHaobanWelcomeSuitRang();
            deptRangQuery.setWxEnterpriseId(one.getWxEnterpriseId());
            deptRangQuery.setWelcomeId(one.getWelcomeId());
            deptRangQuery.setSuitType(WelcomeSuitTypeEnum.DEPARTMENT.getCode());
            deptRangQuery.setSelectType(1);
            deptRangQuery.setDeleteFlag(0);
            bo.setSuitDepartmentList(
                    convertSuitDepartment(welcomeSuitRangMapper.queryAll(deptRangQuery))
            );
            // 适用员工列表
            TabHaobanWelcomeSuitRang staffRangQuery = new TabHaobanWelcomeSuitRang();
            staffRangQuery.setWxEnterpriseId(one.getWxEnterpriseId());
            staffRangQuery.setWelcomeId(one.getWelcomeId());
            staffRangQuery.setSuitType(WelcomeSuitTypeEnum.STAFF.getCode());
            staffRangQuery.setSelectType(1);
            staffRangQuery.setDeleteFlag(0);
            bo.setSuitStaffList(
                    convertSuitStaff(welcomeSuitRangMapper.queryAll(staffRangQuery))
            );
            return bo;
        }).collect(Collectors.toList());
    }

    @Override
    public WelcomeDetailBO getWelcome(String welcomeId, String enterpriseId) {
        TabWelcome welcome = welcomeMapper.selectByPrimaryKey(welcomeId);
        if (Objects.isNull(welcome)) {
            throw new RuntimeException("欢迎语数据不存在");
        }
        // 封装数据
        WelcomeDetailBO welcomeDetail = new WelcomeDetailBO();
        welcomeDetail.setWelcomeId(welcome.getWelcomeId());
        welcomeDetail.setWxEnterpriseId(welcome.getWxEnterpriseId());
        welcomeDetail.setTitle(welcome.getTitle());
        welcomeDetail.setWelcomeContent(welcome.getWelcomeContent());
        welcomeDetail.setOpenFlag(welcome.getOpenFlag());
        welcomeDetail.setDefaultWelcomeFlag(welcome.getDefaultWelcomeFlag());
        welcomeDetail.setType(welcome.getType());
        // 媒体列表
        welcomeDetail.setWelcomeMediaList(
                convertWelcomeMedia(welcomeMediaMapper.listByWelcomeId(welcome.getWelcomeId()))
        );
        // 为媒体列表添加小程序
        assemblyMiniProgram(welcome, welcomeDetail, enterpriseId);
        // 适用部门列表
        TabHaobanWelcomeSuitRang deptRangQuery = new TabHaobanWelcomeSuitRang();
        deptRangQuery.setWxEnterpriseId(welcome.getWxEnterpriseId());
        deptRangQuery.setWelcomeId(welcome.getWelcomeId());
        deptRangQuery.setSuitType(WelcomeSuitTypeEnum.DEPARTMENT.getCode());
        deptRangQuery.setDeleteFlag(0);
        welcomeDetail.setSuitDepartmentList(
                convertSuitDepartment(welcomeSuitRangMapper.queryAll(deptRangQuery))
        );
        // 适用员工列表
        TabHaobanWelcomeSuitRang staffRangQuery = new TabHaobanWelcomeSuitRang();
        staffRangQuery.setWxEnterpriseId(welcome.getWxEnterpriseId());
        staffRangQuery.setWelcomeId(welcome.getWelcomeId());
        staffRangQuery.setSuitType(WelcomeSuitTypeEnum.STAFF.getCode());
        staffRangQuery.setDeleteFlag(0);
        welcomeDetail.setSuitStaffList(
                convertSuitStaff(welcomeSuitRangMapper.queryAll(staffRangQuery))
        );
        return welcomeDetail;
    }

    private void assemblyMiniProgram(TabWelcome welcome, WelcomeDetailBO welcomeDetail, String enterpriseId) {
        List<WelcomeMediaBO> welcomeMediaList = welcomeDetail.getWelcomeMediaList();
        if (CollectionUtils.isEmpty(welcomeMediaList)) {
            return;
        }
        welcomeMediaList.forEach(one -> {
            // 小程序
            if (Objects.equals(WelcomeMediaTypeEnum.PROGRAM.getCode(), one.getMediaType())) {
                // 小程序查询,直接根据id查询
                TabMiniprogramSetting miniprogram = miniprogramSettingMapper.selectByPrimaryKey(one.getMiniprogramSettingId());
                if (Objects.nonNull(miniprogram)) {
                    one.setMediaTitle(miniprogram.getTitle());
                    one.setMiniProgramName(miniprogram.getMiniprogramName());
                    if(null == one.getMediaUrl() || StringUtils.isBlank(one.getMediaId())) {
                        one.setMediaUrl(miniprogram.getImageUrl());
                    }
                }
            }
            // 带参小程序
            if (Objects.equals(WelcomeMediaTypeEnum.PARAM_PROGRAM.getCode(), one.getMediaType())) {
                TabMiniprogramSetting matchMiniProgram = null;
                if (StringUtils.isNotEmpty(enterpriseId)) {
                    matchMiniProgram = miniprogramSettingMapper.getMiniprogramSetting(welcome.getWxEnterpriseId(), enterpriseId);
                }
                if (Objects.isNull(matchMiniProgram)) {
                    List<TabMiniprogramSetting> miniProgramSettings = miniprogramSettingMapper.listMiniprogramSetting(welcome.getWxEnterpriseId());
                    if (CollectionUtils.isNotEmpty(miniProgramSettings)) {
                        matchMiniProgram = miniProgramSettings.get(0);
                    }
                }
                if (Objects.isNull(matchMiniProgram)) {
                    logger.info("无小程序配置, {}", welcome.getWxEnterpriseId());
                } else {
                    // 只展示图片
                    one.setMediaUrl(matchMiniProgram.getImageUrl());
                }
            }
        });
    }

    @Override
    public Boolean saveFriendSetting(SaveFriendSettingBO bo) {
        if (Objects.isNull(bo)) {
            throw new RuntimeException("参数为空");
        }
        TabHaobanFriendSetting friendSetting = null;
        if (Objects.nonNull(bo.getFriendSettingId())) {
            friendSetting = friendSettingMapper.queryById(bo.getFriendSettingId());
        }
        if (Objects.isNull(friendSetting)) {
            // 新增
            friendSetting = new TabHaobanFriendSetting();
            friendSetting.setFriendSettingId(UniqueIdUtils.uniqueLong());
            friendSetting.setWxEnterpriseId(bo.getWxEnterpriseId());
            friendSetting.setFriendSettingType(bo.getFriendSettingType());
            friendSetting.setUpdateId(bo.getUpdateId());
            friendSetting.setUpdateName(bo.getUpdateName());
            friendSetting.setCreateTime(new Date());
            friendSetting.setDeleteFlag(0);
            friendSettingMapper.insert(friendSetting);
        } else {
            // 更新
            friendSetting.setFriendSettingType(bo.getFriendSettingType());
            friendSetting.setUpdateId(bo.getUpdateId());
            friendSetting.setUpdateName(bo.getUpdateName());
            friendSetting.setUpdateTime(new Date());
            friendSettingMapper.update(friendSetting);
        }
        return Boolean.TRUE;
    }

    @Override
    public FriendSettingDetailBO getFriendSetting(String wxEnterpriseId) {
        TabHaobanFriendSetting friendSetting = friendSettingMapper.getByWxEnterpriseId(wxEnterpriseId);
        FriendSettingDetailBO friendSettingDetail = new FriendSettingDetailBO();
        if (Objects.isNull(friendSetting)) {
            // 返回默认
            friendSettingDetail.setFriendSettingType(FriendSettingTypeEnum.TEXT_AND_MINI_PROGRAM.getCode());
            friendSettingDetail.setWxEnterpriseId(wxEnterpriseId);
        } else {
            friendSettingDetail.setFriendSettingId(friendSetting.getFriendSettingId());
            friendSettingDetail.setWxEnterpriseId(friendSetting.getWxEnterpriseId());
            friendSettingDetail.setFriendSettingType(friendSetting.getFriendSettingType());
        }
        return friendSettingDetail;
    }

    @Override
    public WelcomeDetailBO getMatchWelcome(String staffId, String wxEnterpriseId) {
        if (StringUtils.isEmpty(staffId) || StringUtils.isEmpty(wxEnterpriseId)) {
            return null;
        }
        return queryMatchWelcome(staffId, wxEnterpriseId, HmWelcomeType.NORMAL.getCode());
    }

    private WelcomeDetailBO queryMatchWelcome(String staffId, String wxEnterpriseId, Integer type) {
        WelcomeInfoQO welcomeInfoQO = new WelcomeInfoQO();
        welcomeInfoQO.setWxEnterpriseId(wxEnterpriseId);
        welcomeInfoQO.setType(type);
        // 查询非默认欢迎语
        welcomeInfoQO.setDefaultWelcomeFlag(0);
        List<TabWelcome> nonDefaultWelcomList = welcomeMapper.queryWelcomeList(welcomeInfoQO);
        // 查询默认欢迎语
        welcomeInfoQO.setDefaultWelcomeFlag(1);
        List<TabWelcome> defaultWelcomeList = welcomeMapper.queryWelcomeList(welcomeInfoQO);
        if (CollectionUtils.isEmpty(nonDefaultWelcomList)) {
            return checkAndGetDefaultWelcome(defaultWelcomeList);
        }
        // 匹配部门组织架构
        List<TabHaobanStaffDepartmentRelated> departmentRelatedList = staffDepartmentRelatedMapper.listByWxEnterpriseIdAndStaffId(wxEnterpriseId, staffId);
        if (CollectionUtils.isEmpty(departmentRelatedList)) {
            logger.info("员工{}, 未设置部门", staffId);
            return checkAndGetDefaultWelcome(defaultWelcomeList);
        }
        List<TabHaobanStaffDepartmentRelated> filterStaffDepartmentList = departmentRelatedList.stream()
                .filter(one -> StringUtils.isNotEmpty(one.getDepartmentId()))
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(filterStaffDepartmentList)) {
            logger.info("员工{}, 部门过滤为空", staffId);
            return checkAndGetDefaultWelcome(defaultWelcomeList);
        }
        // 获取部门列表
        List<String> departmentIdList = filterStaffDepartmentList.stream()
                .map(TabHaobanStaffDepartmentRelated::getDepartmentId).collect(Collectors.toList());
        // 查询欢迎语适用范围
        List<TabHaobanWelcomeSuitRang> welcomeSuitRangList = welcomeSuitRangMapper.listByWxEnterpriseIdAndDeptList(wxEnterpriseId, departmentIdList);
        if (CollectionUtils.isEmpty(welcomeSuitRangList)) {
            logger.info("当前员工所在部门不存在匹配欢迎语");
            return checkAndGetDefaultWelcome(defaultWelcomeList);
        }
        // welcomeList 已经经过时间排序, 顺序去对适用欢迎语匹配, 第一条即是匹配上的欢迎语
        WelcomeDetailBO matchWelcome = null;
        Set<String> welcomeIdSet = welcomeSuitRangList.stream().map(TabHaobanWelcomeSuitRang::getWelcomeId).collect(Collectors.toSet());
        for (TabWelcome welcome : nonDefaultWelcomList) {
            if (welcomeIdSet.contains(welcome.getWelcomeId())) {
                matchWelcome = convertWelcomeToBo(welcome);
                break;
            }
        }
        if (Objects.isNull(matchWelcome)) {
            return checkAndGetDefaultWelcome(defaultWelcomeList);
        }
        logger.info("欢迎语已匹配");
        return matchWelcome;
    }

    /**
     * desc: 校验并且返回默认欢迎语
     * 在匹配欢迎语时, 每到需要返回默认欢迎语的地方, 就要走这段逻辑
     *
     * @param defaultWelcomeList 默认欢迎语列表
     * @return : {@link WelcomeDetailBO}
     * @author : YongEn
     * @date : 2022/3/10
     */
    private WelcomeDetailBO checkAndGetDefaultWelcome(List<TabWelcome> defaultWelcomeList) {
        if (CollectionUtils.isEmpty(defaultWelcomeList)) {
            logger.info("未配置默认欢迎语");
            return null;
        }
        return convertWelcomeToBo(defaultWelcomeList.get(0));
    }

    @Override
    public Boolean saveDefaultWelcome(String wxEnterpriseId) {
        List<TabWelcome> welcomeList = welcomeMapper.listByWxEnterpriseId(wxEnterpriseId, null, 1);
        if (CollectionUtils.isNotEmpty(welcomeList)) {
            throw new RuntimeException("已存在默认欢迎语");
        }
        // 构造默认欢迎语
        TabWelcome welcome = new TabWelcome();
        welcome.setWelcomeId(StringUtil.randomUUID());
        welcome.setWxEnterpriseId(wxEnterpriseId);
        welcome.setTitle("全员欢迎语");
        welcome.setWelcomeContent("你好,<微信昵称>长按识别图中二维码关注公众号并成为会员吧！");
        welcome.setWelcomeImg("");
        // 默认开启
        welcome.setOpenFlag(1);
        welcome.setStatusFlag(1);
        welcome.setCreateTime(new Date());
        welcome.setUpdateTime(new Date());
        welcome.setOperatorId("-1");
        welcome.setOperatorName("system");
        welcome.setDefaultWelcomeFlag(1);
        welcome.setType(HmWelcomeType.NORMAL.getCode());
        // 插入
        welcomeMapper.insert(welcome);
        return Boolean.TRUE;
    }

    @Override
    public Boolean existDefaultWelcome(String wxEnterpriseId) {
        List<TabWelcome> welcomeList = welcomeMapper.listByWxEnterpriseId(wxEnterpriseId, null, 1);
        return CollectionUtils.isNotEmpty(welcomeList);
    }

    @Override
    public Boolean flushWelcomeMedia() {
        // 列举所有加好友配置
        TabHaobanFriendSetting query = new TabHaobanFriendSetting();
        query.setDeleteFlag(0);
        List<TabHaobanFriendSetting> friendSettingList = friendSettingMapper.queryAll(query);
        if (CollectionUtils.isEmpty(friendSettingList)) {
            return Boolean.TRUE;
        }
        Map<String, Integer> wxIdFriendTypeMap = friendSettingList.stream().collect(Collectors.toMap(
                TabHaobanFriendSetting::getWxEnterpriseId,
                TabHaobanFriendSetting::getFriendSettingType
        ));
        // 查询所有欢迎语
        List<TabWelcome> welcomeList = welcomeMapper.listAllWelcome();
        if (CollectionUtils.isEmpty(welcomeList)) {
            return Boolean.TRUE;
        }
        welcomeList.forEach(one -> {
            Integer type = wxIdFriendTypeMap.get(one.getWxEnterpriseId());
            // 构建欢迎语媒体
            TabHaobanWelcomeMedia media = new TabHaobanWelcomeMedia();
            media.setWelcomeMediaId(UniqueIdUtils.uniqueLong());
            media.setWxEnterpriseId(one.getWxEnterpriseId());
            media.setWelcomeId(one.getWelcomeId());
            media.setMediaUrl("-1");
            media.setMediaSize("0");
            media.setMiniProgramId("-1");
            media.setCreateTime(new Date());
            media.setDeleteFlag(0);
            // 媒体类型 - 根据历史配置的加好友配置设置
            if (Objects.isNull(type) || FriendSettingTypeEnum.TEXT_AND_MINI_PROGRAM.getCode().equals(type)) {
                media.setMediaType(WelcomeMediaTypeEnum.PARAM_PROGRAM.getCode());
                media.setMediaTitle("带参小程序");
            } else if (FriendSettingTypeEnum.TEXT_AND_QRCODE.getCode().equals(type)) {
                media.setMediaType(WelcomeMediaTypeEnum.PARAM_QRCODE.getCode());
                media.setMediaTitle("带参公众号");
            }
            welcomeMediaMapper.insert(media);
        });

        return Boolean.TRUE;
    }

    private WelcomeDetailBO convertWelcomeToBo(TabWelcome welcome) {
        WelcomeDetailBO matchWelcome = new WelcomeDetailBO();
        matchWelcome.setWelcomeId(welcome.getWelcomeId());
        matchWelcome.setWxEnterpriseId(welcome.getWxEnterpriseId());
        matchWelcome.setTitle(welcome.getTitle());
        matchWelcome.setWelcomeContent(welcome.getWelcomeContent());
        matchWelcome.setOpenFlag(welcome.getOpenFlag());
        matchWelcome.setDefaultWelcomeFlag(welcome.getDefaultWelcomeFlag());
        // 媒体列表
        matchWelcome.setWelcomeMediaList(
                convertWelcomeMedia(welcomeMediaMapper.listByWelcomeId(welcome.getWelcomeId()))
        );
        return matchWelcome;
    }

    private List<WelcomeMediaBO> convertWelcomeMedia(List<TabHaobanWelcomeMedia> welcomeMediaList) {
        if (CollectionUtils.isEmpty(welcomeMediaList)) {
            return Collections.emptyList();
        }
        return welcomeMediaList.stream().map(one -> {
            WelcomeMediaBO bo = new WelcomeMediaBO();
            bo.setWelcomeMediaId(one.getWelcomeMediaId());
            bo.setWelcomeId(one.getWelcomeId());
            bo.setWxEnterpriseId(one.getWxEnterpriseId());
            bo.setMediaTitle(one.getMediaTitle());
            bo.setMediaType(one.getMediaType());
            bo.setMediaUrl(one.getMediaUrl());
            bo.setMiniProgramPage(one.getMiniProgramPage());
            bo.setMediaSize(one.getMediaSize());
            bo.setMiniprogramSettingId(one.getMiniProgramId());
            bo.setMediaId(one.getMediaId());
            bo.setMediaTime(one.getMediaTime());
            if(one.getMediaType()==5) {
                if (StringUtils.isBlank(one.getMediaId())) {
                    bo.setMediaUrl(null);
                }
            }
            return bo;
        }).collect(Collectors.toList());
    }

    private List<WelcomeSuitDepartmentBO> convertSuitDepartment(List<TabHaobanWelcomeSuitRang> deptSuitRangList) {
        if (CollectionUtils.isEmpty(deptSuitRangList)) {
            return Collections.emptyList();
        }
        return deptSuitRangList.stream().map(one -> {
            WelcomeSuitDepartmentBO bo = new WelcomeSuitDepartmentBO();
            bo.setDepartmentId(one.getSuitDepartmentId());
            bo.setDepartmentName(one.getSuitDepartmentName());
            bo.setSelectType(one.getSelectType());
            return bo;
        }).collect(Collectors.toList());
    }

    private List<WelcomeSuitStaffBO> convertSuitStaff(List<TabHaobanWelcomeSuitRang> staffSuitRangList) {
        if (CollectionUtils.isEmpty(staffSuitRangList)) {
            return Collections.emptyList();
        }
        return staffSuitRangList.stream().map(one -> {
            WelcomeSuitStaffBO bo = new WelcomeSuitStaffBO();
            bo.setStaffId(one.getSuitStaffId());
            bo.setStaffName(one.getSuitStaffName());
            bo.setBelongDepartmentId(one.getStaffBelongDepartmentId());
            bo.setBelongDepartmentName(one.getStaffBelongDepartmentName());
            return bo;
        }).collect(Collectors.toList());
    }

    /**
     * 条件查询
     *
     * @param queryWelcomeQDTO
     * @return
     */
    @Override
    public Page<WelcomeListBO> queryWelcomeList(QueryWelcomeQDTO queryWelcomeQDTO) {
        WelcomeInfoQO welcomeInfoQo = new WelcomeInfoQO();
        welcomeInfoQo.setWxEnterpriseId(queryWelcomeQDTO.getWxEnterpriseId());
        welcomeInfoQo.setTitle(queryWelcomeQDTO.getTitle());
        welcomeInfoQo.setType(queryWelcomeQDTO.getType());
        PageHelper.startPage(queryWelcomeQDTO.getPageNum(), queryWelcomeQDTO.getPageSize());
        com.github.pagehelper.Page<TabWelcome> tabWelcomes =
                (com.github.pagehelper.Page<TabWelcome>) welcomeMapper.queryWelcomeList(welcomeInfoQo);
        List<WelcomeListBO> welcomeListBos = this.convertWelcomeInfoList(tabWelcomes.getResult());
        Page<WelcomeListBO> tPage = new Page<>();
        tPage.setPageSize(tabWelcomes.getPageSize());
        tPage.setCurrentPage(tabWelcomes.getPageNum());
        tPage.setTotalCount((int) tabWelcomes.getTotal());
        tPage.setTotalPage(tabWelcomes.getPages());
        tPage.setResult(welcomeListBos);
        return tPage;
    }

    @Override
    public WelcomeDetailBO getMatchWelcomeWithReferId(String staffId, String wxEnterpriseId, WelcomeReferBO welcomeReferBo) {
        logger.info("[getMatchWelcomeWithReferId] staffId:{}, wxEnterpriseId:{}, welcomeReferBo:{}",
                staffId, wxEnterpriseId, JSON.toJSONString(welcomeReferBo));

        if (welcomeReferBo == null || welcomeReferBo.getType() == null || StringUtils.isBlank(welcomeReferBo.getReferId())) {
            return null;
        }
        String welcomeId = "";
        try {
            if (HmWelcomeReferType.LINK.getCode().equals(welcomeReferBo.getType())) {
                HmLinkBO linkBo = linkService.getByLinkIdFormCache(null, null, Long.parseLong(welcomeReferBo.getReferId()));
                if (linkBo == null || StringUtils.isBlank(linkBo.getWelcomeId())){
                    return null;
                }
                welcomeId = linkBo.getWelcomeId();
            } else if (HmWelcomeReferType.HM.getCode().equals(welcomeReferBo.getType())) {
                HmQrcodeBO qrcodeBo = qrcodeService.queryById(Long.parseLong(welcomeReferBo.getReferId()));
                if (qrcodeBo == null || StringUtils.isBlank(qrcodeBo.getWelcomeId())){
                    return null;
                }
                welcomeId = qrcodeBo.getWelcomeId();
            }
        } catch (Exception ex) {
            logger.error("[getMatchWelcomeWithReferId] err", ex);
        }
        logger.info("[getMatchWelcomeWithReferId] 获取欢迎语Id:{}, params:{}", welcomeId, JSON.toJSONString(welcomeReferBo));
        if (StringUtils.isBlank(welcomeId)){
            return null;
        }
        TabWelcome tabWelcome = welcomeMapper.selectByPrimaryKey(welcomeId);
        return convertWelcomeToBo(tabWelcome);
    }

    /**
     * 删除欢迎语
     *
     * @param welcomeId
     * @return
     * 删除成功时  直接return null
     * 不可删除时 返回具体的关联数量
     */
    @Override
    public WelcomeRemoveCheckDTO removeWithErrorInfo(String welcomeId) {
        // 1、查询欢迎语
        // 2、根据欢迎语类型 区分
        // 3、特殊类型 查询欢迎语引用的数量
        // 4、判断是否可删除
        TabWelcome tabWelcome = welcomeMapper.selectByPrimaryKey(welcomeId);
        if (tabWelcome == null){
            return null;
        }
        if (HmWelcomeType.NORMAL.getCode().equals(tabWelcome.getType())){
            this.removeWelcome(welcomeId);
            return null;
        }

        WelcomeRemoveCheckDTO welcomeRemoveCheckDTO = this.welcomeReferStatistics(welcomeId);
        if (welcomeRemoveCheckDTO == null){
            this.removeWelcome(welcomeId);
            return null;
        }
        return welcomeRemoveCheckDTO;
    }

    /**
     * 欢迎语引用情况统计
     *
     * @param welcomeId
     * @return
     */
    @Override
    public WelcomeRemoveCheckDTO welcomeReferStatistics(String welcomeId) {
        WelcomeRelationQO welcomeRelationQo = new WelcomeRelationQO();
        welcomeRelationQo.setWelcomeId(welcomeId);
        welcomeRelationQo.setStatus(WelcomeRelationStatusEnum.ENABLE.getCode());
        List<HmWelcomeRelationBO> hmWelcomeRelationBos = welcomeRelationService.queryWelcomeRelationList(welcomeRelationQo);
        if (CollectionUtils.isEmpty(hmWelcomeRelationBos)){
            return null;
        }
        Map<Integer, List<HmWelcomeRelationBO>> welcomeGroupByType = hmWelcomeRelationBos.stream()
                .collect(Collectors.groupingBy(HmWelcomeRelationBO::getType));
        WelcomeRemoveCheckDTO welcomeRemoveCheckDTO = new WelcomeRemoveCheckDTO();
        welcomeRemoveCheckDTO.setQrCodeReferNum(Optional.ofNullable(welcomeGroupByType.get(HmWelcomeReferType.HM.getCode()))
                .map(List::size).orElse(0));
        welcomeRemoveCheckDTO.setLinkReferNum(Optional.ofNullable(welcomeGroupByType.get(HmWelcomeReferType.LINK.getCode()))
                .map(List::size).orElse(0));
        return welcomeRemoveCheckDTO;
    }
}
