package com.bonus.canteen.core.kitchen.service.impl;

import java.io.IOException;
import java.net.InetAddress;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bonus.canteen.core.kitchen.dto.KitchenDeviceListDTO;
import com.bonus.canteen.core.kitchen.vo.KitchenDeviceListVO;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.common.core.utils.DateUtils;
import com.bonus.common.core.utils.StringUtils;
import com.bonus.common.houqin.constant.DelFlagEnum;
import com.bonus.common.houqin.constant.DeviceTypeEnum;
import org.hibernate.validator.internal.util.StringHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bonus.canteen.core.kitchen.mapper.KitchenDeviceInfoMapper;
import com.bonus.canteen.core.kitchen.domain.KitchenDeviceInfo;
import com.bonus.canteen.core.kitchen.service.IKitchenDeviceInfoService;

import javax.annotation.Resource;

/**
 * 厨房设备基础信息Service业务层处理
 *
 * @author xsheng
 * @date 2025-06-16
 */
@Service
public class KitchenDeviceInfoServiceImpl extends ServiceImpl<KitchenDeviceInfoMapper,KitchenDeviceInfo> implements IKitchenDeviceInfoService {
    @Resource
    private KitchenDeviceInfoMapper kitchenDeviceInfoMapper;

    /**
     * 查询厨房设备基础信息
     *
     * @param deviceId 厨房设备基础信息主键
     * @return 厨房设备基础信息
     */
    @Override
    public KitchenDeviceListVO selectKitchenDeviceInfoByDeviceId(Long deviceId) {
        return kitchenDeviceInfoMapper.selectKitchenDeviceInfoByDeviceId(deviceId);
    }

    /**
     * 查询厨房设备基础信息列表
     *
     * @param kitchenDeviceInfo 厨房设备基础信息
     * @return 厨房设备基础信息
     */
    @Override
    public List<KitchenDeviceListVO> selectKitchenDeviceInfoList(KitchenDeviceListDTO kitchenDeviceInfo) {
        List<KitchenDeviceListVO> list = kitchenDeviceInfoMapper.selectKitchenDeviceInfoList(kitchenDeviceInfo);
        // 设置设备在线状态 现不确定验证方式 简易版
//        if(list != null && list.size() >0) {
//            for (KitchenDeviceListVO vo : list) {
//                String ip  = vo.getIpAddress() ;
//                boolean tf = isDeviceOnline(ip, 500); // 设置超时时间为500毫秒
//                vo.setDeviceNetworkState(tf == true ? 1 : 0);
//            }
//
//        }
        return list;
    }


