package com.ruoyi.busi.service.impl;

import java.math.BigDecimal;
import java.util.*;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.base.domain.BaseCategory;
import com.ruoyi.base.domain.BaseCity;
import com.ruoyi.base.service.IBaseCategoryService;
import com.ruoyi.base.service.IBaseCityService;
import com.ruoyi.busi.domain.*;
import com.ruoyi.busi.mapper.BusiNoticeSignMapper;
import com.ruoyi.busi.query.AppNoticeQuery;
import com.ruoyi.busi.service.IBusiNoticeFormService;
import com.ruoyi.busi.service.IBusiSubscribeService;
import com.ruoyi.busi.service.IBusiUserLoveService;
import com.ruoyi.busi.vo.BusiNoticeVo;
import com.ruoyi.busi.vo.SubScribeQuery;
import com.ruoyi.busi.vo.SubscribeDataObj;
import com.ruoyi.common.config.WxAppConfig;

import java.util.stream.Collectors;

import cn.hutool.core.date.DateUtil;
import com.ruoyi.busi.utils.NoticeUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.busi.query.BusiNoticeQuery;
import com.ruoyi.constant.DictConstants;
import com.ruoyi.member.domain.MemberPoints;
import com.ruoyi.member.domain.MemberUser;
import com.ruoyi.member.service.*;
import com.ruoyi.member.vo.MemberUserVO;
import com.ruoyi.payConfig.WechatPayConfig;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.busi.mapper.BusiNoticeMapper;
import com.ruoyi.busi.service.IBusiNoticeService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 通告Service业务层处理
 *
 * @author 朱春云
 * @date 2025-03-17
 */
@Service
public class BusiNoticeServiceImpl extends ServiceImpl<BusiNoticeMapper,BusiNotice>  implements IBusiNoticeService
{
    @Autowired
    private IBaseCategoryService baseCategoryService;
    @Autowired
    private BusiNoticeMapper busiNoticeMapper;
    @Autowired
    private BusiNoticeSignMapper busiNoticeSignMapper;
    @Autowired
    private NoticeUtils noticeUtils;
    @Autowired
    private IBusiUserLoveService userLoveService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private IMemberUserService memberUserService;
    @Autowired
    private ISysDictDataService dictDataService;
    @Autowired
    private IBusiSubscribeService subscribeService;
    @Autowired
    private IBusiNoticeFormService busiNoticeFormService;
    @Autowired
    private IBaseCityService cityService;
    @Resource
    private IMemberCardService cardService;

    @Autowired
    private IMemberCouponService memberCouponService;
    @Autowired
    private IMemberPointsService memberPointsService;

    @Resource
    private WechatPayConfig wechatPayConfig;
    @Autowired
    private WxAppConfig wxAppConfig;

    @Autowired
    private ThreadPoolTaskExecutor executor;

    @Override
    public IPage<BusiNoticeVo> queryListPage(BusiNoticeQuery query, Page<BusiNotice> page) {
        return busiNoticeMapper.queryListPage(query, page);
    }

