package com.fs.watch.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.fs.common.exception.CustomException;
import com.fs.common.exception.ServiceException;
import com.fs.common.utils.DateUtils;
import com.fs.his.domain.FsUserWatch;
import com.fs.his.service.IFsUserWatchService;
import com.fs.watch.domain.WatchBasicInfo;
import com.fs.watch.domain.WatchDeviceInfo;
import com.fs.watch.domain.WatchDeviceStatus;
import com.fs.watch.domain.WatchFsUser;
import com.fs.watch.domain.vo.WatchDeviceInfoAndUserIdVo;
import com.fs.watch.domain.vo.WatchDeviceInfoVo;
import com.fs.watch.domain.vo.WatchLastHealthDataVo;
import com.fs.watch.mapper.WatchDeviceInfoMapper;
import com.fs.watch.param.WatchDeviceInfoQueryParam;
import com.fs.watch.service.*;
import com.fs.watch.utils.MyHttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.CompletableFuture;

/**
 * @author Administrator
 * @description 针对表【watch_device_info(设备硬件信息)】的数据库操作Service实现
 * @createDate 2024-10-15 11:06:50
 */
@Service
public class WatchDeviceInfoServiceImpl implements WatchDeviceInfoService {
    @Autowired
    private WatchDeviceInfoMapper mapper;

    @Autowired
    private WatchDataService watchDataService;

    @Autowired
    private WatchUserService watchUserService;

    @Autowired
    private IFsUserWatchService fsUserWatchService;

    @Autowired
    private WatchBasicInfoService watchBasicInfoService;

    @Autowired
    private WatchDeviceStatusService watchDeviceStatusService;

    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Autowired
    private DeviceSetUpService deviceSetUpService;

    private final MyHttpUtils httpUtils = new MyHttpUtils();


    /**
     * 新增设备信息
     *
     * @param deviceInfo 设备信息
     * @return 结果
     */
    @Override
    public int insertDeviceInfo(WatchDeviceInfo deviceInfo) {
        //查看该设备是否存在
        WatchDeviceInfoVo vo = getByNumber(deviceInfo.getDeviceNumber());
        if (vo != null) {
            throw new ServiceException("该设备已存在");
        }
        //检测设备是否存在
        Integer status = this.getStatus(deviceInfo.getDeviceNumber());
        if (status == 4 || status < 0) {
            throw new ServiceException().setMessage("设备不存在");
        }
        deviceInfo.setCreateTime(DateUtils.getNowDate());
        int i = mapper.insertDeviceInfo(deviceInfo);
//        //推送mysql设备基础信息 device_info给相关公司
//        WatchDeviceInfoVo deviceInfoVo = mapper.selectDeviceInfoByDeviceId(deviceInfo.getDeviceId());
//        Map<String, Object> params = getDeviceMap(deviceInfoVo);
//        if (deviceInfoVo.getCompanyId() != null) {
//            Company company = companyService.selectCompanyByCompanyId(deviceInfoVo.getCompanyId());
//            if (company != null) {
//                String pushUrl = company.getPushUrl();
//                if (StringUtils.isNotBlank(pushUrl)) {
////                    Map response = httpUtils.getPost3(pushUrl + "/app/watch/syncWatchDevice", params);
//                    Map response = httpUtils.getPost3(pushUrl + "/watchDeviceInfo/insert", params);
//                    int code = (int) response.get("code");
//                    String msg = response.get("msg").toString();
//                    if (code != 200) {
//                        if (!("参数错误".equals(msg)) && !("设备已存在".equals(msg))) {
//                            //redis缓存 12:00定时重新新增
//                            redisCache.setCacheObject("errorDevice:" + deviceInfoVo.getDeviceNumber(), params);
//                        }
//                    }
//                }
//            }
//
//        }
        return i;
    }

