package cn.iocoder.yudao.module.system.service.biz;

import cn.hutool.core.bean.BeanUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.date.DateUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.system.dal.dataobject.biz.DeviceProductDO;
import cn.iocoder.yudao.module.system.dal.dataobject.biz.DeviceWarnDO;
import cn.iocoder.yudao.module.system.dal.dataobject.biz.ModelFieldDO;
import cn.iocoder.yudao.module.system.dal.dataobject.biz.SleepReportDO;
import cn.iocoder.yudao.module.system.dal.mysql.biz.DeviceWarnMapper;
import cn.iocoder.yudao.module.system.dal.mysql.biz.ModelFieldMapper;
import cn.iocoder.yudao.module.system.dal.mysql.biz.SleepthingMapper;
import cn.iocoder.yudao.module.system.enums.device.DeviceModelTypeEnum;
import cn.iocoder.yudao.module.system.enums.notice.NotieBusinessTypeEnum;
import cn.iocoder.yudao.module.system.enums.notice.NotifyPriorityEnum;
import cn.iocoder.yudao.module.system.enums.notice.NotifyTypeEnum;
import cn.iocoder.yudao.module.system.service.notify.NotifyMessageService;
import cn.iocoder.yudao.module.system.service.notify.NotifySendService;
import cn.iocoder.yudao.module.system.util.device.SleepHttpSend;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.iocoder.yudao.framework.common.util.date.DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND;
import static cn.iocoder.yudao.module.system.enums.device.SleepthingApiConstants.*;

/**
 * @Author: jinyd
 * @CreateTime: 2024/10/21  14:11
 * @Description:
 * @Version: 4.0
 */


@Slf4j
@Service
@Validated
public class SleepthingServiceImpl implements SleepthingService{

    @Resource
    private ModelFieldMapper modelFieldMapper;


    @Resource
    private SleepthingMapper sleepthingMapper;

    @Resource
    private DeviceProductService deviceProductService;

    @Resource
    private DeviceWarnMapper deviceWarnMapper;

    @Resource
    private NotifySendService notifySendService;


    /**
     * 获取设备电量
     *
     * @param paramMap
     * @return
     */
    @Override
    public JSONObject getDevicePower(HashMap<String, Object> paramMap) {
        return SleepHttpSend.execute(paramMap, GET_DEVICE_POWER_URL, "get");
    }

    /**
     * 获取设备信息
     *
     * @param paramMap
     * @return
     */
    @Override
    public JSONObject getDeviceInfo(HashMap<String, Object> paramMap) {
        return SleepHttpSend.doGet(API_REQUEST_URL + GET_DEVICE_INFO_URL, paramMap);
    }

    /**
     * 获取实时数据
     *
     * @param paramMap
     * @return
     */
    @Override
    public JSONObject getRealTimeData(HashMap<String, Object> paramMap) {
        return SleepHttpSend.doGet(API_REQUEST_URL + GET_REAL_TIME_DATA_URL, paramMap);
    }

    /**
     * 命令设备停止发送实时数据
     *
     * @param paramMap
     * @return
     */
    @Override
    public JSONObject stopSendRealTimeData(HashMap<String, Object> paramMap) {
        return SleepHttpSend.doPost(API_REQUEST_URL + STOP_SEND_REAL_TIME_DATA_URL, paramMap);
    }

    /**
     * 命令设备发送实时数据上来
     *
     * @param paramMap
     * @return
     */
    @Override
    public JSONObject sendRealTimeData(HashMap<String, Object> paramMap) {
        return SleepHttpSend.doPost(API_REQUEST_URL + SEND_REAL_TIME_DATA_URL, paramMap);
    }

    /**
     * 获取设备联网状态
     *
     * @param paramMap
     * @return
     */
    @Override
    public JSONObject getDeviceNetworkState(HashMap<String, Object> paramMap) {
        return SleepHttpSend.doPost(API_REQUEST_URL + GET_DEVICE_NETWORK_STATE_URL, paramMap);
    }

    /**
     * 验证设备是否合法
     *
     * @param paramMap
     * @return
     */
    @Override
    public JSONObject isThisDeviceValid(HashMap<String, Object> paramMap) {
        return SleepHttpSend.doPost(API_REQUEST_URL + IS_THIS_DEVICE_VALID_URL, paramMap);
    }

    /**
     * 获取睡眠报告完整数据
     *
     * @param paramMap
     * @return
     */
    @Override
    public JSONObject getDaySleepReport(HashMap<String, Object> paramMap) {
        return SleepHttpSend.doGet(API_REQUEST_URL + GET_DAY_SLEEP_REPORT_URL, paramMap);
    }

