package com.skr.mdm.api.app.service.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.skr.mdm.api.app.service.MdmAppPushService;
import com.skr.mdm.bean.bo.MdmAppVersionBO;
import com.skr.mdm.bean.bo.QuartzJobBO;
import com.skr.mdm.bean.qo.StrategyDeptQO;
import com.skr.mdm.bean.qo.StrategyUserQO;
import com.skr.mdm.bean.qo.app.*;
import com.skr.mdm.bean.so.app.AppPushSO;
import com.skr.mdm.bean.vo.app.AppPushStatisticsVO;
import com.skr.mdm.constant.JobConstant;
import com.skr.mdm.dao.MdmAppPushDao;
import com.skr.mdm.dao.MdmAppPushUserDao;
import com.skr.mdm.dao.MdmAppStoreVersionDao;
import com.skr.mdm.dao.MdmStrategyDeptDao;
import com.skr.mdm.dto.LoginAdminDTO;
import com.skr.mdm.entity.MdmAppPushDO;
import com.skr.mdm.entity.MdmAppPushUserDO;
import com.skr.mdm.entity.MdmStrategyDeptDO;
import com.skr.mdm.enums.*;
import com.skr.mdm.handle.IssuedUserHandler;
import com.skr.mdm.handle.LogAdminHandler;
import com.skr.mdm.manager.DeviceManager;
import com.skr.mdm.quartz.SchedulerHandler;
import com.skr.mdm.quartz.job.AppPushJob;
import com.skr.mdm.result.ResponseResult;
import com.skr.mdm.util.MdmListUtil;
import com.skr.mdm.util.PageUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author nfq
 * @date 2022-12-02 15:59
 */
@Service
@Slf4j
public class MdmAppPushServiceImpl implements MdmAppPushService {

    private static final String MODULE = "应用推送";

    @Autowired
    private MdmAppPushDao appPushDao;
    @Autowired
    private MdmAppPushUserDao appPushUserDao;
    @Autowired
    private DeviceManager deviceManager;
    @Autowired
    private MdmAppStoreVersionDao appStoreVersionDao;
    @Autowired
    private LogAdminHandler logAdminHandler;
    @Autowired
    private IssuedUserHandler issuedUserHandler;
    @Autowired
    private SchedulerHandler schedulerHandler;
    @Autowired
    private MdmStrategyDeptDao strategyDeptDao;

    @Override
    public ResponseResult listAppPush(AppPushListQO appPushListQO, LoginAdminDTO loginAdminDTO) {
        PageHelper.startPage(appPushListQO.getPageNum(), appPushListQO.getPageSize());
        appPushListQO.setCompanyId(loginAdminDTO.getCompanyId());
        return ResponseResult.success(PageUtil.getPageResult(appPushDao.listAppPushVO(appPushListQO)));
    }

    @Override
    public ResponseResult listAppPushUser(StrategyUserQO strategyUserQO) {
        if (strategyUserQO.getPageNum().equals(0)) {
            return ResponseResult.success(appPushUserDao.listAppPushUserVO(strategyUserQO.getStrategyId(),
                    strategyUserQO.getSearchType(), strategyUserQO.getSearchValue()));
        }
        PageHelper.startPage(strategyUserQO.getPageNum(), strategyUserQO.getPageSize());
        return ResponseResult.success(PageUtil.getPageResult(appPushUserDao.listAppPushUserVO(
                strategyUserQO.getStrategyId(), strategyUserQO.getSearchType(), strategyUserQO.getSearchValue())));
    }

    @Override
    public ResponseResult listAppDept(StrategyUserQO strategyUserQO) {
        StrategyDeptQO strategyDeptQO = StrategyDeptQO.builder()
                .strategyType(StrategyDeptTypeEnum.APP_PUSH.getStrategyType())
                .build();
        BeanUtils.copyProperties(strategyUserQO, strategyDeptQO);
        PageHelper.startPage(strategyUserQO.getPageNum(), strategyUserQO.getPageSize());
        return ResponseResult.success(PageUtil.getPageResult(strategyDeptDao.listDept(strategyDeptQO)));
    }

