package com.yfd.platform.modules.auxcontrol.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yfd.platform.modules.auxcontrol.domain.DeviceSignal;
import com.yfd.platform.modules.auxcontrol.mapper.DeviceSignalMapper;
import com.yfd.platform.modules.auxcontrol.service.IDeviceSignalService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yfd.platform.modules.basedata.domain.SubstationComponent;
import com.yfd.platform.modules.basedata.mapper.SubstationComponentMapper;
import com.yfd.platform.utils.SecurityUtils;
import com.yfd.platform.utils.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 变电站-辅控设备-信号 服务实现类
 * </p>
 *
 * @author zhengsl
 * @since 2025-04-23
 */
@Service
public class DeviceSignalServiceImpl extends ServiceImpl<DeviceSignalMapper, DeviceSignal> implements IDeviceSignalService {

    @Resource
    private DeviceSignalMapper deviceSignalMapper;
    @Resource
    private SubstationComponentMapper substationComponentMapper;

    /**********************************
     * 用途说明: 修改变电站辅控设备信号
     * 参数说明  deviceSignal 变电站辅控设备信号
     * 返回值说明: com.yfd.platform.config.ResponseResult 返回修改成功或者失败
     ***********************************/
    @Override
    public boolean updateDeviceSignalValue(String slaveIp, String address, String type, String value,
                                           String dateString) throws ParseException {

        DeviceSignal deviceSignal = deviceSignalMapper.selectOneDeviceSignal(slaveIp, type, address);
        if (deviceSignal != null && ObjectUtil.isNotEmpty(deviceSignal)) {
            try {
                if ("yx".equals(type)) {
                    // 遥信
                    deviceSignal.setYxValue(Integer.parseInt(value));
                } else {
                    // 遥测
                    deviceSignal.setYcValue(value);
//                    deviceSignal.setYcValue(Convert.toBigDecimal(value));
                }
            } catch (NumberFormatException e) {
                // 处理转换异常，例如返回false或抛出更具体的异常
                return false;
            }

            deviceSignal.setLastmodifier("系统更新");
            // 设置最后修改时间
            Date parsedDate;
            if (StrUtil.isEmpty(dateString) || "null".equals(dateString)) {
                parsedDate = new Date();
            } else {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
                parsedDate = dateFormat.parse(dateString);
            }
            Timestamp timestamp = new Timestamp(parsedDate.getTime());
            deviceSignal.setLastmodifydate(timestamp);

            // 更新并检查结果
            return this.updateById(deviceSignal);
        }

        return false;
    }

    /**********************************
     * 用途说明: 新增变电站辅控设备信号
     * 参数说明 deviceSignal 变电站辅控设备信号对象
     * 返回值说明: boolean
     ***********************************/
    @Override
    public boolean addDeviceSignal(DeviceSignal deviceSignal) {
        String componentId = deviceSignal.getMainComponentId();
        if (StrUtil.isBlank(componentId)) {
            throw new RuntimeException("部件信息不能为空");
        }
        SubstationComponent substationComponent = substationComponentMapper.selectById(componentId);
        if (substationComponent == null) {
            throw new RuntimeException("当前部件不存在");
        }
        deviceSignal.setMainDeviceId(substationComponent.getMainDeviceId());
        LambdaQueryWrapper<DeviceSignal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DeviceSignal::getMainComponentId, deviceSignal.getMainComponentId());
        int count = deviceSignalMapper.selectCount(queryWrapper);
        //序号加1
        int orderNo = count + 1;
        deviceSignal.setOrderno(orderNo);

