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.ShipLockWaterLevel;
import com.shcd.entity.ShipRunInfo;
import com.shcd.mapper.ShipLockWaterLevelMapper;
import com.shcd.service.ShipLockWaterLevelService;
import com.shcd.service.ShipRunInfoService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.log.XxlJobLogger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 *
 */
@Service
@Transactional
public class ShipLockWaterLevelServiceImpl extends ServiceImpl<ShipLockWaterLevelMapper, ShipLockWaterLevel> implements ShipLockWaterLevelService{
    @Autowired
    private ShipRunInfoService shipRunInfoService;
    @Value("${shipLockWaterLevelUrl}")
    private String shipLockWaterLevelUrl;
    @Value("${shipLockSecretId}")
    private String shipLockSecretId;
    @Value("${shipLockSecretKey}")
    private String shipLockSecretKey;
    @Override
    public ReturnT<String> saveWaterLevel() {
        try {
            HttpResponse execute = HttpUtil.createGet(shipLockWaterLevelUrl).
                    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"))){
                HashMap hashMap1 = JSONObject.parseObject(hashMap.get("data").toString(), HashMap.class);
                List<ShipRunInfo> shipRunInfos = JSONObject.parseArray(hashMap1.get("shipRunInfos").toString(), ShipRunInfo.class);
                shipRunInfos.forEach(i->i.setDateTime(i.getDate()));
                ShipLockWaterLevel data = JSONObject.parseObject(hashMap.get("data").toString(), ShipLockWaterLevel.class);
                data.setDateTime(data.getDate());
                this.saveOrUpdate(data);
                try {
                    shipRunInfoService.saveOrUpdateBatch(shipRunInfos);
                } catch (Exception e) {
                    XxlJobLogger.log(e.getMessage());
                }
                return ReturnT.SUCCESS;
            }
        } catch (HttpException e) {
            XxlJobLogger.log(e.getCause() + " ------ " + e.getMessage());
            return ReturnT.FAIL;
        }
        return ReturnT.FAIL;
    }
}