    /**
     * 新增通告
     * @param data 通告对象
     */
    @Override
    public JSONObject saveVo(BusiNotice data) throws Exception {
        JSONObject result = new JSONObject();
        result.put("code",0);
        result.put("msg","自动审核通过，发布成功");
        //获取当前登录用户
        data.setUserId(SecurityUtils.getUserId());
        if (StringUtils.isNotEmpty(data.getApprovalStatus())&&data.getApprovalStatus().equals("8")){
            //草稿数据直接保存
            data.setCreateTime(new Date());
            this.save(data);
            result.put("code",100);
            result.put("msg","草稿数据暂存成功");
        }else {
            //判断 内容重复度 是否大于70%
            //先获取 当前系统中截止日期之前的
            LambdaQueryWrapper<BusiNotice> queryWrapper =new LambdaQueryWrapper<>();
            queryWrapper.gt(BusiNotice::getEndDate, DateUtil.format(new Date(),"yyyy-MM-dd")).eq(BusiNotice::getApprovalStatus,1);
            List<BusiNotice> list = this.list(queryWrapper);
            //无问题数据直接审核通过
            data.setApprovalStatus("1");
            data.setApprovalUserId(null);
            data.setApprovalTime(new Date());
            //遍历 list的每条数据与data对比，如果两条数据相似度大于70% 提出预警
            for (BusiNotice busiNotice : list) {
                if (StringUtils.isNotEmpty(data.getThirdUrl())&&StringUtils.isNotEmpty(busiNotice.getThirdUrl())){
                    if (data.getThirdUrl().equals(busiNotice.getThirdUrl())){
                        //title 和 detail 相似度大于70% 待审核
                        data.setApprovalStatus("0");
                        data.setSimilarityIds(Optional.ofNullable(data.getSimilarityIds()).orElse("")+busiNotice.getId()+",");
                        result.put("code",500);
                        result.put("msg","该通告已被人抢先一步上传，等待平台审核");
                    }
                }
            }
            if (StringUtils.isNotEmpty(data.getSimilarityIds())){
                //删除结尾的最后一个逗号
                data.setSimilarityIds(data.getSimilarityIds().substring(0, data.getSimilarityIds().length() - 1));
            }
            data.setCreateTime(new Date());
            this.save(data);
            MemberUserVO memberUserVO = memberUserService.queryByUserId(SecurityUtils.getUserId(), "01");
            if(data.getApprovalStatus().equals("1")) {
                if (StringUtils.isNotEmpty(memberUserVO.getIdentityType()) && memberUserVO.getIdentityType().equals("05")){
                    //如果审核通过
                    //从配置表中获取积分
                    MemberPoints memberPoints = new MemberPoints();
                    memberPoints.setUserId(SecurityUtils.getUserId());
                    memberPoints.setType("1");
                    memberPoints.setFromCode("fbgg");
                    memberPointsService.savePoints(memberPoints);
                 }
                //若是急招扣除对应急招券
                if (StringUtils.isNotEmpty(data.getIsUrgent())&&data.getIsUrgent().equals("1")){
                    memberCouponService.saveCoupon( data.getUserId(), "2", data.getId(), 1);
                }
                cardService.dealMemberRights2(data.getUserId(),null,"add_notice",1);
                if (CollectionUtil.isNotEmpty(data.getCustomForm())) {
                    cardService.dealMemberRights2(data.getUserId(),null,"report_info_collect",1);
                }
            }

        }
        //保存表单数据
        if (CollectionUtil.isNotEmpty(data.getCustomForm())){
            int sort = 1;
            for (String title : data.getCustomForm()) {
                BusiNoticeForm noticeForm = new BusiNoticeForm();
                noticeForm.setNoticeId(data.getId());
                noticeForm.setLabelTitle(title);
                noticeForm.setSort(sort++);
                busiNoticeFormService.save(noticeForm);
            }
        }

        if(data.getApprovalStatus().equals("1")){
            //进行模版消息通知
            sendNoticeMsg(data);
        }
        result.put("noticeId",data.getId());
        return result;
    }


