package cn.iocoder.yudao.module.server.service.policycommunications;

import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.server.controller.admin.policycommunications.vo.analysis.*;
import cn.iocoder.yudao.module.server.controller.admin.smsrecord.vo.SmsRecordSaveReqVO;
import cn.iocoder.yudao.module.server.dal.dataobject.policycommunications.TrsNonworkdayDO;
import cn.iocoder.yudao.module.server.dal.dataobject.policycommunications.TrsWcmdocDo;
import cn.iocoder.yudao.module.server.dal.dataobject.smsrecord.SmsRecordDO;
import cn.iocoder.yudao.module.server.dal.mysql.policycommunications.TrsNonworkdayMapper;
import cn.iocoder.yudao.module.server.dal.mysql.policycommunications.TrsWcmDocMapper;
import cn.iocoder.yudao.module.server.service.smsrecord.SmsRecordService;
import cn.iocoder.yudao.module.server.utils.SMSUtils;
import cn.iocoder.yudao.module.system.controller.admin.dept.vo.dept.DeptListReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.dept.DeptDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.dal.mysql.dept.DeptMapper;
import cn.iocoder.yudao.module.system.service.dept.DeptService;
import cn.iocoder.yudao.module.system.service.permission.PermissionService;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import com.baomidou.dynamic.datasource.annotation.DS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.math.BigDecimal;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import cn.iocoder.yudao.module.server.controller.admin.policycommunications.vo.*;
import cn.iocoder.yudao.module.server.dal.dataobject.policycommunications.PolicyCommunicationsDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.server.dal.mysql.policycommunications.PolicyCommunicationsMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.server.enums.ErrorCodeConstants.*;