    /**
     * 绑定用户身体信息
     *
     * @param paramMap
     * @return
     */
    @Override
    public JSONObject bindUserBodyInfo(HashMap<String, Object> paramMap) {
        if (paramMap.get("birthday") == null) {
            paramMap.put("birthday", "1987-01-25");
        }
        if (paramMap.get("gender") == null) {
            paramMap.put("gender", "男");
        }
        if (paramMap.get("height") == null) {
            paramMap.put("height", 170);
        }
        if (paramMap.get("weight") == null) {
            paramMap.put("weight", 64);
        }
        return SleepHttpSend.doPost(API_REQUEST_URL + BIND_USER_BODY_INFO_URL, paramMap);
    }

    @Override
    public JSONObject bindUserBodyInfoOld(HashMap<String, Object> paramMap) {
        if (paramMap.get("birthday") == null) {
            paramMap.put("birthday", "1987-01-25");
        }
        if (paramMap.get("gender") == null) {
            paramMap.put("gender", "男");
        }
        if (paramMap.get("height") == null) {
            paramMap.put("height", 170);
        }
        if (paramMap.get("weight") == null) {
            paramMap.put("weight", 64);
        }
        String method = "/user/bindUserBodyInfo";
        return SleepHttpSend.execute(paramMap, method, "post");
    }

    @Override
    public JSONObject unbind(HashMap<String, Object> paramMap) {
        JSONObject jsonObject = SleepHttpSend.doGet(API_REQUEST_URL + DEVICE_UNBIND_URL, paramMap);
        return jsonObject;
    }

    @Override
    public JSONObject unbindOld(HashMap<String, Object> paramMap) {
        return null;
    }

    /**
     * 异常报警设置
     *
     * @param paramMap
     * @return
     */
    @Override
    public JSONObject setAlarmLevel(HashMap<String, Object> paramMap) {
        return SleepHttpSend.execute(paramMap, SET_ALARM_LEVEL_URL, "post");
    }

    /**
     * 获取报警等级
     *
     * @param paramMap
     * @return
     */
    @Override
    public JSONObject getAlarmLevel(HashMap<String, Object> paramMap) {
        return SleepHttpSend.execute(paramMap, GET_ALARM_LEVEL_URL, "get");
    }

    /**
     * 睡眠事件通知设置
     *
     * @param paramMap
     * @return
     */
    @Override
    public JSONObject setEventNotify(HashMap<String, Object> paramMap) {
        return SleepHttpSend.doPost(API_REQUEST_URL + SET_EVENT_NOTIFY_URL, paramMap);
    }

    /**
     * 获取事件通知列表
     *
     * @param paramMap
     * @return
     */
    @Override
    public JSONObject getEventNotifyList(HashMap<String, Object> paramMap) {
        return SleepHttpSend.doGet(API_REQUEST_URL + GET_EVENT_NOTIFY_LIST_URL, paramMap);
    }

    /**
     * 设置睡眠报告通知接收地址
     *
     * @param paramMap
     * @return
     */
    @Override
    public JSONObject setReportNotifyUrl(HashMap<String, Object> paramMap) {
        return SleepHttpSend.doPost(API_REQUEST_URL + SET_REPORT_NOTIFY_URL, paramMap);
    }

    /**
     * 设置异常报警通知接收地址
     *
     * @param paramMap
     * @return
     */
    @Override
    public JSONObject setAlarmNotifyUrl(HashMap<String, Object> paramMap) {
        return SleepHttpSend.doPost(API_REQUEST_URL + SET_ALARM_NOTIFY_URL, paramMap);
    }

    /**
     * 设置睡眠事件通知接收地址
     *
     * @param paramMap
     * @return
     */
    @Override
    public JSONObject setEventNotifyUrl(HashMap<String, Object> paramMap) {
        return SleepHttpSend.execute(paramMap, SET_EVENT_NOTIFY_URL_URL, "post");
    }

