package com.fs.watch.service.impl;

import com.fs.common.utils.DateUtils;
import com.fs.common.utils.StringUtils;
import com.fs.his.domain.FsThirdDeviceData;
import com.fs.his.mapper.FsThirdDeviceDataMapper;
import com.fs.watch.domain.WatchBloodGlucoseData;
import com.fs.watch.domain.WatchDeviceInfo;
import com.fs.watch.enums.WatchBgStatusEnum;
import com.fs.watch.mapper.WatchBloodGlucoseDataMapper;
import com.fs.watch.mapper.WatchDeviceInfoMapper;
import com.fs.watch.service.WatchBloodGlucoseDataService;
import com.fs.watch.service.WatchThirdBpDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
* @author Administrator
* @description 针对表【watch_blood_glucose_data(血糖数据)】的数据库操作Service实现
* @createDate 2024-10-15 11:06:50
*/
@Service
@Slf4j
public class WatchBloodGlucoseDataServiceImpl implements WatchBloodGlucoseDataService {
    @Autowired
    private WatchBloodGlucoseDataMapper mapper;

    @Autowired
    private WatchThirdBpDataService watchThirdBpDataService;
    @Autowired
    private WatchDeviceInfoMapper watchDeviceInfoMapper;
    @Autowired
    private FsThirdDeviceDataMapper fsThirdDeviceDataMapper;


    @Override
    public Boolean insert(WatchBloodGlucoseData watchBloodGlucoseData) {
        try {
            mapper.insert(watchBloodGlucoseData);
        } catch (Exception e) {
            log.error("===============watchBloodGlucoseData:insert=========================={}", e.getMessage());
            return false;
        }
        //修改设备健康状态
        WatchDeviceInfo info = new WatchDeviceInfo();
        info.setDeviceNumber(watchBloodGlucoseData.getDeviceId());
        if (watchBloodGlucoseData.getStatus() != null){
            if (!Objects.equals(watchBloodGlucoseData.getStatus(), WatchBgStatusEnum.NORMAL.getValue())) {

                info.setIsNormal(0);
            } else {
                info.setIsNormal(1);
            }
            watchDeviceInfoMapper.updateByDeviceNumber(info);
        }

        return true;
    }

    private Map<String, Object> getBloodGlucoseDataMap(WatchBloodGlucoseData watchBloodGlucoseData) {
        Map<String, Object> params = new HashMap<>();
        params.put("id", watchBloodGlucoseData.getId().toString());
        params.put("deviceId", watchBloodGlucoseData.getDeviceId());
        params.put("bloodGlucose", watchBloodGlucoseData.getBloodGlucose());
        params.put("status", watchBloodGlucoseData.getStatus());
        params.put("createTime", watchBloodGlucoseData.getCreateTime());
        return params;
    }

    @Override
    public List<WatchBloodGlucoseData> queryByDateAndDeviceId(String date, String deviceId) {
        if (StringUtils.isBlank(date)) {
            date = DateUtils.dateTimeNow("yyyy-MM-dd");
        }
        return mapper.queryByDateAndDeviceId(date, deviceId);
    }