    @Override
    public ResponseResult statisticsAppPush(Integer appPushId) {
        List<Integer> appPushUserStateList = appPushUserDao.listUserState(appPushId);
        if (CollectionUtils.isNotEmpty(appPushUserStateList)) {
            Integer waitPushCount = 0;
            Integer waitDownloadCount = 0;
            Integer downloadingCount = 0;
            Integer downloadFailedCount = 0;
            Integer downloadSuccessCount = 0;
            Integer installSuccessCount = 0;
            Integer installFailedCount = 0;
            for (Integer state : appPushUserStateList) {
                if (state.equals(0)) {
                    waitPushCount++;
                }
                if (state.equals(1)) {
                    waitDownloadCount++;
                }
                if (state.equals(2)) {
                    downloadingCount++;
                }
                if (state.equals(3)) {
                    downloadFailedCount++;
                }
                if (state.equals(4)) {
                    downloadSuccessCount++;
                }
                if (state.equals(5)) {
                    installSuccessCount++;
                }
                if (state.equals(6)) {
                    installFailedCount++;
                }
            }
            AppPushStatisticsVO appPushStatisticsVO = AppPushStatisticsVO.builder()
                    .userCount(appPushUserStateList.size())
                    .waitPushCount(waitPushCount)
                    .waitDownloadCount(waitDownloadCount)
                    .downloadingCount(downloadingCount)
                    .downloadFailedCount(downloadFailedCount)
                    .downloadSuccessCount(downloadSuccessCount)
                    .installSuccessCount(installSuccessCount)
                    .installFailedCount(installFailedCount)
                    .build();
            return ResponseResult.success(appPushStatisticsVO);
        }
        return ResponseResult.success();
    }

    @Override
    public ResponseResult addAppPush(MdmAppPushAddQO appPushAddQO, LoginAdminDTO loginAdminDTO) {
        // 查重
        long count = new LambdaQueryChainWrapper<>(appPushDao)
                .eq(MdmAppPushDO::getGlobalType, appPushAddQO.getGlobalType())
                .in(MdmAppPushDO::getAppVersionId, appPushAddQO.getAppVersionIdList())
                .count();
        if (count > 0) {
            return ResponseResult.failure("应用版本已存在");
        }
        // 保存
        saveAppPush(appPushAddQO, loginAdminDTO);
        // log
        List<String> appNameList = appStoreVersionDao.listMdmAppVersionBO(appPushAddQO.getAppVersionIdList())
                .stream()
                .map(appVersionBO -> appVersionBO.getAppName() + "(" + appVersionBO.getVersionName() + ")")
                .collect(Collectors.toList());
        String content = getGlobalType(appPushAddQO.getGlobalType()) + "添加应用推送：" + StringUtils.join(appNameList, "、");
        logAdminHandler.log(loginAdminDTO, LogAdminTypeEnum.APP_TYPE.getLogType(), content, MODULE, null);
        return ResponseResult.success();
    }

    private void saveAppPush(MdmAppPushAddQO appPushAddQO, LoginAdminDTO loginAdminDTO) {
        List<MdmAppPushDO> appPushDOList = appPushAddQO.getAppVersionIdList()
                .stream()
                .map(appPushId -> MdmAppPushDO.builder()
                        .appVersionId(appPushId)
                        .globalType(appPushAddQO.getGlobalType())
                        .isPause(0)
                        .operator(loginAdminDTO.getAdminName())
                        .companyId(loginAdminDTO.getCompanyId())
                        .build())
                .collect(Collectors.toList());
        appPushDao.insertBatch(appPushDOList);
    }

    @Override
    public ResponseResult deleteAppPush(List<Integer> appPushIdList, LoginAdminDTO loginAdminDTO) {
        // 下发
        appPushIdList.forEach(appPushId -> {
            MdmAppPushDO mdmAppPushDO = appPushDao.selectById(appPushId);
            List<Integer> equipmentIdList = appPushUserDao.listEquipmentIdByStrategyIds(ListUtil.toList(appPushId));
            if (CollectionUtils.isNotEmpty(equipmentIdList)) {
                issuedUserHandler.issuedUser(equipmentIdList, loginAdminDTO.getCompanyId(), AppPushCmdEnum.REMOVE_APP_PUSH.getCmd(), JSONUtil.toJsonStr(ListUtil.toList(appPushId)));
            }
            // log
            MdmAppVersionBO mdmAppVersionBO = appPushDao.getMdmAppVersionBO(appPushId);
            String content = getGlobalType(mdmAppPushDO.getGlobalType()) + "删除应用推送：" + mdmAppVersionBO.getAppName()
                    + "(" + mdmAppVersionBO.getVersionName() + ")";
            logAdminHandler.log(loginAdminDTO, LogAdminTypeEnum.APP_TYPE.getLogType(), content, MODULE, equipmentIdList);
        });

        appPushDao.deleteBatchIds(appPushIdList);
        appPushUserDao.delete(Wrappers.lambdaQuery(MdmAppPushUserDO.class).in(MdmAppPushUserDO::getAppPushId, appPushIdList));
        return ResponseResult.success();
    }