    @Override
    public CommonResult generateSleepReport(HashMap<String, Object> params) {
        JSONObject resp = getDaySleepReport(params);
        log.info("睡小宝睡眠报告数据,{}", resp);
        if (resp.getInteger("code")==0) {
            JSONObject resp2 = resp.getJSONObject("data");
            String tableName = "";
            List<ModelFieldDO> modelFieldDOList = modelFieldMapper.selectList(new LambdaQueryWrapperX<ModelFieldDO>()
                    .eq(ModelFieldDO::getModelType, DeviceModelTypeEnum.SLEEP.getType()));
            Map<String, Object> map = new HashMap<>();
            for (int i = 0; i < modelFieldDOList.size(); i++) {
                ModelFieldDO modelFieldDO = modelFieldDOList.get(i);
                tableName = modelFieldDO.getTableName();
                Object object = resp2.get(modelFieldDO.getColumnName());
                if (null != object) {
                    String temp = StringUtils.join(StringUtils.splitByCharacterTypeCamelCase(modelFieldDO.getOriginalColumnName()), ' ');
                    map.put(StringUtils.uncapitalize(temp.replaceAll("_", "")), object);
                }
            }

            // TODO 补全数据
//            DeviceProduct2 where = new DeviceProduct2();
//            where.setDeviceMac(resp2.getString("devID"));
//            List<DeviceProduct2> list = deviceProductService.list(where);
//            if (list.size() > 0) {
//                entity.setOrgId(list.get(0).getChannelId());
//                Long bedId = list.get(0).getBedId();
//                if (bedId != null && bedId > 0) {
//                    QueryDomain where2 = new QueryDomain();
//                    where2.getParams().put("orgId", entity.getOrgId());
//                    where2.getParams().put("bedId", bedId);
//                    PageBean list2 = elderlyInfoService.getByPage(where2);
//                    if (list2.getData().size() > 0) {
//                        List<ElderlyInfo> elderlyInfos = list2.getData();
//                        entity.setElderId(elderlyInfos.get(0).getId().toString());
//                        entity.setElderName(elderlyInfos.get(0).getElderName());
//                    }
//                } else {
//                    entity.setElderId(list.get(0).getTestUserId());
//                    entity.setElderName(list.get(0).getTestUserName());
//                }
//            }

            // Map转实体类
            SleepReportDO sleepReportDO = BeanUtil.toBean(map, SleepReportDO.class);
            sleepthingMapper.insert(sleepReportDO);
        }
        return CommonResult.success("");
    }

    @Override
    public void alarmNotify(HashMap<String, Object> params) {
        log.info("睡小宝接收到报警数据,{}", params);
        // TODO 睡小宝异常日志
        DeviceProductDO deviceProduct = deviceProductService.getByDeviceMac(params.get("devID").toString());
        if (deviceProduct != null) {
            DeviceWarnDO deviceWarnDO = new DeviceWarnDO();
            deviceWarnDO.setDeviceMac(params.get("devID").toString());
            deviceWarnDO.setTenantId(deviceProduct.getTenantId());
//            deviceWarnDO.setWarnTime(DateUtils.asLocalDateTime(DateUtils.dateTime(FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND, params.get("time").toString())));
            deviceWarnDO.setStatus(1);      //日志级别
            deviceWarnDO.setAlarmType(10);  //日志类型，睡眠日志
            String event = (String) params.get("event");
            deviceWarnDO.setWarnParam(event);
            switch (event) {
                case "HR_low":
                    deviceWarnDO.setRemark("心动过缓");
                    deviceWarnDO.setLogType(1);
                    break;
                case "HR_high":
                    deviceWarnDO.setRemark("心动过速");
                    deviceWarnDO.setLogType(1);
                    break;
                case "BR_low":
                    deviceWarnDO.setRemark("呼吸过缓");
                    deviceWarnDO.setLogType(1);
                    break;
                case "BR_high":
                    deviceWarnDO.setRemark("呼吸过速");
                    deviceWarnDO.setLogType(1);
                    break;
                case "outbed":
                    deviceWarnDO.setRemark("离床过久");
                    deviceWarnDO.setLogType(2);
                    break;
            }
            deviceWarnMapper.insert(deviceWarnDO);
            // todo 告警信息,查询产品告警人长者，工作人员
            // 告警信息接收人
            Map<String, Object> templateParams = new HashMap<>();
            notifySendService.sendSingleNotifyToAdmin(1l, deviceWarnDO.getId().toString(), "", "",
                    "device_warn", templateParams, NotieBusinessTypeEnum.ALARM.getValue(), NotifyTypeEnum.NOTIFY_TODO.getValue(),
                    NotifyPriorityEnum.HIGH.getValue(), 0, deviceProduct.getTenantId());
            //notifySendService.sendSingleNotifyToAdmin();

        }
    }

    public static void main(String[] args) {
     /*   SleepXiaobaoManager aaa = new SleepXiaobaoManagerImpl();
        HashMap<String, Object> paramMap = Maps.newHashMap();
        paramMap.put("devID","40F5200F8B1F");
        //paramMap.put("day","2021-07-07");
        aaa.getDaySleepReport(paramMap);
        //aaa.getAlarmLevel(paramMap);
        //paramMap.put("alarmLevel","3");
        //paramMap.put("getInbed",1);
        //aaa.setEventNotify(paramMap);

        aaa.getEventNotifyList(paramMap);*/

        /*paramMap.put("alarmNotifyUrl", "http://1753162t3p.iok.la/api/sleep/alarmNotify");
        aaa.setAlarmNotifyUrl(paramMap);*/

      /* paramMap.put("reportNotifyUrl","http://1753162t3p.iok.la/api/sleep/reportIsReady");
        aaa.setReportNotifyUrl(paramMap);*/

        /*paramMap.put("eventNotifyUrl","http://1753162t3p.iok.la/api/sleep/eventNotify");
        aaa.setEventNotifyUrl(paramMap);*/

    }

}
