package cn.iocoder.yudao.module.system.service.notice;

import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.system.api.subscribe.SubscribeMessageSendApi;
import cn.iocoder.yudao.module.system.controller.admin.notice.vo.NoticePageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.notice.vo.NoticePushReqVO;
import cn.iocoder.yudao.module.system.controller.admin.notice.vo.NoticeSaveReqVO;
import cn.iocoder.yudao.module.system.convert.notice.NoticeConvert;
import cn.iocoder.yudao.module.system.dal.dataobject.dict.DictDataDO;
import cn.iocoder.yudao.module.system.dal.dataobject.notice.NoticeDO;
import cn.iocoder.yudao.module.system.dal.dataobject.notice.NoticeGroupDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.dal.mysql.notice.NoticeMapper;
import cn.iocoder.yudao.module.system.service.dict.DictDataService;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import com.google.common.annotations.VisibleForTesting;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.NOTICE_NOT_FOUND;
import static cn.iocoder.yudao.module.system.framework.ThreadPool.config.AsyncConfig.NOTIFY_THREAD_POOL_TASK_EXECUTOR;

/**
 * 通知公告 Service 实现类
 *

 */
@Service
public class NoticeServiceImpl implements NoticeService {

    @Resource
    private NoticeMapper noticeMapper;

    @Resource
    private NoticeGroupService noticeGroupService;

    @Resource(name = NOTIFY_THREAD_POOL_TASK_EXECUTOR)
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Resource
    private DictDataService dictDataService;

    @Override
    public Long createNotice(NoticeSaveReqVO createReqVO) {
        NoticeDO notice = BeanUtils.toBean(createReqVO, NoticeDO.class);
        noticeMapper.insert(notice);
        return notice.getId();
    }

    @Override
    public void updateNotice(NoticeSaveReqVO updateReqVO) {
        // 校验是否存在
        validateNoticeExists(updateReqVO.getId());
        // 更新通知公告
        NoticeDO updateObj = BeanUtils.toBean(updateReqVO, NoticeDO.class);
        noticeMapper.updateById(updateObj);
    }

    @Override
    public void deleteNotice(Long id) {
        // 校验是否存在
        validateNoticeExists(id);
        // 删除通知公告
        noticeMapper.deleteById(id);
    }

    @Override
    public PageResult<NoticeDO> getNoticePage(NoticePageReqVO reqVO) {
        return noticeMapper.selectPage(reqVO);
    }

    @Override
    public NoticeDO getNotice(Long id) {
        return noticeMapper.selectById(id);
    }

    @VisibleForTesting
    public void validateNoticeExists(Long id) {
        if (id == null) {
            return;
        }
        NoticeDO notice = noticeMapper.selectById(id);
        if (notice == null) {
            throw exception(NOTICE_NOT_FOUND);
        }
    }

    /** 添加小程序发送公告通知 add by yj 2024-04-07*/
    @Resource
    private AdminUserService userService;
    @Resource
    private SubscribeMessageSendApi subscribeMessageSendApi;

    @Override
    public void sendNotice(NoticePushReqVO pushReqVO) {

        //获得公告信息
        NoticeDO notice = getNotice(pushReqVO.getId());
        if (notice == null) {
            throw exception(NOTICE_NOT_FOUND);
        }

        // 获得公告类型 字典label
        DictDataDO dictDataDO = dictDataService.getDictData("system_notice_type", String.valueOf(notice.getType()));

        //获取当前登陆用户的名称
        LoginUser user = SecurityFrameworkUtils.getLoginUser() ;
        AdminUserDO currentUser = userService.getUser(user.getId()) ;

        List<AdminUserDO> userDOs = new ArrayList<>();
        switch (pushReqVO.getType()) {

            //全员推送
            case 0:
                //获得用户信息
                userDOs = userService.getUserListByStatus(CommonStatusEnum.ENABLE.getStatus());
                break;
            //部门推送
            case 1:
                //获得用户信息
                userDOs = userService.getUserListByDeptIds(pushReqVO.getDeptIds());
                break;
            //用户组推送
            case 2:
                //获得用户组信息
                List<NoticeGroupDO> groupDOs = noticeGroupService.getUserGroupList(pushReqVO.getGroupId());

                //获得用户组中 用户信息
                userDOs = userService.getUserList(groupDOs.stream().flatMap(group -> group.getMemberUserIds().stream()).collect(Collectors.toSet()));
                break;
        }

        for(AdminUserDO adminUserDO : userDOs) {
            if( adminUserDO.getOpenId() != null && !adminUserDO.getOpenId().isEmpty()) {

                threadPoolTaskExecutor.execute(() -> {

                    //获取openId有值的用户
                    subscribeMessageSendApi.sendCompanyNotice(NoticeConvert.INSTANCE.convertCompanyNotice(
                            adminUserDO.getOpenId(), notice, dictDataDO.getLabel(),  currentUser.getNickname(),
                            "formal"));
                });
            }
        }
    }
}