package org.dromara.elevator.job;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.json.utils.JsonUtils;
import org.dromara.elevator.domain.EBlackBoxInfo;
import org.dromara.elevator.domain.EVidiconInfo;
import org.dromara.elevator.domain.message.AuthToken;
import org.dromara.elevator.mapper.EBlackBoxInfoMapper;
import org.dromara.elevator.mapper.EVidiconInfoMapper;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 同步黑匣子状态
 * @author zy
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class SyncDeviceStateJob {

    private final EBlackBoxInfoMapper blackBoxInfoMapper;
    private final EVidiconInfoMapper vidiconInfoMapper;
    private static final String CLIENT_ID = "4861fee8e89d4d638be4041ae6f97970";
    private static final String CLIENT_SECRET = "3c0174def53a44008395f91f232bb579";
    private static final String URL_TOKEN = "https://ele.secp.com.cn/oauth/tooken.do";
    private static final String URL_DATA = "https://ele.secp.com.cn/v5.0/api/getDevList.do";

    /**
     * 同步黑匣子在线状态
     */
    @Scheduled(cron = "0 0 0/1 * * ?")
    public void syncBlackBoxStateJob() {
        try {
            log.info("开始同步黑匣子在线状态！");
            // 获取token
            Map<String, Object> params = new HashMap<>();
            params.put("clientId", CLIENT_ID);
            params.put("clientSecret", CLIENT_SECRET);
            String res = HttpUtil.get(URL_TOKEN, params);
            AuthToken authToken = JsonUtils.parseObject(res, AuthToken.class);
            String token = authToken.getObj().getAccessToken();

            // 获取数据
            Map<String, Object> stateMap = new HashMap<>();
            stateMap.put("page", 1);
            stateMap.put("size", 100);
            String result = HttpRequest.post(URL_DATA).header("api-key", token).form(stateMap).timeout(10000)
                .execute().body();

            // 解析数据
            JSONObject jsonObject = JSONUtil.parseObj(result);
            JSONObject obj = (JSONObject) jsonObject.get("obj");
            JSONArray array = obj.getJSONArray("rows");

            List<EBlackBoxInfo> blackBoxList = blackBoxInfoMapper.selectList();
            List<EVidiconInfo> vidiconList = vidiconInfoMapper.selectList();
            for (Object object : array) {
                JSONObject row = (JSONObject) object;
                String code = row.getStr("code");
                String registerCode = row.getStr("registerCode");

                // 设置黑匣子状态
                for (EBlackBoxInfo blackBox : blackBoxList) {
                    if (code.equals(blackBox.getDeviceCode())) {
                        blackBox.setFinallyTime(row.getDate("devLastStautsTime"));
                        if (2 == row.getInt("status")) {
                            blackBox.setIsLine(1);
                            blackBox.setOfflineTime("");
                        } else if (1 == row.getInt("status")) {
                            blackBox.setIsLine(0);
                            LocalDateTime offLine = row.getDate("devLastStautsTime").toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
                            Duration duration = Duration.between(offLine, LocalDateTime.now());
                            long days = duration.toDays();
                            long hours = duration.toHours() % 24;

                            blackBox.setOfflineTime(days+"天"+hours+"小时");
                        } else {
                            blackBox.setIsLine(2);
                        }
                        break;
                    }
                }
                // 设置网络摄像机状态
                for (EVidiconInfo vidicon : vidiconList) {
                    if (registerCode.equals(vidicon.getRegisterCode())) {
                        vidicon.setFinallyTime(row.getDate("devLastStautsTime"));
                        if (2 == row.getInt("status")) {
                            vidicon.setIsLine(1);
                            vidicon.setOfflineTime("");
                        } else if (1 == row.getInt("status")) {
                            vidicon.setIsLine(0);
                            LocalDateTime offLine = row.getDate("devLastStautsTime").toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
                            Duration duration = Duration.between(offLine, LocalDateTime.now());
                            long days = duration.toDays();
                            long hours = duration.toHours() % 24;

                            vidicon.setOfflineTime(days+"天"+hours+"小时");
                        } else {
                            vidicon.setIsLine(2);
                        }
                        break;
                    }
                }
            }
            blackBoxInfoMapper.updateBatchById(blackBoxList);
            vidiconInfoMapper.updateBatchById(vidiconList);
            log.info("同步黑匣子在线状态完成！");
        } catch (Exception e) {
            log.error("同步黑匣子在线状态失败！");
        }
    }

}
