package com.shcd.service.impl;

import cn.hutool.http.HttpException;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shcd.entity.ShipLockDoorStatusRealtime;
import com.shcd.service.ShipLockDoorStatusRealtimeService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.shcd.mapper.ShipLockDoorStatusRealtimeMapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;

/**
 *
 */
@Service
@Transactional
public class ShipLockDoorStatusRealtimeServiceImpl extends ServiceImpl<ShipLockDoorStatusRealtimeMapper, ShipLockDoorStatusRealtime> implements ShipLockDoorStatusRealtimeService {
    @Value("${shipLockDoorStatusUrl}")
    private String shipLockDoorStatusUrl;
    @Value("${shipLockSecretId}")
    private String shipLockSecretId;
    @Value("${shipLockSecretKey}")
    private String shipLockSecretKey;

    @Override
    public ReturnT<String> saveDoorStatus() {
        try {
            HttpResponse execute = HttpUtil.createGet(shipLockDoorStatusUrl).
                    header("secretId", shipLockSecretId).
                    header("secretKey", shipLockSecretKey).execute();
            execute.close();
            HashMap hashMap = JSONObject.parseObject(execute.body(), HashMap.class);
            if (new Integer(0).equals(hashMap.get("code"))) {
                List<ShipLockDoorStatusRealtime> data = JSONObject.parseArray(hashMap.get("data").toString(), ShipLockDoorStatusRealtime.class);
                data.forEach(i -> i.setDates(i.getDate()));
                boolean b = this.saveOrUpdateBatch(data);
                if (b) {
                    return ReturnT.SUCCESS;
                } else {
                    return ReturnT.FAIL;
                }
            }
            return ReturnT.FAIL;
        } catch (HttpException e) {
            XxlJobLogger.log(e.getCause() + "-----" + e.getMessage());
            return ReturnT.FAIL;
        }
    }
}