    @Override
    public int updateByDeviceNumber(WatchDeviceInfo data) {
        int flag = 0;
        WatchDeviceInfoVo vo = getByNumber(data.getDeviceNumber());
        if (vo == null) {
            //新增
            data.setCreateTime(DateUtils.getNowDate());
            //判断是否绑定用户
            WatchFsUser user = watchUserService.selectWatchFsUserByDeviceId(data.getDeviceNumber());
            if (user != null) {
                FsUserWatch fsUserWatch = fsUserWatchService.getLastByUserId(user.getUserId());
                if (fsUserWatch != null) {
                    data.setDoctorId(fsUserWatch.getDoctorId());
                    data.setCompanyId(fsUserWatch.getCompanyId());
                    data.setCompanyUserId(fsUserWatch.getCompanyUserId());
                    data.setLifeStatus(2);
                }
            }
            flag = mapper.insertDeviceInfo(data);
        } else {
            //更新
            data.setUpdateTime(DateUtils.getNowDate());
            flag = mapper.updateByDeviceNumber(data);

        }
        return flag;
    }

    @Override
    public int remove(String deviceNums) {
        return mapper.remove(deviceNums);
    }

    @Override
    public Map<String, Object> getInfo(String deviceNumber) {
        Map<String, Object> params = new HashMap<>();
        params.put("device_id", deviceNumber);
        //电量 信号
        WatchBasicInfo info = watchBasicInfoService.queryLastByDeviceId(deviceNumber);
        if (info != null) {
            System.out.println(info);
            Map<String, Object> map = new HashMap<>();
            map.put("rssi", info.getRssi());
            map.put("device_id", deviceNumber);
            map.put("battery", info.getBattery());
            //查询设备状态
            map.put("status",getStatus(deviceNumber));
            return map;
        }
        return null;
    }

