package com.dsk.monitor.job;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dsk.common.tenant.helper.TenantHelper;
import com.dsk.common.utils.DateUtils;
import com.dsk.common.utils.redis.RedisUtils;
import com.dsk.monitor.domain.dto.PushMonitorInfo;
import com.dsk.monitor.domain.dto.PushMonitorRules;
import com.dsk.monitor.domain.vo.ConditionVo;
import com.dsk.monitor.domain.vo.PushMonitorDynamicPageVo;
import com.dsk.monitor.domain.vo.PushSettingHolidayVo;
import com.dsk.monitor.mapper.PushMonitorInfoMapper;
import com.dsk.monitor.mapper.PushMonitorRulesMapper;
import com.dsk.monitor.service.MonitorService;
import com.dsk.monitor.util.SendMessageUtil;
import org.apache.commons.collections4.MapUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.*;

/**
 * @ClassName PushScheduling
 * @Description 发送短信
 * @Author Dgm
 * @Date 2023/12/9 13:51
 * @Version
 */
@Component
public class PushScheduling {

    @Resource
    private MonitorService monitorService;

    @Resource
    private PushMonitorInfoMapper monitorInfoMapper;

    @Resource
    private PushMonitorRulesMapper rulesMapper;

    /**
     * 关闭推动
     */
    private static final Integer IS_SWITCH = 1;

//    @Scheduled(cron = "0 0/2 * * * ?")
    @Scheduled(cron = "0 0 * * * ?")
    public void receiveModePhone() throws Exception {
        TenantHelper.setTenantId("1");
        // 设置redisKey
        String lockKey = "stockKey";
        // 设置redisValue
        String value = UUID.randomUUID().toString();
        // 这里默认设置超时时间为30秒
        boolean hasKey = RedisUtils.setObjectIfAbsent(lockKey, value, Duration.ofMillis(1000 * 30));
        if (!hasKey) {
            return ;
        }
        // 是否是周末
        boolean isWeekend = DateUtil.isWeekend(new Date());
        PushSettingHolidayVo holidayVo = new PushSettingHolidayVo();
        holidayVo.setTimestamp(System.currentTimeMillis());
        Map<String, Object> settingHolidayMap = monitorService.settingHoliday(holidayVo);
        Integer settingHolidayCode = MapUtils.getInteger(settingHolidayMap, "code", 300);
        Boolean settingHolidayData = MapUtils.getBoolean(settingHolidayMap, "data", null);
        if (200 == settingHolidayCode) {
            isWeekend = !settingHolidayData;
        }
        // 获取当前整点时间
        Integer concurrentHour = DateUtils.getHour();
        QueryWrapper<PushMonitorRules> queryWrapper = new QueryWrapper();
        List<PushMonitorRules> detailList  = rulesMapper.selectList(queryWrapper);
        Integer timeStart = 0;
        Integer timeEnd = 24;
        for (PushMonitorRules detail : detailList) {
            if (IS_SWITCH.equals(detail.getReceiveMode())) {
                continue;
            }
            Integer pushFrequency = detail.getPushFrequency();
            if (pushFrequency > 1) {
                if (isWeekend) {
                    continue;
                }
            }
            // 推送时段-起
            String timePeriodStart = detail.getTimePeriodStart();
            if (ObjectUtil.isNotEmpty(timePeriodStart)) {
                timePeriodStart = timePeriodStart.substring(0,2);
                if (timePeriodStart.contains("0")) {
                    timePeriodStart = timePeriodStart.substring(1,2);
                }
                timeStart = Integer.valueOf(timePeriodStart);
            }
            // 推送时段-止
            String timePeriodEnd = detail.getTimePeriodEnd();
            if (ObjectUtil.isNotEmpty(timePeriodEnd)) {
                timePeriodEnd = timePeriodEnd.substring(0,2);
                if (timePeriodEnd.contains("0")) {
                    timePeriodEnd = timePeriodEnd.substring(1,2);
                }
                timeEnd = Integer.valueOf(timePeriodEnd);
            }
            if (ObjectUtil.isNotEmpty(timePeriodStart) && ObjectUtil.isEmpty(timePeriodEnd)) {
                if (concurrentHour >= timeStart) {
                    savePushMonitorInfo(detail);
                }
            }
            if (ObjectUtil.isEmpty(timePeriodStart) && ObjectUtil.isNotEmpty(timePeriodEnd)) {
                if (concurrentHour <= timeEnd) {
                    savePushMonitorInfo(detail);
                }
            }
            if (ObjectUtil.isEmpty(timePeriodStart) && ObjectUtil.isEmpty(timePeriodEnd)) {
                savePushMonitorInfo(detail);
            }
            if (ObjectUtil.isNotEmpty(timePeriodStart) && ObjectUtil.isNotEmpty(timePeriodEnd)) {
                if (concurrentHour >= timeStart && concurrentHour <= timeEnd) {
                    savePushMonitorInfo(detail);
                }
            }
        }
    }

    /***
     *@Description: 查询并保存动态信息
     *@Param:
     *@return: void
     *@Author: Dgm
     *@date: 2024/3/17 14:30
     */
    private void savePushMonitorInfo (PushMonitorRules detail) throws Exception {
        PushMonitorDynamicPageVo pageVo = new PushMonitorDynamicPageVo();
        pageVo.setUserId(detail.getUserId());
        ConditionVo vo = new ConditionVo();
        // 截止时间
        vo.setEndTime(DateUtils.getTime());
        vo.setBeginTime(DateUtils.format(DateUtils.addDays(new Date(),-1)));
        // 条件查询监控维度子级名称数组
        vo.setDimension(getParamList(detail.getDimension()));
        // 条件查询监控维度父级名称数组
        vo.setParentDimension(getParamList((detail.getRiskType())));
        vo.setUserId(detail.getUserId());
        pageVo.setCondition(vo);;
        Map<String, Object> resMap = monitorService.companyDynamicPageScheduled(pageVo);
        Integer code = MapUtils.getInteger(resMap, "code", 300);
        Map data = MapUtils.getMap(resMap, "data", null);
        if (200 != code) {
            return;
        }
        Integer count = MapUtils.getInteger(data, "totalCount", 0);
        if (count > 0 ) {
            SendMessageUtil.sendMessage(detail.getPhones(), count.toString());
//            SendMessageUtil.sendMessage(detail.getPhones(), getContent(count));
        }
        if (count > 0) {
            PushMonitorInfo pushMonitorInfo = new PushMonitorInfo();
            pushMonitorInfo.setUserId(detail.getUserId());
            pushMonitorInfo.setCount(count);
            monitorInfoMapper.insert(pushMonitorInfo);
        }
    }

    public static  List<String> getParamList(String dimension) {
        List<String> getParamList = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(dimension)) {
            getParamList = Arrays.asList(dimension.split(","));
        }
        return getParamList;
    }

    /**
     *@Description: 组装推送信息
     *@Param:
     *@return: java.lang.String
     *@Author: Dgm
     *@date: 2024/3/16 14:05
     */
    private String getContent (Integer number) {
        return "您监控的企业发生".concat(number.toString()).concat("条风险动态。");
    }

}