        String signalCode = deviceSignal.getSignalCode();
        if (StrUtil.isBlank(signalCode)) {
            throw new RuntimeException("信号编号不能为空");
        }
        LambdaQueryWrapper<DeviceSignal> signalCodeWrapper = new LambdaQueryWrapper<>();
        signalCodeWrapper.eq(DeviceSignal::getSignalCode, signalCode);
        int signalCount = deviceSignalMapper.selectCount(signalCodeWrapper);
        if (signalCount > 0) {
            throw new RuntimeException("当前信号编号已存在");
        }
        deviceSignal.setLastmodifier(SecurityUtils.getCurrentUsername());
        deviceSignal.setLastmodifydate(new Timestamp(System.currentTimeMillis()));
        return this.saveOrUpdate(deviceSignal);
    }

    /**********************************
     * 用途说明: 修改变电站辅控设备信号
     * 参数说明 deviceSignal 变电站辅控设备信号对象
     * 返回值说明: boolean
     ***********************************/
    @Override
    public boolean updateDeviceSignal(DeviceSignal deviceSignal) {

        String componentId = deviceSignal.getMainComponentId();
        if (StrUtil.isNotBlank(componentId)) {
            SubstationComponent substationComponent = substationComponentMapper.selectById(componentId);
            if (substationComponent == null) {
                throw new RuntimeException("当前部件不存在");
            }
            deviceSignal.setMainDeviceId(substationComponent.getMainDeviceId());
        }
        String signalCode = deviceSignal.getSignalCode();
        if (StrUtil.isNotBlank(signalCode)) {
            LambdaQueryWrapper<DeviceSignal> signalCodeWrapper = new LambdaQueryWrapper<>();
            signalCodeWrapper.ne(DeviceSignal::getSignalId, deviceSignal.getSignalId()).eq(DeviceSignal::getSignalCode, signalCode);
            int signalCount = deviceSignalMapper.selectCount(signalCodeWrapper);
            if (signalCount > 0) {
                throw new RuntimeException("当前信号编号已存在");
            }
        }
        deviceSignal.setLastmodifier(SecurityUtils.getCurrentUsername());
        deviceSignal.setLastmodifydate(new Timestamp(System.currentTimeMillis()));
        return this.saveOrUpdate(deviceSignal);
    }

    /**********************************
     * 用途说明:
     * 参数说明 deviceId 设备ID
     * 参数说明 signalName 信号名称
     * 参数说明 page
     * 返回值说明: com.baomidou.mybatisplus.extension.plugins.pagination.Page<com.yfd.platform.modules.auxcontrol.domain
     * .DeviceSignal>
     ***********************************/
    @Override
    public Page<DeviceSignal> getDeviceSignalPage(String systemcode,String meterDeviceId,String mainDeviceId, String componentId, String signalName,
                                                  Page<DeviceSignal> page) {
        LambdaQueryWrapper<DeviceSignal> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(systemcode)) {
            //查询条件拼接模糊
            queryWrapper.like(DeviceSignal::getSystemcode, systemcode);
        }
        if (StrUtil.isNotBlank(meterDeviceId)) {
            queryWrapper.eq(DeviceSignal::getMeterDeviceId, meterDeviceId);
        }
        //如果信号名称signalName不为空 模糊搜索
        if (StrUtil.isNotBlank(signalName)) {
            //查询条件拼接模糊
            queryWrapper.like(DeviceSignal::getSignalName, signalName);
        }
        if (StrUtil.isNotBlank(mainDeviceId)) {
            queryWrapper.eq(DeviceSignal::getMainDeviceId, mainDeviceId);
        }

        if (StrUtil.isNotBlank(componentId)) {
            queryWrapper.eq(DeviceSignal::getMainComponentId, componentId);
        }
        //排序
        queryWrapper.orderByAsc(DeviceSignal::getOrderno);
        return deviceSignalMapper.selectPage(page, queryWrapper);
    }

    /**********************************
     * 用途说明: 获取信号集合
     * 参数说明 stationCode 变电站编号
     * 参数说明 signalName 信号名称
     * 返回值说明: java.util.List<com.yfd.platform.modules.basedata.domain.TreeNode>
     ***********************************/
    @Override
    public List<Map<String, Object>> getDeviceSignalMaps(String stationCode, String signalName) {
        return deviceSignalMapper.getDeviceSignalMaps(stationCode, signalName);
    }

    /**********************************
     * 用途说明: 根据信号id查询信号信息
     * 参数说明 signalId 信号ID
     * 返回值说明: java.util.Map<java.lang.String,java.lang.Object>
     ***********************************/
    @Override
    public Map<String, Object> querySignalDataById(String signalId) {
        return deviceSignalMapper.querySignalDataById(signalId);
    }
}