    @Override
    @Transactional
    public JSONObject updateByIdVo(BusiNotice data) throws Exception {
        BusiNotice oldData = this.getById(data.getId());
        JSONObject result = new JSONObject();
        result.put("code",0);
        result.put("msg","自动审核通过，发布成功");
        //获取当前登录用户
        data.setUserId(SecurityUtils.getUserId());
        if (StringUtils.isNotEmpty(data.getApprovalStatus())&&data.getApprovalStatus().equals("8")){

            result.put("code",100);
            result.put("msg","草稿数据暂存成功");
        }else {
            //判断 内容重复度 是否大于70%
            //先获取 当前系统中截止日期之前的
            LambdaQueryWrapper<BusiNotice> queryWrapper =new LambdaQueryWrapper<>();
            queryWrapper.gt(BusiNotice::getEndDate, DateUtil.format(new Date(),"yyyy-MM-dd")).eq(BusiNotice::getApprovalStatus,1)
                    .ne(BusiNotice::getId,data.getId());
            List<BusiNotice> list = this.list(queryWrapper);
            //无问题数据直接审核通过
            data.setApprovalStatus("1");
            data.setApprovalUserId(null);
            data.setApprovalTime(new Date());
            //遍历 list的每条数据与data对比，如果两条数据相似度大于70% 提出预警
            for (BusiNotice busiNotice : list) {
                if (StringUtils.isNotEmpty(data.getThirdUrl())&&StringUtils.isNotEmpty(busiNotice.getThirdUrl())){
                    if (data.getThirdUrl().equals(busiNotice.getThirdUrl())){
                        //title 和 detail 相似度大于70% 待审核
                        data.setApprovalStatus("0");
                        data.setSimilarityIds(Optional.ofNullable(data.getSimilarityIds()).orElse("")+busiNotice.getId()+",");
                        result.put("code",500);
                        result.put("msg","该通告已被人抢先一步上传，等待平台审核");
                    }
                }
            }
            if (StringUtils.isNotEmpty(data.getSimilarityIds())){
                //删除结尾的最后一个逗号
                data.setSimilarityIds(data.getSimilarityIds().substring(0, data.getSimilarityIds().length() - 1));
            }
            //若是急招扣除对应急招券
            if (data.getApprovalStatus().equals("1")&&(StringUtils.isEmpty(oldData.getIsUrgent())||oldData.getIsUrgent().equals("0"))&&StringUtils.isNotEmpty(data.getIsUrgent())&&data.getIsUrgent().equals("1")){
                memberCouponService.saveCoupon( data.getUserId(), "2", data.getId(), 1);
            }
            this.updateById(data);
        }
        //先删除表单数据
        busiNoticeFormService.remove(new LambdaQueryWrapper<BusiNoticeForm>().eq(BusiNoticeForm::getNoticeId,data.getId()));
        //保存表单数据
        if (CollectionUtil.isNotEmpty(data.getCustomForm())){
            int sort = 1;
            for (String title : data.getCustomForm()) {
                BusiNoticeForm noticeForm = new BusiNoticeForm();
                noticeForm.setNoticeId(data.getId());
                noticeForm.setLabelTitle(title);
                noticeForm.setSort(sort++);
                busiNoticeFormService.save(noticeForm);
            }
        }
        result.put("noticeId",data.getId());
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject saveOrUpdateVo(BusiNotice data) throws Exception {
        if(ObjectUtil.isNotEmpty(data.getCityId())){
            //转换城市名称
            LambdaQueryWrapper<BaseCity> queryWrapper =new LambdaQueryWrapper<>();
            queryWrapper.eq(BaseCity::getCityId,data.getCityId());
            BaseCity city = cityService.getOne(queryWrapper);
            String cityName = city.getName();
            queryWrapper =new LambdaQueryWrapper<>();
            queryWrapper.eq(BaseCity::getCityId,city.getParentId());
            BaseCity parentCity = cityService.getOne(queryWrapper);
            data.setCity(cityName);
            data.setProvince(parentCity.getName());
        }
        if (StringUtils.isNotEmpty(data.getId())){
            return  this.updateByIdVo(data);
        }else {
            return this.saveVo(data);
        }

    }

    @Override
    @Transactional
    public void removeByIdsVo(List<String> ids) {
        for (String id : ids) {
            busiNoticeFormService.remove(new LambdaQueryWrapper<BusiNoticeForm>().eq(BusiNoticeForm::getNoticeId,id));
            this.removeById(id);
        }
    }


    /**
     * 查询博主报名的通告
     *
     * @param userId 博主id
     * @return java.util.List<com.ruoyi.busi.vo.BusiNoticeVo>
     * @author PQZ
     * @date 11:05 2025/3/22
     **/
    @Override
    public IPage<BusiNoticeVo> queryListByUserId(Long userId,Page<BusiNotice> page) {
        return busiNoticeMapper.queryListByUserId(userId,page);
    }
    /**
     * 发布或者下架
     * @param noticeId 通告主键
     * @param publishTakeDown 1发布0下架
     */
    @Override
    @Transactional
    public void publishTakeDown(String noticeId, String publishTakeDown) {
        BusiNotice data = this.getById(noticeId);
        if (publishTakeDown.equals("1")){
            //如果是发布
            //判断 内容重复度 是否大于70%
            //先获取 当前系统中截止日期之前的
            LambdaQueryWrapper<BusiNotice> queryWrapper =new LambdaQueryWrapper<>();
            queryWrapper.gt(BusiNotice::getEndDate, DateUtil.format(new Date(),"yyyy-MM-dd")).eq(BusiNotice::getApprovalStatus,1);
            List<BusiNotice> list = this.list(queryWrapper);
            //无问题数据直接审核通过
            data.setApprovalStatus("1");
            //遍历 list的每条数据与data对比，如果两条数据相似度大于70% 提出预警
            for (BusiNotice busiNotice : list) {
                if (StringUtils.isNotEmpty(data.getThirdUrl())&&StringUtils.isNotEmpty(busiNotice.getThirdUrl())){
                    if (data.getThirdUrl().equals(busiNotice.getThirdUrl())){
                        //title 和 detail 相似度大于70% 待审核
                        data.setApprovalStatus("0");
                        data.setSimilarityIds(Optional.ofNullable(data.getSimilarityIds()).orElse("")+busiNotice.getId()+",");
                    }
                }
            }
            if (StringUtils.isNotEmpty(data.getSimilarityIds())){
                //删除结尾的最后一个逗号
                data.setSimilarityIds(data.getSimilarityIds().substring(0, data.getSimilarityIds().length() - 1));
            }
            MemberUserVO memberUserVO = memberUserService.queryByUserId(data.getUserId(), "01");
            if (StringUtils.isNotEmpty(memberUserVO.getIdentityType())&&memberUserVO.getIdentityType().equals("05")){
                //如果审核通过
                MemberPoints memberPoints =new MemberPoints();
                memberPoints.setUserId(data.getUserId());
                memberPoints.setType("1");
                memberPoints.setFromCode("fbgg");
                memberPointsService.savePoints(memberPoints);
            }
        }else {
            //如果是关闭 关闭状态
            data.setApprovalStatus("2");
        }
        this.updateById(data);
    }

    /**
     * 审核接口
     * @param query 审核参数
     */

    @Override
    public void auditInfo(BusiNoticeQuery query) {
        BusiNotice busiNotice = this.getById(query.getId());
        //1代表审核通过
        if (query.getApprovalStatus().equals("1")){
            busiNotice.setApprovalStatus("1");
        }else {
            busiNotice.setApprovalStatus("9");
        }
        busiNotice.setApprovalUserId(SecurityUtils.getUserId());
        busiNotice.setApprovalTime(new Date());
        busiNotice.setApprovalRemark(query.getApprovalRemark());
        this.updateById(busiNotice);
        if(busiNotice.getApprovalStatus().equals("1")){
            //进行模版消息通知
            sendNoticeMsg(busiNotice);
        }
    }

    /**
     * 小程序端查询通告列表
     *
     * @param query TODO
     * @param page  TODO
     * @return com.baomidou.mybatisplus.core.metadata.IPage<com.ruoyi.busi.domain.BusiNotice>
     * @author vinjor-M
     * @date 15:41 2025/3/25
     **/
    @Override
    public IPage<BusiNoticeVo> queryAppListPage(AppNoticeQuery query, Page<BusiNotice> page) {
        if (ObjectUtil.isNotEmpty(query.getCityId())){
            LambdaQueryWrapper<BaseCity> queryWrapper =new LambdaQueryWrapper<>();
            queryWrapper.eq(BaseCity::getCityId,query.getCityId()).last("limit 1");
            BaseCity city = cityService.getOne(queryWrapper);
            query.setCityName(city.getName());
        }
        try {
            query.setUserId(SecurityUtils.getUserId());
        }catch (Exception ignored){

        }
        IPage<BusiNoticeVo> pageList = busiNoticeMapper.queryAppListPage(query,page);
        //打乱records的排列顺序
        List<BusiNoticeVo> records = pageList.getRecords();
        Collections.shuffle(records);
        pageList.setRecords(records);
        List<String> idList = pageList.getRecords().stream().map(BusiNotice::getId).collect(Collectors.toList());
        if(!idList.isEmpty()){
            //查博主类型字典
            List<BaseCategory> categoryList = baseCategoryService.listByParentCode(DictConstants.BLOGGER_TYPES_KEY,null);
            //转map
            Map<String,String> categoryMap = categoryList.stream().collect(Collectors.toMap(BaseCategory::getCode,BaseCategory::getTitle));
            pageList.getRecords().forEach(item->{
                //报名数量、浏览量、相关字典转换
                if(null==item.getViewNum()){
                    item.setViewNum(0);
                }
                item.setBloggerTypesText(noticeUtils.translateBloggerTypes(item.getBloggerTypes(),categoryMap));
                if(StringUtils.isNotEmpty(item.getImages())){
                    item.setMainImage(item.getImages().split(StrUtil.COMMA)[0]);
                }
            });
        }
        //TODO 后续需要拼接开通会员的通告主发布的通告，增加曝光度，这部分逻辑需要商讨
        return pageList;


    }
    /**
     * 小程序端查询浏览通告列表
     * @author zcy
     * @date 15:39 2025/3/29
     * @param query 查询条件
     * @return com.ruoyi.common.core.domain.AjaxResult
     **/
    @Override
    public List<BusiNoticeVo> appFootprintList(AppNoticeQuery query) {
        query.setUserId(SecurityUtils.getUserId());
        Integer num = cardService.getCardRightsValue(SecurityUtils.getUserId(), "02", "history");
        List<BusiNoticeVo> pageList = busiNoticeMapper.appFootprintList(query,num);
        List<String> idList = pageList.stream().map(BusiNotice::getId).collect(Collectors.toList());
        if(!idList.isEmpty()){
            //查博主类型字典
            List<BaseCategory> categoryList = baseCategoryService.listByParentCode(DictConstants.BLOGGER_TYPES_KEY,null);
            //转map
            Map<String,String> categoryMap = categoryList.stream().collect(Collectors.toMap(BaseCategory::getCode,BaseCategory::getTitle));
            pageList.forEach(item->{
                //报名数量、浏览量、相关字典转换
                if(null==item.getViewNum()){
                    item.setViewNum(0);
                }

                item.setBloggerTypesText(noticeUtils.translateBloggerTypes(item.getBloggerTypes(),categoryMap));
                if(StringUtils.isNotEmpty(item.getImages())){
                    item.setMainImage(item.getImages().split(StrUtil.COMMA)[0]);
                }
            });
        }
        return pageList;
    }

    /**
     * 小程序端查询通告详细信息
     * @author 朱春云
     * @date 15:39 2025/3/29
     * @param noticeId 通告id
     * @return JSONObject
     **/
    @Override
    public JSONObject appGetDetail(String noticeId) {
        JSONObject res =new JSONObject();
        //通告信息
        BusiNoticeVo detail = busiNoticeMapper.selectByIdVo(noticeId);
        //再获取报名动态表单
        List<BusiNoticeForm> customForm = busiNoticeFormService.list(new LambdaQueryWrapper<BusiNoticeForm>()
                .eq(BusiNoticeForm::getNoticeId,noticeId).orderByAsc(BusiNoticeForm::getSort));
        detail.setCustomForm(customForm.stream().map(BusiNoticeForm::getLabelTitle).collect(Collectors.toList()));
        //获取城市id
        LambdaQueryWrapper<BaseCity> queryWrapperCity = new LambdaQueryWrapper<>();
        queryWrapperCity.eq(BaseCity::getName,detail.getCity()).ne(BaseCity::getParentId,"0");
        List<BaseCity> list = cityService.list(queryWrapperCity);
        for (BaseCity baseCity : list) {
            queryWrapperCity = new LambdaQueryWrapper<>();
            queryWrapperCity.eq(BaseCity::getCityId,baseCity.getParentId());
            BaseCity byId = cityService.getOne(queryWrapperCity);
            if (byId.getName().equals(detail.getProvince())) {
                detail.setCityId(baseCity.getCityId());
            }
        }

        res.put("noticeDetail",detail);
        //通告主信息
        SysUser userDetail = userService.selectUserById(detail.getUserId());
        JSONObject userDetailJson = new JSONObject();
        userDetailJson.put("userId",userDetail.getUserId());
        userDetailJson.put("nickName",userDetail.getNickName());
        userDetailJson.put("avatar",Optional.ofNullable(userDetail.getAvatar()).orElse(""));
        //关联认证表
        LambdaQueryWrapper<MemberUser> queryWrapperMember =new LambdaQueryWrapper<>();
        queryWrapperMember.eq(MemberUser::getUserId,userDetail.getUserId()).eq(MemberUser::getUserType,"01").last("limit 1");
        MemberUser memberUser = memberUserService.getOne(queryWrapperMember);
        userDetailJson.put("identityType","未认证");
        if (null != memberUser&&StringUtils.isNotEmpty(memberUser.getIdentityType())){
            userDetailJson.put("identityType",dictDataService.selectDictLabel("dl_identity_type",memberUser.getIdentityType()));
        }
        res.put("userDetail",userDetailJson);
        //已报名用户头像
        List<BusiNoticeSign> signList = busiNoticeSignMapper.selectList(new LambdaQueryWrapper<BusiNoticeSign>().eq(BusiNoticeSign::getNoticeId, noticeId));
        List<String> signUserAvatarList = signList.stream().map(it-> Optional.ofNullable(it.getAvatar()).orElse("")
        ).collect(Collectors.toList());
        res.put("signUserAvatarList",signUserAvatarList);
        //当前用户是否已关注该通告主
        Long userId=null;
        try {
             userId = SecurityUtils.getUserId();
        }catch (Exception ignored){
            //未登录状态
        }
        res.put("isLove",false);
        res.put("isSign",false);
        res.put("passSign",false);
        if (null != userId){
            LambdaQueryWrapper<BusiUserLove> queryWrapper =new LambdaQueryWrapper<>();
            queryWrapper.eq(BusiUserLove::getUserId,userId).eq(BusiUserLove::getLoveUserId,detail.getUserId());
            if(userLoveService.getOne(queryWrapper)!=null){
                //当前用户已关注通告主
                res.put("isLove",true);
            }
            //当前用户是否已报名该通告
            if(busiNoticeSignMapper.selectOne(new LambdaQueryWrapper<BusiNoticeSign>().eq(BusiNoticeSign::getNoticeId, noticeId).eq(BusiNoticeSign::getUserId, userId).last("limit 1"))!=null){
                res.put("isSign",true);
            }

            //当前用户是否已通过当前报名
            if(busiNoticeSignMapper.selectOne(new LambdaQueryWrapper<BusiNoticeSign>().eq(BusiNoticeSign::getNoticeId, noticeId).eq(BusiNoticeSign::getUserId, userId).eq(BusiNoticeSign::getStatus,"02").last("limit 1"))!=null){
                res.put("passSign",true);
            }
        }
        return res;
    }
    /**
     * 小程序端查询订阅通告列表
     * @author zcy
     * @date 15:39 2025/3/29
     * @param query 查询条件
     * @return com.ruoyi.common.core.domain.AjaxResult
     **/
    @Override
    public IPage<BusiNoticeVo> subscribeList(AppNoticeQuery query, Page<BusiNotice> page) {
        //获取当前登录用户
        Long userId = SecurityUtils.getUserId();
        LambdaQueryWrapper<BusiSubscribe> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BusiSubscribe::getUserId,userId).last("limit 1");
        BusiSubscribe subscribe = subscribeService.getOne(queryWrapper);
        if(null!=subscribe){
            //如果使用订阅 则获取 订阅规则进行查询
            SubscribeDataObj subscribeDataObj = JSONObject.parseObject(subscribe.getJsonObj(), SubscribeDataObj.class);
            if (subscribeDataObj.getPlatformCode().contains("-1")){
                subscribeDataObj.setPlatformCode(null);
            }
            if (subscribeDataObj.getBloggerTypeCode().contains("-1")){
                subscribeDataObj.setBloggerTypeCode(null);
            }
            if (subscribeDataObj.getSettleTypeCode().contains("-1")){
                subscribeDataObj.setSettleTypeCode(null);
            }
            if(!subscribeDataObj.getFansLimit()){
                subscribeDataObj.setFansDown(null);
                subscribeDataObj.setFansUp(null);
            }
            if(!subscribeDataObj.getFeeLimit()){
                subscribeDataObj.setFeeDown(null);
                subscribeDataObj.setFeeUp(null);
            }
            IPage<BusiNoticeVo> pageList = baseMapper.subscribeList(subscribeDataObj, page);

            List<String> idList = pageList.getRecords().stream().map(BusiNotice::getId).collect(Collectors.toList());
            if(!idList.isEmpty()){
                //查博主类型字典
                List<BaseCategory> categoryList = baseCategoryService.listByParentCode(DictConstants.BLOGGER_TYPES_KEY,null);
                //转map
                Map<String,String> categoryMap = categoryList.stream().collect(Collectors.toMap(BaseCategory::getCode,BaseCategory::getTitle));
                pageList.getRecords().forEach(item->{
                    //报名数量、浏览量、相关字典转换
                    if(null==item.getViewNum()){
                        item.setViewNum(0);
                    }
                    item.setBloggerTypesText(noticeUtils.translateBloggerTypes(item.getBloggerTypes(),categoryMap));
                    if(StringUtils.isNotEmpty(item.getImages())){
                        item.setMainImage(item.getImages().split(StrUtil.COMMA)[0]);
                    }
                });
            }
            return pageList;
        }else {
            //未设置订阅则使用常规查询
            return new Page<>();
        }

    }
    /**
     * 小程序端关注订阅通告列表
     * @author zcy
     * @date 15:39 2025/3/29
     * @param query 查询条件
     * @return com.ruoyi.common.core.domain.AjaxResult
     **/
    @Override
    public IPage<BusiNoticeVo> loveList(AppNoticeQuery query, Page<BusiNotice> page) {
        //获取当前登录用户
        Long userId = SecurityUtils.getUserId();
        query.setUserId(userId);
        IPage<BusiNoticeVo> pageList = baseMapper.loveList(query, page);
        List<String> idList = pageList.getRecords().stream().map(BusiNotice::getId).collect(Collectors.toList());
        if(!idList.isEmpty()){
            //查博主类型字典
            List<BaseCategory> categoryList = baseCategoryService.listByParentCode(DictConstants.BLOGGER_TYPES_KEY,null);
            //转map
            Map<String,String> categoryMap = categoryList.stream().collect(Collectors.toMap(BaseCategory::getCode,BaseCategory::getTitle));
            pageList.getRecords().forEach(item->{
                //报名数量、浏览量、相关字典转换
                if(null==item.getViewNum()){
                    item.setViewNum(0);
                }
                item.setBloggerTypesText(noticeUtils.translateBloggerTypes(item.getBloggerTypes(),categoryMap));
                if(StringUtils.isNotEmpty(item.getImages())){
                    item.setMainImage(item.getImages().split(StrUtil.COMMA)[0]);
                }
            });
        }
        return pageList;
    }
    /**
     * 小程序端我的通告列表
     * @author zcy
     * @date 15:39 2025/3/29
     * @param query 查询条件
     * @return com.ruoyi.common.core.domain.AjaxResult
     **/
    @Override
    public IPage<BusiNoticeVo> myNoticeList(AppNoticeQuery query, Page<BusiNotice> page) {
        //获取当前登录用户
        Long userId = SecurityUtils.getUserId();
        query.setUserId(userId);
        IPage<BusiNoticeVo> pageList = baseMapper.myNoticeList(query, page);
        List<String> idList = pageList.getRecords().stream().map(BusiNotice::getId).collect(Collectors.toList());
        if(!idList.isEmpty()){
            //查博主类型字典
            List<BaseCategory> categoryList = baseCategoryService.listByParentCode(DictConstants.BLOGGER_TYPES_KEY,null);
            //转map
            Map<String,String> categoryMap = categoryList.stream().collect(Collectors.toMap(BaseCategory::getCode,BaseCategory::getTitle));
            pageList.getRecords().forEach(item->{
                //报名数量、浏览量、相关字典转换
                if(null==item.getViewNum()){
                    item.setViewNum(0);
                }
                item.setBloggerTypesText(noticeUtils.translateBloggerTypes(item.getBloggerTypes(),categoryMap));
                if(StringUtils.isNotEmpty(item.getImages())){
                    item.setMainImage(item.getImages().split(StrUtil.COMMA)[0]);
                }
            });
        }
        return pageList;
    }