    @Override
    public ResponseResult pauseAppPush(Integer appPushId, Integer isPause, LoginAdminDTO loginAdminDTO) {
        new LambdaUpdateChainWrapper<>(appPushDao)
                .set(MdmAppPushDO::getIsPause, isPause)
                .eq(MdmAppPushDO::getId, appPushId)
                .update();
        new LambdaUpdateChainWrapper<>(appPushUserDao)
                .set(MdmAppPushUserDO::getPauseStatus, isPause)
                .eq(MdmAppPushUserDO::getAppPushId, appPushId)
                .update();
        // 下发
        String pauseStr = "恢复应用推送:";
        String cmdType = AppPushCmdEnum.RECOVER_APP_PUSH.getCmd();
        if (isPause == 1) {
            cmdType = AppPushCmdEnum.PAUSE_APP_PUSH.getCmd();
            pauseStr = "暂停应用推送:";
        }
        List<Integer> equipmentIdList = appPushUserDao.listEquipmentIdByStrategyIds(ListUtil.toList(appPushId));
        issuedUserHandler.issuedUser(equipmentIdList, loginAdminDTO.getCompanyId(), cmdType, JSONUtil.toJsonStr(ListUtil.toList(appPushId)));
        // log
        MdmAppPushDO mdmAppPushDO = appPushDao.selectById(appPushId);
        MdmAppVersionBO mdmAppVersionBO = appPushDao.getMdmAppVersionBO(appPushId);
        String content = getGlobalType(mdmAppPushDO.getGlobalType()) + pauseStr + mdmAppVersionBO.getAppName()
                + "(" + mdmAppVersionBO.getVersionName() + ")";
        logAdminHandler.log(loginAdminDTO, LogAdminTypeEnum.APP_TYPE.getLogType(), content, MODULE, equipmentIdList);
        return ResponseResult.success();
    }