    private Map<String, Object> getDeviceMap(WatchDeviceInfo deviceInfo) {
        Map<String, Object> params = new HashMap<>();
        params.put("device_id", deviceInfo.getDeviceId());
        params.put("companyId", deviceInfo.getCompanyId());
        params.put("deviceNumber", deviceInfo.getDeviceNumber());
        params.put("battery", deviceInfo.getBattery());
        params.put("rssi", deviceInfo.getRssi());
        params.put("status", deviceInfo.getStatus());
        params.put("createTime", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, deviceInfo.getCreateTime()));
        params.put("createBy", deviceInfo.getCreateBy());
        params.put("updateTime", null);
        params.put("updateBy", deviceInfo.getUpdateBy());
        params.put("IsDel", deviceInfo.getIsDel());
        return params;
    }

    /**
     * 查询设备信息列表
     *
     * @param param 设备信息
     * @return 设备信息
     */
    @Override
    public List<WatchDeviceInfoVo> selectDeviceInfoList(WatchDeviceInfoQueryParam param) {
        List<WatchDeviceInfoVo> watchDeviceInfoVos = mapper.selectDeviceInfoList(param);
        if (param.getLifeStatus() != null && param.getLifeStatus() == 0) {
            return watchDeviceInfoVos;
        }

        List<CompletableFuture<Void>> futures = new ArrayList<>();
        for (WatchDeviceInfoVo watchDeviceInfoVo : watchDeviceInfoVos) {
            CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
                //查询设备状态
                Integer deviceStatus = getStatus(watchDeviceInfoVo.getDeviceNumber());
                if (deviceStatus != null) {
                    watchDeviceInfoVo.setStatus(deviceStatus);
                }
                List<WatchLastHealthDataVo> watchLastHealthDataVos = watchDataService.queryLastWatchData(watchDeviceInfoVo.getDeviceNumber());
                watchDeviceInfoVo.setLastHealthData(watchLastHealthDataVos);
                // 判断健康状态
                boolean isNormal = true;
                for (WatchLastHealthDataVo vo : watchLastHealthDataVos) {

                    String status = vo.getStatus();
                    if ((status.contains("高") || status.contains("低")) && !status.contains("正常")) {
                        isNormal = false;
                        break; // 一旦发现异常状态，立即退出循环
                    }

                }
                watchDeviceInfoVo.setIsNormal(isNormal ? "正常" : "异常");
            }, threadPoolTaskExecutor);
            futures.add(future);
        }
        // 等待所有任务完成
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
        return watchDeviceInfoVos;
    }

    /**
     * 查询设备信息列表
     *
     * @return 设备信息
     */
    @Override
    public List<WatchDeviceInfoAndUserIdVo> selectByUserExist() {

        return mapper.selectByUserExist();
    }

    /**
     * 查询设备信息
     *
     * @param deviceId 设备信息主键
     * @return 设备信息
     */
    @Override
    public WatchDeviceInfoVo selectDeviceInfoByDeviceId(Long deviceId) {
        WatchDeviceInfoVo deviceInfoVo = mapper.selectDeviceInfoByDeviceId(deviceId);
        //同步设备信息
//        Map<String, Object> info = getInfo(deviceInfoVo.getDeviceNumber());
//        deviceInfoVo.setRssi(Integer.valueOf(info.get("rssi").toString()));
//        deviceInfoVo.setBattery(Integer.valueOf(info.get("battery").toString()));
//        deviceInfoVo.setStatus(Integer.valueOf(info.get("status").toString()));
//        updateDeviceInfo(deviceInfoVo);
        return deviceInfoVo;
    }

    /**
     * 修改设备信息
     *
     * @param deviceInfo 设备信息
     * @return 结果
     */
    @Override
    public int updateDeviceInfo(WatchDeviceInfo deviceInfo) {
        //检测设备是否存在
        Integer status = this.getStatus(deviceInfo.getDeviceNumber());
        if (status == 4 || status < 0) {
            throw new CustomException("设备不存在");
        }
        Date nowDate = DateUtils.getNowDate();
        deviceInfo.setUpdateTime(nowDate);
        return mapper.updateDeviceInfo(deviceInfo);
    }

    @Override
    public WatchDeviceInfoVo getByNumber(String number) {
        return mapper.getByNumber(number);
    }

    @Override
    public Integer getStatus(String deviceId) {
        //访问接口直接查询状态
        Integer status = deviceSetUpService.status(deviceId);
        //查询设备状态
//        WatchDeviceStatus status = watchDeviceStatusService.getLastByDeviceId(deviceId);
//        if (status != null) {
//            switch (status.getStatus()) {
//                case "offline":
//                    return 0;
//                case "online":
//                    return 1;
//                case "unactive":
//                    return 2;
//                case "disable":
//                    return 3;
//                case "not exist":
//                    return 4;
//                default:
//                    return -1;
//            }
//        }
        return status;
    }


    /**
     * 批量删除设备信息
     *
     * @param deviceIds 需要删除的设备信息主键
     * @return 结果
     */
    @Override
    public int deleteDeviceInfoByDeviceIds(Long[] deviceIds) {
        int result = mapper.deleteDeviceInfoByDeviceIds(deviceIds);
//        if (result > 0) {
//            for (int i = 0; i < deviceIds.length; i++) {
//                WatchDeviceInfoVo deviceInfoVo = selectDeviceInfoByDeviceId(deviceIds[i]);
//                if (deviceInfoVo != null && deviceInfoVo.getCompanyId() != null) {
//                    Company company = companyService.selectCompanyByCompanyId(deviceInfoVo.getCompanyId());
//                    if (company != null) {
//                        String pushUrl = company.getPushUrl();
//                        if (StringUtils.isNotBlank(pushUrl)) {
//                            //推送mysql设备基础信息 device_info给相关公司
////                            Map delResult = httpUtils.getDel(pushUrl + "/app/watch/delWatchDevice?deviceNums=" + deviceIds[i]);
//                            Map delResult = httpUtils.getDel(pushUrl + "/watchDeviceInfo/remove?deviceNums=" + deviceIds[i]);
//                            if (delResult != null) {
//                                int code = (int) delResult.get("code");
//                                if (code != 200) {
//                                    //redis缓存 12:00定时重新新增
//                                    redisCache.setCacheObject("errorDelDevice:" + deviceInfoVo.getDeviceNumber(), deviceInfoVo);
//                                }
//                            }
//                        }
//                    }
//                }
//            }
//        }
        return result;
    }
}