    public static boolean isDeviceOnline(String ipAddress, int timeout) {
        try {
            InetAddress address = InetAddress.getByName(ipAddress);
            return address.isReachable(timeout);
        } catch (IOException e) {
            return false;
        }
    }
    /**
     * 新增厨房设备基础信息
     *
     * @param kitchenDeviceInfo 厨房设备基础信息
     * @return 结果
     */
    @Override
    public int insertKitchenDeviceInfo(KitchenDeviceInfo kitchenDeviceInfo) {
        if(StringHelper.isNullOrEmptyString(kitchenDeviceInfo.getDeviceNo())){
            throw new ServiceException("编设备编号不能为空");
        }
        if(kitchenDeviceInfo.getDeviceType() == null){
            throw new ServiceException("编设备类型不能为空");
        }
        if(StringHelper.isNullOrEmptyString(kitchenDeviceInfo.getDeviceSn())){
            throw new ServiceException("编设备sn号不能为空");
        }
        kitchenDeviceInfo.setDeviceNo(kitchenDeviceInfo.getDeviceNo() == null ? "2" : kitchenDeviceInfo.getDeviceNo().trim());
        kitchenDeviceInfo.setCreateTime(DateUtils.getNowDate());
        KitchenDeviceInfo bean;
        bean = kitchenDeviceInfoMapper.selectOne(
                Wrappers.<KitchenDeviceInfo>lambdaQuery()
                        .eq(KitchenDeviceInfo::getDeviceName, kitchenDeviceInfo.getDeviceName())
        );
        if(bean !=null) {
            throw new ServiceException("设备编号已存在，请检查后重新输入");
        }
        bean = kitchenDeviceInfoMapper.selectOne(
                Wrappers.<KitchenDeviceInfo>lambdaQuery()
                        .eq(KitchenDeviceInfo::getDeviceSn, kitchenDeviceInfo.getDeviceSn())
        );
        if(bean !=null) {
            throw new ServiceException("设备SN码已存在，请检查后重新输入");
        }
        bean = kitchenDeviceInfoMapper.selectOne(
                Wrappers.<KitchenDeviceInfo>lambdaQuery()
                        .eq(KitchenDeviceInfo::getDeviceName, kitchenDeviceInfo.getDeviceName())
        );
        if(bean !=null) {
            throw new ServiceException("设备名称已存在，请检查后重新输入");
        }
        try {
            return kitchenDeviceInfoMapper.insertKitchenDeviceInfo(kitchenDeviceInfo);
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }

    /**
     * 修改厨房设备基础信息
     *
     * @param kitchenDeviceInfo 厨房设备基础信息
     * @return 结果
     */
    @Override
    public int updateKitchenDeviceInfo(KitchenDeviceInfo kitchenDeviceInfo) {
        kitchenDeviceInfo.setUpdateTime(DateUtils.getNowDate());

        if(StringHelper.isNullOrEmptyString(kitchenDeviceInfo.getDeviceNo())){
            throw new ServiceException("编设备编号不能为空");
        }
        if(kitchenDeviceInfo.getDeviceType() == null){
            throw new ServiceException("编设备类型不能为空");
        }
        if(StringHelper.isNullOrEmptyString(kitchenDeviceInfo.getDeviceSn())){
            throw new ServiceException("编设备sn号不能为空");
        }

        KitchenDeviceInfo bean;
        bean = kitchenDeviceInfoMapper.selectOne(
                Wrappers.<KitchenDeviceInfo>lambdaQuery()
                        .eq(KitchenDeviceInfo::getDeviceName, kitchenDeviceInfo.getDeviceName())
                        .ne(KitchenDeviceInfo::getDeviceId, kitchenDeviceInfo.getDeviceId())
        );
        if(bean !=null){
            throw new ServiceException("设备名称已存在");
        }
        bean = kitchenDeviceInfoMapper.selectOne(
                Wrappers.<KitchenDeviceInfo>lambdaQuery()
                        .eq(KitchenDeviceInfo::getDeviceSn, kitchenDeviceInfo.getDeviceSn())
                        .ne(KitchenDeviceInfo::getDeviceId, kitchenDeviceInfo.getDeviceId())
        );
        if(bean !=null){
            throw new ServiceException("编设备sn码已存在");
        }
        bean = kitchenDeviceInfoMapper.selectOne(
                Wrappers.<KitchenDeviceInfo>lambdaQuery()
                        .eq(KitchenDeviceInfo::getDeviceNo, kitchenDeviceInfo.getDeviceNo())
                        .ne(KitchenDeviceInfo::getDeviceId, kitchenDeviceInfo.getDeviceId())
        );
        if(bean !=null){
            throw new ServiceException("编设备编码已存在");
        }
        try {
            return kitchenDeviceInfoMapper.update(kitchenDeviceInfo,
                Wrappers.<KitchenDeviceInfo>lambdaUpdate()
                        .eq(KitchenDeviceInfo::getDeviceId, kitchenDeviceInfo.getDeviceId()));
           // return kitchenDeviceInfoMapper.updateKitchenDeviceInfo(kitchenDeviceInfo);
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }

    /**
     * 批量删除厨房设备基础信息
     *
     * @param deviceIds 需要删除的厨房设备基础信息主键
     * @return 结果
     */
    @Override
    public int deleteKitchenDeviceInfoByDeviceIds(List<Long> deviceIds) {
        return kitchenDeviceInfoMapper.deleteKitchenDeviceInfoByDeviceIds(deviceIds);
    }

    /**
     * 删除厨房设备基础信息信息
     *
     * @param deviceId 厨房设备基础信息主键
     * @return 结果
     */
    @Override
    public int deleteKitchenDeviceInfoByDeviceId(Long deviceId) {
        return kitchenDeviceInfoMapper.deleteKitchenDeviceInfoByDeviceId(deviceId);
    }


    @Override
    public List<KitchenDeviceInfo> selectKitchenDeviceInfoSelect(KitchenDeviceListDTO kitchenDeviceInfo) {
        return kitchenDeviceInfoMapper.selectList(
                Wrappers.<KitchenDeviceInfo>lambdaQuery()
                        .like(StringUtils.isNotEmpty(kitchenDeviceInfo.getDeviceName()), KitchenDeviceInfo::getDeviceName, kitchenDeviceInfo.getDeviceName())
                        .like(StringUtils.isNotEmpty(kitchenDeviceInfo.getDeviceNo()), KitchenDeviceInfo::getDeviceNo, kitchenDeviceInfo.getDeviceNo())
                        .like(StringUtils.isNotEmpty(kitchenDeviceInfo.getDeviceSn()), KitchenDeviceInfo::getDeviceSn, kitchenDeviceInfo.getDeviceSn())
                        .eq(kitchenDeviceInfo.getDeviceType() != 0, KitchenDeviceInfo::getDeviceType, kitchenDeviceInfo.getDeviceType())
                        .eq(KitchenDeviceInfo::getDelFlag, DelFlagEnum.DEL_FALSE.key()) // 仅查询未删除的设备
        );
    }

    @Override
    public Map<Integer, String> deviceType() {
        Map<Integer, String> deviceMap   = DeviceTypeEnum.toMap();
        String [] stringArray  = new String[]{"摄像头","门禁","留样秤","留样柜","温湿度传感器","烟雾检测传感器","水表","电表","智能称重货架","智能厨余秤"};
        // 将 stringArray 转为 Set 便于快速查找
        Set<String> validValues = new HashSet<>(Arrays.asList(stringArray));
        // 使用 Stream 过滤，只保留 value 存在于 validValues 中的条目
        Map<Integer, String> filteredMap = deviceMap.entrySet().stream()
                .filter(entry -> validValues.contains(entry.getValue()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
        return filteredMap;
    }
}