    @Override
    public ResponseResult pushApp(MdmAppPushQO mdmAppPushQO, LoginAdminDTO loginAdminDTO) {
        // 更新全局部门
        updateGlobalDept(mdmAppPushQO);
        // 更新推送时间
        new LambdaUpdateChainWrapper<>(appPushDao)
                .set(MdmAppPushDO::getPushTime, mdmAppPushQO.getPushTime())
                .set(MdmAppPushDO::getOperator, loginAdminDTO.getAdminName())
                .in(MdmAppPushDO::getId, mdmAppPushQO.getAppPushIdList())
                .update();
        // 保存
        List<String> appNameList = Lists.newArrayListWithCapacity(mdmAppPushQO.getAppPushIdList().size());
        List<Integer> equipmentIdList = deviceManager.getDeviceIdList(mdmAppPushQO.getGlobalType(),
                mdmAppPushQO.getCandidateIdList(), loginAdminDTO.getCompanyId());
        List<AppPushSO> appPushSOList = Lists.newArrayListWithCapacity(mdmAppPushQO.getAppPushIdList().size());
        mdmAppPushQO.getAppPushIdList().forEach(appPushId -> {
            MdmAppVersionBO mdmAppVersionBO = appPushDao.getMdmAppVersionBO(appPushId);
            if (CollectionUtils.isNotEmpty(equipmentIdList)) {
                List<Integer> listEquipmentIdByStrategyIds = appPushUserDao.listEquipmentIdByStrategyIds(ListUtil.toList(appPushId));
                List<Integer> addEquipmentIdList = MdmListUtil.difference(equipmentIdList, listEquipmentIdByStrategyIds);
                List<Integer> updateEquipmentIdList = MdmListUtil.intersection(equipmentIdList, listEquipmentIdByStrategyIds);
                // 下发数据
                AppPushSO appPushSO = addAppPushSO(mdmAppPushQO, appPushSOList, appPushId);
                // 定时推送
                Integer state = scheduledPush(mdmAppPushQO, loginAdminDTO, appPushSO, appPushId);
                // 新增
                saveAppPushUser(mdmAppPushQO, addEquipmentIdList, appPushId, state, mdmAppVersionBO.getIsPause());
                // 更新
                updateAppPushUser(mdmAppPushQO, appPushId, updateEquipmentIdList, state);
            }
            // log
            appNameList.add(mdmAppVersionBO.getAppName() + "(" + mdmAppVersionBO.getVersionName() + ")");
        });
        // log
        String content = getGlobalType(mdmAppPushQO.getGlobalType()) + "应用推送：" + StringUtils.join(appNameList, "、");
        logAdminHandler.log(mdmAppPushQO.getGlobalType(), mdmAppPushQO.getCandidateIdList(),
                loginAdminDTO, LogAdminTypeEnum.APP_TYPE.getLogType(), content, MODULE);
        // 下发
        if (!mdmAppPushQO.getPushType().equals(AppPushTypeEnum.TIMING_PUSH.getPushType()) && CollectionUtils.isNotEmpty(appPushSOList)) {
            issuedUserHandler.issuedUser(equipmentIdList, loginAdminDTO.getCompanyId(), AppPushCmdEnum.ISSUED_APP_PUSH.getCmd(), JSONUtil.toJsonStr(appPushSOList));
        }
        return ResponseResult.success();
    }

    private AppPushSO addAppPushSO(MdmAppPushQO mdmAppPushQO, List<AppPushSO> appPushSOList, Integer appPushId) {
        AppPushSO appPushSO = new AppPushSO();
        appPushSO.setId(appPushId);
        appPushSO.setSendTime(mdmAppPushQO.getPushTime());
        BeanUtils.copyProperties(appPushDao.getMdmAppVersionBO(appPushId), appPushSO);
        BeanUtils.copyProperties(mdmAppPushQO, appPushSO);
        appPushSOList.add(appPushSO);
        return appPushSO;
    }

    private Integer scheduledPush(MdmAppPushQO mdmAppPushQO, LoginAdminDTO loginAdminDTO, AppPushSO appPushSO, Integer appPushId) {
        if (AppPushTypeEnum.TIMING_PUSH.getPushType().equals(mdmAppPushQO.getPushType()) &&
                mdmAppPushQO.getPushTime() != null && mdmAppPushQO.getPushTime().after(new Date())) {
            QuartzJobBO quartzJobBO = QuartzJobBO.builder()
                    .cmd(AppPushCmdEnum.ISSUED_APP_PUSH.getCmd())
                    .message(JSONUtil.toJsonStr(ListUtil.toList(appPushSO)))
                    .id(appPushId)
                    .companyId(loginAdminDTO.getCompanyId())
                    .executeTime(mdmAppPushQO.getPushTime())
                    .prefix(JobConstant.JOB_APP_PUSH_KEY_PREFIX)
                    .build();
            schedulerHandler.handleJob(quartzJobBO, AppPushJob.class);
            return StrategyEquipmentStateEnum.WAIT_ISSUED.getState();
        }
        return StrategyEquipmentStateEnum.ISSUING.getState();
    }

    private void updateGlobalDept(MdmAppPushQO mdmAppPushQO) {
        if (IssuedTypeEnum.DEPT_GLOBAL.getIssuedType().equals(mdmAppPushQO.getGlobalType())) {
            // 保存全局部门
            List<Integer> deptIdList = Lists.newCopyOnWriteArrayList(mdmAppPushQO.getCandidateIdList());
            mdmAppPushQO.getAppPushIdList().forEach(appPushId -> saveAppDept(deptIdList, appPushId));
        }
    }