/**
 * 政策沟通交流 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
public class PolicyCommunicationsServiceImpl implements PolicyCommunicationsService {

    @Resource
    private PolicyCommunicationsMapper policyCommunicationsMapper;

    @Resource
    private DeptService deptService;

    @Resource
    private AdminUserService userService; ;

    @Resource
    private DeptMapper deptMapper;

    @Resource
    private SMSUtils smsUtils;
    @Resource
    private TrsNonworkdayMapper trsNonworkdayMapper; // 非工作日Mapper
    @Resource
    private TrsWcmDocMapper trsWcmDocMapper;

    @Resource
    private SmsRecordService smsRecordService;

    // 缓存休息日数据
    private volatile List<TrsNonworkdayDO> cachedNonWorkdays;
    private volatile long cacheTimestamp = 0;
    private static final long CACHE_DURATION = 3600000; // 缓存1小时

    @Override
    public Long createPolicyCommunications(PolicyCommunicationsSaveReqVO createReqVO) {
        // 插入
        PolicyCommunicationsDO policyCommunications = BeanUtils.toBean(createReqVO, PolicyCommunicationsDO.class);
        policyCommunicationsMapper.insert(policyCommunications);
        // 返回
        return policyCommunications.getId();
    }

    @Override
    public void updatePolicyCommunications(PolicyCommunicationsSaveReqVO updateReqVO) {
        // 校验存在
        validatePolicyCommunicationsExists(updateReqVO.getId());
        // 更新
        if (updateReqVO.getReplayContent() != null && updateReqVO.getReplayIsPublic()==0 && updateReqVO.getRejectReason() == null) {
            updateReqVO.setDealStatus(1);
        }else if (updateReqVO.getReplayContent() != null && updateReqVO.getReplayIsPublic()==1 && updateReqVO.getRejectReason() == null) {
            updateReqVO.setDealStatus(2);
        }else if (updateReqVO.getRejectReason()!= null ) {
            updateReqVO.setDealStatus(3);
            updateReqVO.setReplayIsPublic(0);
        }
        PolicyCommunicationsDO updateObj = BeanUtils.toBean(updateReqVO, PolicyCommunicationsDO.class);
        policyCommunicationsMapper.updateById(updateObj);
    }

    public void updateStatusPolicyCommunications(PolicyCommunicationsSaveReqVO updateReqVO) {
        // 校验存在
        validatePolicyCommunicationsExists(updateReqVO.getId());
        PolicyCommunicationsDO policyCommunicationsDO = policyCommunicationsMapper.selectById(updateReqVO.getId());
        policyCommunicationsDO.setReplayIsPublic(updateReqVO.getReplayIsPublic());
        if (updateReqVO.getReplayIsPublic()==1) {
            policyCommunicationsDO.setDealStatus(2);
        }else{
            policyCommunicationsDO.setDealStatus(1);
        }
        policyCommunicationsMapper.updateById(policyCommunicationsDO);
    }

    @Override
    public void deletePolicyCommunications(Long id) {
        // 校验存在
        validatePolicyCommunicationsExists(id);
        // 删除
        policyCommunicationsMapper.deleteById(id);
    }

    private void validatePolicyCommunicationsExists(Long id) {
        if (policyCommunicationsMapper.selectById(id) == null) {
            throw exception(POLICY_COMMUNICATIONS_NOT_EXISTS);
        }
    }

    @Override
    public PolicyCommunicationsDO getPolicyCommunications(Long id) {
        return policyCommunicationsMapper.selectById(id);
    }

    @Override
    public PageResult<PolicyCommunicationsDO> getPolicyCommunicationsPage(PolicyCommunicationsPageReqVO pageReqVO) {
        PageResult<PolicyCommunicationsDO> pageResult = policyCommunicationsMapper.selectPage(pageReqVO);

        // 如果有状态筛选且是待处理状态，计算剩余工作日
        if (pageReqVO.getDealStatus() != null && pageReqVO.getDealStatus() == 0) {
            calculateRemainingWorkdaysForList(pageResult.getList());
        }

        return pageResult;
//        return policyCommunicationsMapper.selectPage(pageReqVO);
    }

    @Override
    public void updatePolicyCommunicationsSort(PolicyCommunicationsSortReqVO reqVO) {
        // 校验存在
        validatePolicyCommunicationsExists(reqVO.getId());
        // 更新排序
        PolicyCommunicationsDO updateObj = new PolicyCommunicationsDO();
        updateObj.setId(reqVO.getId());
        updateObj.setSortOrder(reqVO.getSortOrder()); // 假设有sortOrder字段
        policyCommunicationsMapper.updateById(updateObj);
    }

    @Transactional(rollbackFor = Exception.class)
    public void batchUpdateSort(List<PolicyCommunicationsBatchSortReqVO.SortItem> items) {
        if (items == null || items.isEmpty()) {
            return;
        }

        for (PolicyCommunicationsBatchSortReqVO.SortItem item : items) {
            // 校验存在
            validatePolicyCommunicationsExists(item.getId());
            // 更新排序
            PolicyCommunicationsDO updateObj = new PolicyCommunicationsDO();
            updateObj.setId(item.getId());
            updateObj.setSortOrder(item.getSortOrder());
            policyCommunicationsMapper.updateById(updateObj);
        }
    }

    public Long createPolicyCommunicationsAnonymous(PolicyCommunicationsAnonymousCreateReqVO createReqVO) {

        // 创建 DO 对象
        PolicyCommunicationsDO policyCommunications = BeanUtils.toBean(createReqVO, PolicyCommunicationsDO.class);

        // 设置默认值
        policyCommunications.setDealStatus(0); // 待处理状态
        policyCommunications.setReplyDeptid(createReqVO.getReplyDeptid()); // 处理部门默认为空
        policyCommunications.setSubmitTime(LocalDateTime.now());

        List<DeptDO> deptDOS = deptMapper.selectListByReplyDeptid(createReqVO.getReplyDeptid());
        for (DeptDO deptDO : deptDOS) {
            policyCommunications.setDepartmentId(deptDO.getId());
            policyCommunications.setDepartmentIdT(deptDO.getId());
            policyCommunications.setReplyDept(deptDO.getName());
        }
        if(createReqVO.getPolicyId()!=null){
            TrsWcmdocDo trsWcmdocDo = trsWcmDocMapper.selectById(createReqVO.getPolicyId());
            if(trsWcmdocDo!=null){
                policyCommunications.setPuburl(trsWcmdocDo.getDocpuburl());
            }
        }

        // 保存到数据库
        policyCommunicationsMapper.insert(policyCommunications);
        sendSmsReminder(policyCommunications,"POLICY_COMMUNICATIONS_CREATE");

        return policyCommunications.getId();
    }

/*    public PageResult<PolicyCommunicationsDO> getPolicyCommunicationsByUser(PolicyCommunicationsAnonymousQueryReqVO queryReqVO) {
        // 设置用户ID条件，并查询所有状态（包含公开和不公开）
        queryReqVO.setUserId(queryReqVO.getUserId());
        // dealStatus 和 replayIsPublic 不设置，查询所有状态
        return policyCommunicationsMapper.selectAnonymousPage(queryReqVO);
    }*/

    public PageResult<PolicyCommunicationsDO> getPolicyCommunicationsByUser(PolicyCommunicationsAnonymousQueryReqVO queryReqVO) {
        // 设置用户ID条件，并查询所有状态（包含公开和不公开）
        queryReqVO.setUserId(queryReqVO.getUserId());
        // dealStatus 和 replayIsPublic 不设置，查询所有状态
        PageResult<PolicyCommunicationsDO> pageResult = policyCommunicationsMapper.selectAnonymousPage(queryReqVO);

        // 处理数据：如果 submitIsPublic 是 1，则设置 replayIsPublic = 1
        List<PolicyCommunicationsDO> list = pageResult.getList();
        if (list != null && !list.isEmpty()) {
            for (PolicyCommunicationsDO item : list) {
                if (item.getSubmitIsPublic() != null && item.getSubmitIsPublic() == 0) {
                    item.setReplayIsPublic(0);
                }
            }
        }

        return pageResult;
    }

    @Override
    public PageResult<PolicyCommunicationsDO> getPolicyCommunicationsByPolicy(PolicyCommunicationsAnonymousQueryReqVO queryReqVO) {
        // 设置政策ID条件，并只查询公开状态
        queryReqVO.setPolicyId(queryReqVO.getPolicyId());
        queryReqVO.setDealStatus(2); // 只查询已公开（dealStatus = 2）
        queryReqVO.setReplayIsPublic(1); // 回复内容公开
        return policyCommunicationsMapper.selectAnonymousPage(queryReqVO);
    }

    @Override
    public PageResult<PolicyCommunicationsDO> getPublicPolicyCommunications(
            PolicyCommunicationsAnonymousQueryReqVO queryReqVO) {
        // 只查询公开状态
        queryReqVO.setDealStatus(2); // 只查询已公开（dealStatus = 2）
        queryReqVO.setReplayIsPublic(1); // 回复内容公开
        return policyCommunicationsMapper.selectAnonymousPage(queryReqVO);
    }






    @Override
    public PolicyCommunicationsAnalysisKpiRespVO getAnalysisKpi(PolicyCommunicationsAnalysisQueryReqVO queryReqVO) {
        PolicyCommunicationsAnalysisKpiRespVO respVO = new PolicyCommunicationsAnalysisKpiRespVO();

        // 构建查询参数
        PolicyCommunicationsPageReqVO pageReqVO = buildAnalysisPageReqVO(queryReqVO);

        // 1. 累计沟通总数
        PolicyCommunicationsPageReqVO totalQuery = BeanUtils.toBean(pageReqVO, PolicyCommunicationsPageReqVO.class);
        totalQuery.setPageSize(PageParam.PAGE_SIZE_NONE);
        Long totalCount = policyCommunicationsMapper.selectCount(totalQuery);
        respVO.setTotalCount(totalCount);

        // 2. 今日新增
        LocalDateTime todayStart = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0);
        LocalDateTime todayEnd = LocalDateTime.now().withHour(23).withMinute(59).withSecond(59);
        PolicyCommunicationsPageReqVO todayQuery = BeanUtils.toBean(pageReqVO, PolicyCommunicationsPageReqVO.class);
        todayQuery.setSubmitTime(new LocalDateTime[]{todayStart, todayEnd});
        todayQuery.setPageSize(PageParam.PAGE_SIZE_NONE);
        Long todayCount = policyCommunicationsMapper.selectCount(todayQuery);
        respVO.setTodayCount(todayCount);

        // 3. 平均处理时长
        Double avgProcessTime = policyCommunicationsMapper.selectAvgProcessTime(pageReqVO);
        respVO.setAvgProcessTime(BigDecimal.valueOf(avgProcessTime != null ? avgProcessTime : 0));

        // 4. 总回复率
        Long repliedCount = policyCommunicationsMapper.selectRepliedCount(pageReqVO);
        Double replyRate = totalCount > 0 ? (repliedCount * 100.0 / totalCount) : 0;
        respVO.setReplyRate(BigDecimal.valueOf(replyRate));

        // 5. 状态统计
        // 待处理
        pageReqVO.setDealStatus(0);
        Long pendingCount = policyCommunicationsMapper.selectCount(pageReqVO);
        respVO.setPendingCount(pendingCount);

        // 已回复
        pageReqVO.setDealStatus(1);
        Long repliedCount2 = policyCommunicationsMapper.selectCount(pageReqVO);
        respVO.setRepliedCount(repliedCount2);

        // 已公开
        pageReqVO.setDealStatus(2);
        Long publishedCount = policyCommunicationsMapper.selectCount(pageReqVO);
        respVO.setPublishedCount(publishedCount);

        return respVO;
    }

    @Override
    public PolicyCommunicationsRankRespVO getPolicyRankAnalysis(PolicyCommunicationsAnalysisQueryReqVO queryReqVO, String order, Integer limit) {
        PolicyCommunicationsRankRespVO respVO = new PolicyCommunicationsRankRespVO();

        // 1. 政策排行
        PolicyCommunicationsPageReqVO pageReqVO = buildAnalysisPageReqVO(queryReqVO);
        pageReqVO.setPageSize(limit != null ? limit : 10);

        List<PolicyCommunicationsRankRespVO.PolicyRankItem> policyRankList = policyCommunicationsMapper.selectPolicyRank(pageReqVO, order,limit);
        respVO.setPolicyRankList(policyRankList);

        // 2. 部门排行
        List<PolicyCommunicationsRankRespVO.DeptRankItem> deptRankList = policyCommunicationsMapper.selectDeptRank(pageReqVO);
        respVO.setDeptRankList(deptRankList);

        return respVO;
    }

    @Override
    public PolicyCommunicationsTrendAnalysisRespVO getTrendAnalysis(PolicyCommunicationsAnalysisQueryReqVO queryReqVO) {
        PolicyCommunicationsTrendAnalysisRespVO respVO = new PolicyCommunicationsTrendAnalysisRespVO();

        PolicyCommunicationsPageReqVO pageReqVO = buildAnalysisPageReqVO(queryReqVO);

        // 根据粒度查询趋势数据
        List<PolicyCommunicationsTrendAnalysisRespVO.TrendItem> trendData;
        switch (queryReqVO.getGranularity()) {
            case "week":
                trendData = policyCommunicationsMapper.selectWeekTrend(pageReqVO);
                break;
            case "month":
                trendData = policyCommunicationsMapper.selectMonthTrend(pageReqVO);
                break;
            default: // day
                trendData = policyCommunicationsMapper.selectDayTrend(pageReqVO);
                break;
        }

        respVO.setTrendData(trendData);

        // 提取时间标签和数量列表
        List<String> timeLabels = new ArrayList<>();
        List<Long> countValues = new ArrayList<>();
        List<Long> replyCountValues = new ArrayList<>();

        for (PolicyCommunicationsTrendAnalysisRespVO.TrendItem item : trendData) {
            if ("day".equals(queryReqVO.getGranularity())) {
                timeLabels.add(item.getDate());
            } else if ("week".equals(queryReqVO.getGranularity())) {
                timeLabels.add(item.getWeek());
            } else {
                timeLabels.add(item.getMonth());
            }
            countValues.add(item.getCount());
            replyCountValues.add(item.getReplyCount());
        }

        respVO.setTimeLabels(timeLabels);
        respVO.setCountValues(countValues);
        respVO.setReplyCountValues(replyCountValues);

        return respVO;
    }

    @Override
    public PolicyCommunicationsDepartmentAnalysisRespVO getDepartmentAnalysis(PolicyCommunicationsAnalysisQueryReqVO queryReqVO) {
        PolicyCommunicationsDepartmentAnalysisRespVO respVO = new PolicyCommunicationsDepartmentAnalysisRespVO();

        PolicyCommunicationsPageReqVO pageReqVO = buildAnalysisPageReqVO(queryReqVO);

        // 1. 部门详细分析数据
        List<PolicyCommunicationsDepartmentAnalysisRespVO.DepartmentAnalysisItem> departmentData =
                policyCommunicationsMapper.selectDepartmentAnalysis(pageReqVO);
        respVO.setDepartmentData(departmentData);

        // 2. 工作量分布
        List<PolicyCommunicationsDepartmentAnalysisRespVO.WorkloadItem> workloadDistribution =
                policyCommunicationsMapper.selectWorkloadDistribution(pageReqVO);
        respVO.setWorkloadDistribution(workloadDistribution);

        // 3. 效率排行
        List<PolicyCommunicationsDepartmentAnalysisRespVO.EfficiencyItem> efficiencyRanking =
                policyCommunicationsMapper.selectEfficiencyRanking(pageReqVO);
        respVO.setEfficiencyRanking(efficiencyRanking);

        return respVO;
    }

    @Override
    public PolicyCommunicationsOverdueListRespVO getOverdueList(PolicyCommunicationsAnalysisQueryReqVO queryReqVO, Integer overdueDays) {
        PolicyCommunicationsOverdueListRespVO respVO = new PolicyCommunicationsOverdueListRespVO();

        PolicyCommunicationsPageReqVO pageReqVO = buildAnalysisPageReqVO(queryReqVO);
        pageReqVO.setDealStatus(0); // 只查询待处理状态

        // 计算截止时间：当前时间减去超时天数
        LocalDateTime deadline = LocalDateTime.now().minusDays(overdueDays != null ? overdueDays : 30);

        // 查询超时数据
        List<PolicyCommunicationsOverdueListRespVO.OverdueItem> overdueList =
                policyCommunicationsMapper.selectOverdueList(pageReqVO, deadline);
        respVO.setOverdueList(overdueList);

        // 统计信息
        if (!overdueList.isEmpty()) {
            respVO.setTotalOverdueCount((long) overdueList.size());

            // 计算平均超时天数
            double avgOverdueDays = overdueList.stream()
                    .mapToInt(PolicyCommunicationsOverdueListRespVO.OverdueItem::getOverdueDays)
                    .average()
                    .orElse(0);
            respVO.setAvgOverdueDays(avgOverdueDays);

            // 计算最长超时天数
            int maxOverdueDays = overdueList.stream()
                    .mapToInt(PolicyCommunicationsOverdueListRespVO.OverdueItem::getOverdueDays)
                    .max()
                    .orElse(0);
            respVO.setMaxOverdueDays(maxOverdueDays);
        } else {
            respVO.setTotalOverdueCount(0L);
            respVO.setAvgOverdueDays(0.0);
            respVO.setMaxOverdueDays(0);
        }

        return respVO;
    }

    @Override
    public PolicyCommunicationsContentAnalysisRespVO getContentAnalysis(PolicyCommunicationsAnalysisQueryReqVO queryReqVO) {
        PolicyCommunicationsContentAnalysisRespVO respVO = new PolicyCommunicationsContentAnalysisRespVO();

        PolicyCommunicationsPageReqVO pageReqVO = buildAnalysisPageReqVO(queryReqVO);

        // 1. 类型分布
        List<PolicyCommunicationsContentAnalysisRespVO.TypeDistributionItem> typeDistribution =
                policyCommunicationsMapper.selectTypeDistribution(pageReqVO);
        respVO.setTypeDistribution(typeDistribution);

        // 2. 高频词云数据
        List<PolicyCommunicationsContentAnalysisRespVO.WordCloudItem> wordCloudData =
                policyCommunicationsMapper.selectWordCloudData(pageReqVO);
        respVO.setWordCloudData(wordCloudData);

        // 3. 热词统计
        List<PolicyCommunicationsContentAnalysisRespVO.HotWordItem> hotWords =
                policyCommunicationsMapper.selectHotWords(pageReqVO);
        respVO.setHotWords(hotWords);

        return respVO;
    }

    @Override
    public DepartmentListRespVO getDepartmentList() {
        DepartmentListRespVO respVO = new DepartmentListRespVO();

        // 查询所有有效的部门
        List<DeptDO> deptList = deptService.getDeptList(new DeptListReqVO());

        List<DepartmentListRespVO.DepartmentItem> departmentList = deptList.stream()
                .map(dept -> {
                    DepartmentListRespVO.DepartmentItem item = new DepartmentListRespVO.DepartmentItem();
                    item.setId(dept.getId());
                    item.setName(dept.getName());
                    item.setParentId(dept.getParentId());
                    item.setSort(dept.getSort());
                    return item;
                })
                .collect(Collectors.toList());

        respVO.setDepartmentList(departmentList);
        return respVO;
    }

    /**
     * 构建分析查询参数
     */
    private PolicyCommunicationsPageReqVO buildAnalysisPageReqVO(PolicyCommunicationsAnalysisQueryReqVO queryReqVO) {
        PolicyCommunicationsPageReqVO pageReqVO = BeanUtils.toBean(queryReqVO, PolicyCommunicationsPageReqVO.class);

        // 设置时间范围
        if (queryReqVO.getStartTime() != null && queryReqVO.getEndTime() != null) {
            pageReqVO.setSubmitTime(new LocalDateTime[]{queryReqVO.getStartTime(), queryReqVO.getEndTime()});
        }

        if (queryReqVO.getDepartmentId() != null ) {
            // 这里需要根据实际字段名调整
             pageReqVO.setDepartmentId(queryReqVO.getDepartmentId());
        }

        // 设置部门过滤
/*        if (queryReqVO.getDepartmentIds() != null && !queryReqVO.getDepartmentIds().isEmpty()) {
            // 这里需要根据实际字段名调整
            // pageReqVO.setDepartmentIds(queryReqVO.getDepartmentIds());
        }
        Long deptId = SecurityFrameworkUtils.getLoginUserDeptId();
        boolean trs_policy_user = permissionService.hasAnyRoles(SecurityFrameworkUtils.getLoginUser().getId(), "trs_policy_user");
        if(deptId!=null && trs_policy_user){
            pageReqVO.setDepartmentId(deptId);
        }*/


        return pageReqVO;
    }

    /**
     * 获取休息日数据（带缓存）
     */
    @DS("slave") // 使用从库查询，根据你的实际数据源名称配置
    private List<TrsNonworkdayDO> getNonWorkdaysWithCache() {
        long now = System.currentTimeMillis();

        // 如果缓存为空或缓存过期，重新加载
        if (cachedNonWorkdays == null || now - cacheTimestamp > CACHE_DURATION) {
            synchronized (this) {
                if (cachedNonWorkdays == null || now - cacheTimestamp > CACHE_DURATION) {
                    // 从从库查询休息日数据
                    cachedNonWorkdays = trsNonworkdayMapper.selectList();
                    cacheTimestamp = now;
                }
            }
        }

        return cachedNonWorkdays;
    }

    /**
     * 判断是否为工作日
     */
    private boolean isWorkday(LocalDate date, List<TrsNonworkdayDO> nonWorkdays) {
        if (nonWorkdays == null || nonWorkdays.isEmpty()) {
            return true; // 如果没有休息日数据，默认都是工作日
        }
        // 判断是否为休息日表中的日期
        String dateStr = date.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        for (TrsNonworkdayDO nonWorkday : nonWorkdays) {
            if (dateStr.equals(nonWorkday.getNDate())) {
                return false; // 在休息日表中，不是工作日
            }
        }
        return true; // 不在休息日表中，是工作日
    }

    /**
     * 计算剩余工作日（核心算法）
     * 从提交时间开始算，20个工作日时限
     */
    public Integer calculateRemainingWorkdays(LocalDateTime submitTime) {
        if (submitTime == null) {
            return 20; // 默认20个工作日
        }

        List<TrsNonworkdayDO> nonWorkdays = getNonWorkdaysWithCache();

        LocalDate submitDate = submitTime.toLocalDate();
        LocalDate today = LocalDate.now();

        // 如果提交日期在今天之后，直接返回20
        if (submitDate.isAfter(today)) {
            return 20;
        }

        int workdaysCounted = 0;
        LocalDate currentDate = submitDate;

        // 计算从提交日到昨天（含）的工作日数量
        LocalDate yesterday = today.minusDays(1);

        while (!currentDate.isAfter(yesterday) /*&& workdaysCounted < 20*/) {
            if (isWorkday(currentDate, nonWorkdays)) {
                workdaysCounted++;
            }
            currentDate = currentDate.plusDays(1);
        }

        // 计算剩余工作日
        int remainingWorkdays = 20 - workdaysCounted;

        // 如果今天还没计算，检查今天是否为工作日
        if (remainingWorkdays > 0 && isWorkday(today, nonWorkdays)) {
            // 今天还没结束，但统计时包括今天
            remainingWorkdays--;
        }

        // 处理已超期的情况
        if (remainingWorkdays < 0) {
            // 返回负数，表示已超期多少天
            return remainingWorkdays;
        }

        return remainingWorkdays;
    }

    /**
     * 为政策沟通记录计算剩余工作日
     */
    private void calculateRemainingWorkdaysForRecord(PolicyCommunicationsDO record) {
        if (record == null) return;

        // 只有在待处理状态才计算
        if (record.getDealStatus() != null && record.getDealStatus() == 0) { // 0 表示待处理
            Integer remainingWorkdays = calculateRemainingWorkdays(record.getSubmitTime());
            record.setRemainingWorkdays(remainingWorkdays);
            if(record.getSubmitIsPublic()==0){
                record.setReplayIsPublic(0);
            }else{
                record.setReplayIsPublic(1);
            }

        } else {
            // 非待处理状态不显示
            record.setRemainingWorkdays(null);
        }
    }

    /**
     * 批量计算剩余工作日
     */
    private void calculateRemainingWorkdaysForList(List<PolicyCommunicationsDO> list) {
        if (list == null || list.isEmpty()) return;

        for (PolicyCommunicationsDO record : list) {
            calculateRemainingWorkdaysForRecord(record);
        }
    }





    public void sendDeadlineReminders() {

        try {
            // 查询所有待处理的记录
            PolicyCommunicationsPageReqVO reqVO = new PolicyCommunicationsPageReqVO();
            reqVO.setPageNo(1);
            reqVO.setPageSize(Integer.MAX_VALUE); // 查询所有
            reqVO.setDealStatus(0); // 待处理状态

            PageResult<PolicyCommunicationsDO> pageResult = getPolicyCommunicationsPage(reqVO);

            int reminderCount = 0;
            for (PolicyCommunicationsDO item : pageResult.getList()) {
                Integer remainingWorkdays = item.getRemainingWorkdays();

                // 提前3个工作日提醒（包括当天）
                if (remainingWorkdays != null && remainingWorkdays == 3 && remainingWorkdays >= 0) {
                    sendSmsReminder(item,"POLICY_COMMUNICATIONS_DEADLINE");
                    reminderCount++;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送短信提醒
     */
    private void sendSmsReminder(PolicyCommunicationsDO item,String type) {
        try {
            // TODO: 根据你的实际短信服务实现
            // 这里需要获取办理人员的手机号
            List<AdminUserDO> userListByDeptIds = userService.getUserListByDeptIds(Collections.singleton(item.getDepartmentId()));
            for (AdminUserDO user : userListByDeptIds) {
                String mobile = user.getMobile();
                if(user.getStatus()!=0||user.getDeleted()==true)continue;
                if (mobile != null && !mobile.isEmpty()) {
                    // 构建短信内容
                    String content = "";
                    if (type.equals("POLICY_COMMUNICATIONS_DEADLINE")) {
                        content = buildReminderContent(item);
                    } else if (type.equals("POLICY_COMMUNICATIONS_CREATE")){
                        content = "您有新的政策沟通交流待答复，请及时前往内蒙古自治区集约化平台-政策沟通交流系统进行处理。";
                    }
                    // TODO: 调用短信发送服务
                    boolean b = false;
                    try {
                        System.out.println("调用");
                        //b = smsUtils.sendMsg(mobile, content);
                        // 创建短信记录
                        SmsRecordSaveReqVO smsRecord = new SmsRecordSaveReqVO();
                        smsRecord.setMobile(mobile);
                        smsRecord.setContent(content);
                        smsRecord.setSendStatus(0); // 待发送
                        smsRecord.setBusinessType(type);
                        smsRecord.setBusinessId(item.getId());
                        smsRecordService.createSmsRecord(smsRecord);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    // smsService.sendSms(mobile, content, SmsSceneEnum.POLICY_COMMUNICATIONS_DEADLINE);

                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 构建提醒内容
     */
    private String buildReminderContent(PolicyCommunicationsDO item) {
        String title = item.getTitle();
        String policyTitle = item.getPolicyTitle();
        Integer remaining = item.getRemainingWorkdays();

        String remainingText;
        if (remaining == 0) {
            remainingText = "今日截止";
        } else if (remaining == 1) {
            remainingText = "剩余1个工作日";
        } else if (remaining <= 3) {
            remainingText = String.format("剩余%d个工作日", remaining);
        } else {
            remainingText = String.format("剩余%d个工作日", remaining);
        }

        return String.format(
                "您有一条政策沟通待处理：%s，请及时办理。", remainingText
        );
    }



}