    @Override
    public List<WatchBloodGlucoseData> queryBgByDate(Date startTime, Date endTime, String deviceId, Integer status,Integer deviceType) {
        if (StringUtils.isNotBlank(deviceId)) {
            if (deviceType == null || deviceType == 0) {
                return mapper.queryBgByDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, startTime),
                        DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, endTime),
                        deviceId,
                        status);
            } else {
                List<FsThirdDeviceData> list = fsThirdDeviceDataMapper.selectListByDateAndDeviceIdAndRecordType(startTime, endTime, deviceId, 1, status);
                if (list != null && !list.isEmpty()) {
                    List<WatchBloodGlucoseData> voList= new ArrayList<>();
                    list.forEach(fsThirdDeviceData -> {
                        WatchBloodGlucoseData data = new WatchBloodGlucoseData();
                        data.setDeviceId(fsThirdDeviceData.getDeviceId());
                        String recordValue = fsThirdDeviceData.getRecordValue();
                        if (recordValue != null) {
                            // 移除所有双引号
                            recordValue = recordValue.replace("\"", "");
                            // 或者只移除首尾的引号和可能的空格
                            recordValue = recordValue.replaceAll("^[\"']+|[\"']+$", "");
                        }
                        data.setBloodGlucose(Float.valueOf(recordValue));
                        data.setCreateTime(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",fsThirdDeviceData.getCreateTime()));
                        data.setStatus(fsThirdDeviceData.getStatus());
                        voList.add(data);
                    });
                    return voList;
                }
            }

        }
        return null;
    }


    @Override
    public List<Map<String, Object>> countBgByDate(Date startTime, Date endTime, String deviceId,Integer deviceType) {
        if (StringUtils.isBlank(deviceId)) {
            return null;
        }
        //返回对象
        List<Map<String, Object>> res = null;
        if (deviceType == null || deviceType == 0) {
            res = mapper.countBpByDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, startTime),
                    DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, endTime), deviceId);
        } else {
            res = fsThirdDeviceDataMapper.countByDateAndDeviceIdAndRecordType(startTime, endTime, deviceId, 1,null);
        }



        return res;
    }

    @Override
    public WatchBloodGlucoseData getLatest(String deviceId) {
        return mapper.getLatest(deviceId);
    }

    @Override
    public int countBgPageByDate(Date startTime, Date endTime, String deviceId, Integer status,Integer deviceType) {
        if (deviceType == null || deviceType == 0) {
            return mapper.countBgPageByDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, startTime),
                    DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, endTime),
                    deviceId, status);
        } else {
            return fsThirdDeviceDataMapper.countPageByDateAndDeviceIdAndRecordType(startTime,endTime,deviceId,1,status);
        }

    }

    @Override
    public List<WatchBloodGlucoseData> queryBgPageByDate(Date startTime, Date endTime, String deviceId, Integer status, Integer num, Integer size,Integer deviceType) {
        if (deviceType == null || deviceType == 0) {
            if (StringUtils.isNotBlank(deviceId)) {
                return mapper.queryBgPageByDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, startTime),
                        DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, endTime),
                        deviceId, status, num, size);
            } else {
                return null;
            }
        } else {
            List<WatchBloodGlucoseData> voList= new ArrayList<>();
            List<FsThirdDeviceData> list = fsThirdDeviceDataMapper.queryPageByDateAndDeviceIdAndRecordType(startTime, endTime, deviceId, 1,status, num, size);
            if (list != null && !list.isEmpty()) {
                list.forEach(fsThirdDeviceData -> {
                    WatchBloodGlucoseData data = new WatchBloodGlucoseData();
                    data.setDeviceId(fsThirdDeviceData.getDeviceId());
                    String recordValue = fsThirdDeviceData.getRecordValue();
                    if (recordValue != null) {
                        // 移除所有双引号
                        recordValue = recordValue.replace("\"", "");
                        // 或者只移除首尾的引号和可能的空格
                        recordValue = recordValue.replaceAll("^[\"']+|[\"']+$", "");
                    }
                    data.setBloodGlucose(Float.valueOf(recordValue));
                    data.setCreateTime(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",fsThirdDeviceData.getCreateTime()));
                    data.setStatus(fsThirdDeviceData.getStatus());
                    voList.add(data);
                });

            }
            return voList;
        }

    }

    /**
     * 高风险：血糖值大于等于 7.0 mmol/L，返回 1。
     * 一般：血糖值在 6.0 mmol/L 和 7.0 mmol/L 之间，返回 3。
     * 良好：血糖值在 5.0 mmol/L 和 6.0 mmol/L 之间，返回 4。
     * 正常：血糖值在 3.9 mmol/L和 4.0 mmol/L 之间，，返回 5。
     * 不良：血糖值小于 3.9 mmol/L 之间，返回 2。
     * 获得血糖状态
     *
     * @param num
     * @return 状态码
     */
    @Override
    public Integer getStatus(Double num) {
        if (num >= 7.0) {
            return WatchBgStatusEnum.HYPERGLYCEMIA.getValue(); // 高风险(糖尿病)
        } else if (num >= 6.1) {
            return WatchBgStatusEnum.HIGHER.getValue(); // 一般(糖尿病前期)
        } else if (num >= 3.9) {
            return WatchBgStatusEnum.NORMAL.getValue(); // 良好正常
        } else {
            return WatchBgStatusEnum.HYPOGLYCEMIA.getValue(); //不良 (低血糖)
        }
    }

}