    @Override
    public ResponseResult repushApp(MdmAppRePushQO appRePushQO, LoginAdminDTO loginAdminDTO) {
        // 下发
        MdmAppPushDO appPushDO = appPushDao.selectById(appRePushQO.getAppPushId());
        Integer globalType = appPushDO.getGlobalType();
        appRePushQO.getEquipmentIdList().forEach(equipmentId -> {
            doRePushApp(appRePushQO, loginAdminDTO, globalType, equipmentId);
        });
        // 更新状态
        new LambdaUpdateChainWrapper<>(appPushUserDao)
                .set(MdmAppPushUserDO::getState, StrategyEquipmentStateEnum.ISSUING.getState())
                .set(MdmAppPushUserDO::getPushTime, new Date())
                .eq(MdmAppPushUserDO::getAppPushId, appRePushQO.getAppPushId())
                .in(MdmAppPushUserDO::getEquipmentId, appRePushQO.getEquipmentIdList())
                .gt(MdmAppPushUserDO::getState, StrategyEquipmentStateEnum.WAIT_ISSUED.getState())
                .update();
        // log
        MdmAppVersionBO appVersionBO = appPushDao.getMdmAppVersionBO(appRePushQO.getAppPushId());
        String content = getGlobalType(globalType) + "应用作用人重新推送：" + appVersionBO.getAppName()
                + "(" + appVersionBO.getVersionName() + ")";
        logAdminHandler.log(loginAdminDTO, LogAdminTypeEnum.APP_TYPE.getLogType(), content, MODULE, appRePushQO.getEquipmentIdList());
        return ResponseResult.success();
    }

    @Override
    public ResponseResult forcePushApp(MdmAppRePushQO appRePushQO, LoginAdminDTO loginAdminDTO) {
        // 下发
        MdmAppPushDO appPushDO = appPushDao.selectById(appRePushQO.getAppPushId());
        Integer globalType = appPushDO.getGlobalType();
        AppPushSO appPushSO = new AppPushSO();
        appPushSO.setId(appRePushQO.getAppPushId());
        appPushSO.setSendTime(new Date());
        appPushSO.setGlobalType(globalType);
        appPushSO.setPushType(AppPushTypeEnum.FORCE_PUSH.getPushType());
        appPushSO.setIsOnlyWifi(0);
        appPushSO.setIsShortcutIcon(0);
        appPushSO.setIsSafeSpace(0);
        BeanUtils.copyProperties(appPushDao.getMdmAppVersionBO(appRePushQO.getAppPushId()), appPushSO);
        issuedUserHandler.issuedUser(appRePushQO.getEquipmentIdList(), loginAdminDTO.getCompanyId(), AppPushCmdEnum.ISSUED_APP_PUSH.getCmd(), JSONUtil.toJsonStr(ListUtil.toList(appPushSO)));
        // 更新状态
        new LambdaUpdateChainWrapper<>(appPushUserDao)
                .set(MdmAppPushUserDO::getState, StrategyEquipmentStateEnum.ISSUING.getState())
                .set(MdmAppPushUserDO::getPushType, AppPushTypeEnum.FORCE_PUSH.getPushType())
                .set(MdmAppPushUserDO::getIsOnlyWifi, 0)
                .set(MdmAppPushUserDO::getIsSafeSpace, 0)
                .set(MdmAppPushUserDO::getIsShortcutIcon, 0)
                .set(MdmAppPushUserDO::getPushTime, new Date())
                .eq(MdmAppPushUserDO::getAppPushId, appRePushQO.getAppPushId())
                .in(MdmAppPushUserDO::getEquipmentId, appRePushQO.getEquipmentIdList())
                .gt(MdmAppPushUserDO::getState, StrategyEquipmentStateEnum.WAIT_ISSUED.getState())
                .update();
        // log
        MdmAppVersionBO appVersionBO = appPushDao.getMdmAppVersionBO(appRePushQO.getAppPushId());
        String content = getGlobalType(globalType) + "作用人强制推送：" + appVersionBO.getAppName()
                + "(" + appVersionBO.getVersionName() + ")";
        logAdminHandler.log(loginAdminDTO, LogAdminTypeEnum.APP_TYPE.getLogType(), content, MODULE, appRePushQO.getEquipmentIdList());
        return ResponseResult.success();
    }