    @Override
    public IPage<BusiNoticeVo> myPublishNoticeList(AppNoticeQuery query, Page<BusiNotice> page) {
        if (query.getUserId() == null) {
            //获取当前登录用户
            Long userId = SecurityUtils.getUserId();
            query.setUserId(userId);
        }
        IPage<BusiNoticeVo> pageList = baseMapper.myPublishNoticeList(query, page);
        List<String> idList = pageList.getRecords().stream().map(BusiNotice::getId).collect(Collectors.toList());
        if(!idList.isEmpty()){
            //查博主类型字典
            List<BaseCategory> categoryList = baseCategoryService.listByParentCode(DictConstants.BLOGGER_TYPES_KEY,null);
            //转map
            Map<String,String> categoryMap = categoryList.stream().collect(Collectors.toMap(BaseCategory::getCode,BaseCategory::getTitle));
            pageList.getRecords().forEach(item->{
                //报名数量、浏览量、相关字典转换
                if(null==item.getViewNum()){
                    item.setViewNum(0);
                }
                item.setBloggerTypesText(noticeUtils.translateBloggerTypes(item.getBloggerTypes(),categoryMap));
                if(StringUtils.isNotEmpty(item.getImages())){
                    item.setMainImage(item.getImages().split(StrUtil.COMMA)[0]);
                }
            });
        }
        return pageList;
    }

