package com.yfd.platform.modules.basedata.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yfd.platform.annotation.Log;
import com.yfd.platform.component.voiceserver.VoiceServerService;
import com.yfd.platform.config.ResponseResult;
import com.yfd.platform.modules.basedata.domain.SubstationPatroldevice;
import com.yfd.platform.modules.basedata.domain.VoicePatrolLog;
import com.yfd.platform.modules.basedata.service.ISubstationPatroldeviceService;
import com.yfd.platform.modules.basedata.service.IVoicePatrolLogService;
import com.yfd.platform.utils.HttpRESTfulUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhengsl
 * @since 2025-04-25
 */
@RestController
@RequestMapping("/basedata/voice-patrol-log")
@Api(value = "VoicePatrolLogController", tags = "声纹巡视数据")
public class VoicePatrolLogController {

    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Resource
    private IVoicePatrolLogService voicePatrolLogService;
    @Resource
    private ISubstationPatroldeviceService substationPatroldeviceService;
    @Resource
    private HttpRESTfulUtils httpRESTfulUtils;
    @Resource
    private VoiceServerService voiceServerService;

    @GetMapping("/getVoicePatrolPage")
    @ApiOperation("分页查看声纹检测数据")
    public ResponseResult getVoicePatrolPage(Page<Map<String, Object>> page, String stationId, String patroldeviceId,
                                             String patroldeviceName
            , String startDate, String endDate) {
        if (StrUtil.isBlank(stationId)) {
            return ResponseResult.error("未传变电站信息");
        }
        String startFormat = "";
        if (StrUtil.isNotBlank(startDate)) {
            Date parseStart = DateUtil.parse(startDate);
            //一天的开始
            Date beginOfDay = DateUtil.beginOfDay(parseStart);
            startFormat = DateUtil.format(beginOfDay, "yyyy-MM-dd HH:mm:ss");
        }
        String endFormat = "";
        if (StrUtil.isNotBlank(startDate)) {
            Date parseEnd = DateUtil.parse(endDate);
            //一天的结束
            Date endOfDay = DateUtil.endOfDay(parseEnd);
            endFormat = DateUtil.format(endOfDay, "yyyy-MM-dd HH:mm:ss");
        }
        LambdaQueryWrapper<VoicePatrolLog> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(stationId)) {
            queryWrapper.eq(VoicePatrolLog::getStationId, stationId);
        }
        if (StrUtil.isNotBlank(patroldeviceId)) {
            queryWrapper.eq(VoicePatrolLog::getPatroldeviceId, patroldeviceId);
        }
        if (StrUtil.isNotBlank(patroldeviceName)) {
            queryWrapper.like(VoicePatrolLog::getPatroldeviceName, patroldeviceName);
        }
        if (StrUtil.isNotBlank(startFormat) && StrUtil.isNotBlank(endFormat)) {
            queryWrapper.le(VoicePatrolLog::getDate, endFormat);
            queryWrapper.ge(VoicePatrolLog::getDate, startFormat);
        }
        queryWrapper.orderByDesc(VoicePatrolLog::getDate);
        Page<Map<String, Object>> mapPage = voicePatrolLogService.pageMaps(page, queryWrapper);
        return ResponseResult.successData(mapPage);
    }

    @Log(module = "声纹检测", value = "执行声纹任务", type = "1")
    @PostMapping("/executeVoicePatrolTask")
    @ApiOperation("执行声纹任务")
    public ResponseResult executeVoicePatrolTask(String id, String duration) {
        SubstationPatroldevice substationPatroldevice = substationPatroldeviceService.getById(id);
        if (substationPatroldevice == null) {
            return ResponseResult.error("当前设备不存在");
        }
        Boolean aBoolean = redisTemplate.hasKey(id);
        if (aBoolean != null && aBoolean) {
            throw new RuntimeException("当前设备正在录制");
        }
        redisTemplate.opsForValue().set(id, "1", 5 * 60);
        // 生成日志对象基础信息（同步执行）
        VoicePatrolLog log = buildBaseLog(substationPatroldevice, duration);
        // 提交异步任务
        voiceServerService.executeVoiceTaskAsync(substationPatroldevice, duration, log);
        // 立即返回响应
        return ResponseResult.success("任务已提交");
    }

    // 基础日志对象构建方法
    private VoicePatrolLog buildBaseLog(SubstationPatroldevice device, String duration) {
        VoicePatrolLog log = new VoicePatrolLog();
        log.setPatroldeviceId(device.getPatroldeviceId());
        log.setPatroldeviceCode(device.getPatroldeviceCode());
        log.setPatroldeviceName(device.getPatroldeviceName());
        log.setStationId(device.getStationId());
        log.setStationCode(device.getStationCode());
        log.setStationName(device.getStationName());
        log.setDate(DateUtil.now());
        log.setDuration(duration);
        return log;
    }
}