    private void doRePushApp(MdmAppRePushQO appRePushQO, LoginAdminDTO loginAdminDTO, Integer globalType, Integer equipmentId) {
        MdmAppPushUserDO appPushUserDO = new LambdaQueryChainWrapper<>(appPushUserDao)
                .eq(MdmAppPushUserDO::getAppPushId, appRePushQO.getAppPushId())
                .eq(MdmAppPushUserDO::getEquipmentId, equipmentId)
                .gt(MdmAppPushUserDO::getState, StrategyEquipmentStateEnum.WAIT_ISSUED.getState())
                .one();
        if (appPushUserDO != null) {
            AppPushSO appPushSO = new AppPushSO();
            BeanUtils.copyProperties(appPushUserDO, appPushSO);
            BeanUtils.copyProperties(appPushDao.getMdmAppVersionBO(appRePushQO.getAppPushId()), appPushSO);
            appPushSO.setId(appRePushQO.getAppPushId());
            appPushSO.setSendTime(new Date());
            appPushSO.setGlobalType(globalType);
            issuedUserHandler.issuedUser(ListUtil.toList(equipmentId), loginAdminDTO.getCompanyId(), AppPushCmdEnum.ISSUED_APP_PUSH.getCmd(), JSONUtil.toJsonStr(ListUtil.toList(appPushSO)));
        }
    }

    private void updateAppPushUser(MdmAppPushQO mdmAppPushQO, Integer appPushId, List<Integer> deviceIdList, Integer state) {
        if (CollectionUtils.isNotEmpty(deviceIdList)) {
            new LambdaUpdateChainWrapper<>(appPushUserDao)
                    .set(MdmAppPushUserDO::getState, state)
                    .set(MdmAppPushUserDO::getPushType, mdmAppPushQO.getPushType())
                    .set(MdmAppPushUserDO::getPushTime, mdmAppPushQO.getPushTime())
                    .set(MdmAppPushUserDO::getIsOnlyWifi, mdmAppPushQO.getIsOnlyWifi())
                    .set(MdmAppPushUserDO::getIsSafeSpace, mdmAppPushQO.getIsSafeSpace())
                    .set(MdmAppPushUserDO::getIsShortcutIcon, mdmAppPushQO.getIsShortcutIcon())
                    .eq(MdmAppPushUserDO::getAppPushId, appPushId)
                    .in(MdmAppPushUserDO::getEquipmentId, deviceIdList)
                    .update();
        }
    }

    private void saveAppPushUser(MdmAppPushQO mdmAppPushQO, List<Integer> equipmentIdList, Integer appPushId, Integer state, Integer pauseStatus) {
        if (CollectionUtils.isNotEmpty(equipmentIdList)) {
            List<MdmAppPushUserDO> appPushUserDOList = equipmentIdList.stream()
                    .map(deviceId -> MdmAppPushUserDO.builder()
                            .equipmentId(deviceId)
                            .state(state)
                            .appPushId(appPushId)
                            .pushType(mdmAppPushQO.getPushType())
                            .pushTime(mdmAppPushQO.getPushTime())
                            .isOnlyWifi(mdmAppPushQO.getIsOnlyWifi())
                            .isSafeSpace(mdmAppPushQO.getIsSafeSpace())
                            .isShortcutIcon(mdmAppPushQO.getIsShortcutIcon())
                            .pauseStatus(pauseStatus)
                            .build())
                    .collect(Collectors.toList());
            appPushUserDao.insertBatch(appPushUserDOList);
        }
    }

    @Override
    public ResponseResult deleteAppUserUser(Integer appPushId, List<Integer> equipmentIdList, LoginAdminDTO loginAdminDTO) {
        // 下发
        MdmAppPushDO mdmAppPushDO = appPushDao.selectById(appPushId);
        if (CollectionUtils.isNotEmpty(equipmentIdList)) {
            issuedUserHandler.issuedUser(equipmentIdList, loginAdminDTO.getCompanyId(), AppPushCmdEnum.REMOVE_APP_PUSH.getCmd(), JSONUtil.toJsonStr(ListUtil.toList(appPushId)));
        }
        // log
        MdmAppVersionBO mdmAppVersionBO = appPushDao.getMdmAppVersionBO(appPushId);
        String content = getGlobalType(mdmAppPushDO.getGlobalType()) + "删除应用推送：" + mdmAppVersionBO.getAppName()
                + "(" + mdmAppVersionBO.getVersionName() + ")";
        logAdminHandler.log(loginAdminDTO, LogAdminTypeEnum.APP_TYPE.getLogType(), content, MODULE, equipmentIdList);
        // 删除
        appPushUserDao.delete(Wrappers.lambdaQuery(MdmAppPushUserDO.class)
                .eq(MdmAppPushUserDO::getAppPushId, appPushId)
                .in(MdmAppPushUserDO::getEquipmentId, equipmentIdList));
        return ResponseResult.success();
    }