    @Override
    public IPage<BusiNoticeSign> reportList(AppNoticeQuery query, Page<BusiNoticeSign> page) {
        return busiNoticeSignMapper.reportList(page,query);
    }

    /**
     * 获取报名数量
     * @param query
     * @return
     */
    @Override
    public JSONObject reportNum(AppNoticeQuery query) {
        JSONObject result = new JSONObject();
        LambdaQueryWrapper<BusiNoticeSign> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BusiNoticeSign::getNoticeId,query.getNoticeId()).eq(BusiNoticeSign::getStatus,"01");
        Integer i = busiNoticeSignMapper.selectCount(queryWrapper);
        result.put("waitNum",i);
        queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BusiNoticeSign::getNoticeId,query.getNoticeId()).eq(BusiNoticeSign::getStatus,"02");
        Integer i2 = busiNoticeSignMapper.selectCount(queryWrapper);
        result.put("checkedNum",i2);
        return result;
    }





    /**
     * 获取token
     * @return
     */
    public String getAccessToken(String APPLET_APPID,String APPLET_SECRET) {
        String tokenUrl="https://api.weixin.qq.com/cgi-bin/token?appid="+APPLET_APPID+"&secret="+APPLET_SECRET+"&grant_type=client_credential";
        String responseStr= HttpUtil.get(tokenUrl);
        JSONObject object = JSON.parseObject(responseStr);
        String access_Token = object.getString("access_token");
        System.out.println("appid："+APPLET_APPID+"，secret："+APPLET_SECRET);
        System.out.println("获取到的token信息："+object.toJSONString());
        return access_Token;
    }




    /**
     * 推送
     * @param content
     * @return
     */
    public String push(Map<String, String> content) {
        /**小程序appid*/
        String APPLET_APPID=wxAppConfig.getAppId();
        /**公众号秘钥*/
        String OFFICIAL_ACCOUNT_SECRET=wechatPayConfig.getWxAppSecret();
        /**公众号appid*/
        String  OFFICIAL_ACCOUNT_APPID=wechatPayConfig.getAppId();
        /**公众号模板id*/
        String OFFICIAL_ACCOUNT_TEMPLATE_ID="h646Xn1xNc70npuUI7C3bvrL0DxZQgf7wM0qKRqep5c";
        //获取需要推送的用户openid
        String openid= content.get("openid");
        //获取用户token
        String token = getAccessToken(OFFICIAL_ACCOUNT_APPID,OFFICIAL_ACCOUNT_SECRET);

        String resultStatus = "0";//0:失败，1：成功
        try {
            //小程序统一消息推送
            String path = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + token;
            //封装参数
            JSONObject jsonData = new JSONObject();
            //小程序用户的openid
            jsonData.put("touser", openid);
            //公众号模板ID
            jsonData.put("template_id", OFFICIAL_ACCOUNT_TEMPLATE_ID);

            //公众号模板消息所要跳转的小程序，小程序的必须与公众号具有绑定关系
            JSONObject miniprogram = new JSONObject();
            //小程序APPID
            miniprogram.put("appid",APPLET_APPID);
            //跳转到小程序的页面路径
            miniprogram.put("pagepath","pages/notice/detail?id="+content.get("noticeId"));
            jsonData.put("miniprogram", miniprogram);
            //公众号消息数据封装
            JSONObject data = new JSONObject();
            //此处的参数key,需要对照模板中的key来设置
            data.put("thing15", getValue(content.get("noticeTitle")));
            data.put("thing2", getValue(content.get("platformName")));//联系方式
            data.put("thing19", getValue(content.get("tgzName")));//时间
            data.put("time78", getValue(content.get("startTime")));
            data.put("time38", getValue(content.get("endTime")));
            jsonData.put("data", data);
            System.out.println("请求参数："+jsonData);
            String s = HttpUtil.post(path, jsonData.toJSONString());
            System.out.println("返回结果："+s);
            resultStatus="1";
        } catch (Exception e) {
            log.error("微信公众号发送消息失败！"+e.getMessage());
            resultStatus="0";
        }
        return resultStatus;
    }



    /**
     * 获取data
     * @param value
     * @return
     */
    private JSONObject getValue(String value) {
        // TODO Auto-generated method stub
        JSONObject json = new JSONObject();
        json.put("value", value);
        return json;
    }


    public void sendNoticeMsg(BusiNotice notice){
        //开始线程
        ThreadUtil.execute(()->{
            if(null!=notice){
                //推送分两个1：符合订阅设置的 2：符合关注的
                SubScribeQuery subScribeQuery =new SubScribeQuery();
                subScribeQuery.setBloggerTypeCode(StringUtils.isNotEmpty(notice.getBloggerTypes())?notice.getBloggerTypes().split(","):new String[]{});
                subScribeQuery.setPlatformCode(notice.getPlatformCode());
                //结算方式
                subScribeQuery.setSettleTypeCode(notice.getIsPlatformFree().toString());
                subScribeQuery.setFansDown(notice.getFansDown());
                subScribeQuery.setFansUp(notice.getFansUp()==null?999999999:notice.getFansUp());
                subScribeQuery.setFeeDown(notice.getFeeDown());
                subScribeQuery.setFeeUp(notice.getFeeUp()==null?new BigDecimal(999999999):notice.getFeeUp());
                subScribeQuery.setLoveUserId(notice.getUserId().toString());
                List<JSONObject> okUser = subscribeService.getOkUser(subScribeQuery);
                //过滤重复wxOpenId
                List<String> wxOpenIdList = new ArrayList<>();
                for (JSONObject jsonObject : okUser) {
                    //判断关键词是否满足
                    boolean flag = true;
                    if (jsonObject.getString("allOk").equals("0")&&jsonObject.containsKey("keywordsList")&& StringUtils.isNotEmpty(jsonObject.getString("keywordsList"))){
                        String[] split = jsonObject.getString("keywordsList").split(",");
                        flag = false;
                        for (String s : split) {
                            //判断关键词是否满足
                            if (notice.getTitle().contains(s)) {
                                //满足关键词
                                flag = true;

                                break;
                            }

                        }
                    }
                    if (flag){
                        if (!wxOpenIdList.contains(jsonObject.getString("wxOpenId"))){
                            wxOpenIdList.add(jsonObject.getString("wxOpenId"));
                            //推送消息
                            Map<String, String> content =new HashMap<>();
                            content.put("openid",jsonObject.getString("wxOpenId"));
                            String noticeTitle = notice.getTitle();
                            if (noticeTitle.length() > 20) {
                                noticeTitle = noticeTitle.substring(0, 19);
                            }
                            content.put("noticeTitle", noticeTitle);
                            content.put("platformName",baseCategoryService.selectByCode(notice.getPlatformCode()).get(0).getTitle());
                            SysUser sysUser = userService.selectUserById(notice.getUserId());
                            content.put("tgzName",sysUser.getNickName());
                            content.put("startTime",DateUtil.format(notice.getApprovalTime(),"yyyy年MM月dd日 HH:mm"));
                            content.put("endTime",DateUtil.format(notice.getEndDate(),"yyyy年MM月dd日 HH:mm"));
                            push(content);
                    }
                    }
                }


            }

        });

    }
}
