package com.mortals.xhx.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.mortals.framework.util.HttpUtil;
import com.mortals.xhx.busiz.rsp.ApiResp;
import com.mortals.xhx.busiz.rsp.DeviceResp;
import com.mortals.xhx.common.code.DeviceOnlineStatusEnum;
import com.mortals.xhx.daemon.task.CustomerInfo;
import com.mortals.xhx.module.device.model.DeviceEntity;
import com.mortals.xhx.module.device.service.DeviceService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.mortals.framework.util.HttpUtil.HEADER_CONTENT_TYPE;

/**
 * 发送任务
 *
 * @author: zxfei
 * @date: 2022/4/28 10:56
 * @description:
 **/
@Slf4j
@AllArgsConstructor
public class SendTask implements Runnable {
    private String sendUrl;
    private Long deviceId;
    private String content;
    private DeviceService deviceService;

    @Override
    public void run() {
        try {
            Map<String, String> headers = new HashMap<>();
            DeviceEntity deviceEntity = new DeviceEntity();
            deviceEntity.setId(deviceId);
            headers.put(HEADER_CONTENT_TYPE, "application/json");

            log.info("\n sendUrl:{} \n sendContent:{}", sendUrl,content);
            String resp = HttpUtil.doPost(sendUrl, headers, content);
            ApiResp<DeviceResp> apiResp = JSON.parseObject(resp, new TypeReference<ApiResp<DeviceResp>>(){});
            if (apiResp.getCode() == 0) {
                if (apiResp.getData().getIsOnLine() == "0") {
                    deviceEntity.setDeviceOnlineStatus(DeviceOnlineStatusEnum.在线.getValue());
                    deviceEntity.setOnlineTime(new Date());
                } else if (apiResp.getData().getIsOnLine() == "1") {
                    deviceEntity.setDeviceOnlineStatus(DeviceOnlineStatusEnum.离线.getValue());
                    deviceEntity.setOfflineTime(new Date());
                } else {
                    deviceEntity.setDeviceOnlineStatus(DeviceOnlineStatusEnum.在线.getValue());
                    deviceEntity.setOnlineTime(new Date());
                }
                deviceService.update(deviceEntity);
            }
            log.info("http resp:{}", resp);
        } catch (Exception e) {
            log.error("发送异常：" + e);
        }
    }
}