    @Override
    public ResponseResult configGlobal(MdmAppPushGlobalQO appPushGlobalQO, LoginAdminDTO loginAdminDTO) {
        new LambdaUpdateChainWrapper<>(appPushDao)
                .set(MdmAppPushDO::getPushType, appPushGlobalQO.getPushType())
                .set(MdmAppPushDO::getIsOnlyWifi, appPushGlobalQO.getIsOnlyWifi())
                .set(MdmAppPushDO::getIsSafeSpace, appPushGlobalQO.getIsSafeSpace())
                .set(MdmAppPushDO::getIsShortcutIcon, appPushGlobalQO.getIsShortcutIcon())
                .eq(MdmAppPushDO::getId, appPushGlobalQO.getAppPushId())
                .update();
        // log
        MdmAppPushDO mdmAppPushDO = appPushDao.selectById(appPushGlobalQO.getAppPushId());
        String pushType = AppPushTypeEnum.getDescription(appPushGlobalQO.getPushType());
        String onlyWifi = "仅WiFi自动下载：";
        if (appPushGlobalQO.getIsOnlyWifi().equals(1)) {
            onlyWifi = onlyWifi.concat("是");
        } else {
            onlyWifi = onlyWifi.concat("否");
        }
        MdmAppVersionBO mdmAppVersionBO = appPushDao.getMdmAppVersionBO(appPushGlobalQO.getAppPushId());
        String content = new StringBuilder()
                .append(getGlobalType(mdmAppPushDO.getGlobalType()))
                .append("应用推送全局配置修改：")
                .append(mdmAppVersionBO.getAppName())
                .append("(".concat(mdmAppVersionBO.getVersionName()).concat(")".concat("\n")))
                .append("推送类型：")
                .append(pushType.concat("\n"))
                .append(onlyWifi)
                .toString();
        logAdminHandler.log(loginAdminDTO, LogAdminTypeEnum.APP_TYPE.getLogType(), content, MODULE, null);
        return ResponseResult.success();
    }

    private String getGlobalType(Integer globalType) {
        if (globalType.equals(IssuedTypeEnum.GLOBAL.getIssuedType())) {
            return "全局";
        }
        if (globalType.equals(IssuedTypeEnum.DEPT_GLOBAL.getIssuedType())) {
            return "部门全局";
        }
        if (globalType.equals(IssuedTypeEnum.DEVICE.getIssuedType())) {
            return "指定用户";
        }
        return "";
    }

    private void saveAppDept(List<Integer> departmentIdList, Integer appPushId) {
        if (CollectionUtils.isNotEmpty(departmentIdList)) {
            // 去重
            List<Integer> alreadyDepartmentIdList = new LambdaQueryChainWrapper<>(strategyDeptDao)
                    .eq(MdmStrategyDeptDO::getStrategyId, appPushId)
                    .eq(MdmStrategyDeptDO::getStrategyType, StrategyDeptTypeEnum.APP_PUSH.getStrategyType())
                    .list()
                    .stream().map(MdmStrategyDeptDO::getDepartmentId)
                    .collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(alreadyDepartmentIdList)) {
                departmentIdList.removeAll(alreadyDepartmentIdList);
            }
            if (CollectionUtils.isNotEmpty(departmentIdList)) {
                List<MdmStrategyDeptDO> strategyDeptDOList = departmentIdList
                        .stream()
                        .map(departmentId -> MdmStrategyDeptDO
                                .builder()
                                .strategyId(appPushId)
                                .strategyType(StrategyDeptTypeEnum.APP_PUSH.getStrategyType())
                                .departmentId(departmentId)
                                .build())
                        .collect(Collectors.toList());
                strategyDeptDao.insertBatch(strategyDeptDOList);
            }
        }
    }
}