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.shanghaigeography.Util.DateUtils;
import com.shcd.entity.ShipLockStatistic;
import com.shcd.entity.ShipLockStatisticDetail;
import com.shcd.mapper.ShipLockStatisticMapper;
import com.shcd.service.ShipLockStatisticDetailService;
import com.shcd.service.ShipLockStatisticService;
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.Date;
import java.util.HashMap;
import java.util.List;

/**
 *
 */
@Service
@Transactional
public class ShipLockStatisticServiceImpl extends ServiceImpl<ShipLockStatisticMapper, ShipLockStatistic> implements ShipLockStatisticService {
    @Autowired
    private ShipLockStatisticDetailService shipLockStatisticDetailService;
    @Value("${lockStaticUrl}")
    private String lockStaticUrl;
    @Value("${infoSecretId}")
    private String infoSecretId;
    @Value("${infoSecretKey}")
    private String infoSecretKey;
    @Override
    public ReturnT<String> saveShipStatisticInfo() {
        try {
            String date = DateUtils.dateToString(new Date(), "yyyy-MM-dd");
            HttpResponse execute = HttpUtil.createGet(lockStaticUrl + "date=" + date).
                    header("secretId", infoSecretId).
                    header("secretKey", infoSecretKey).execute();
            execute.close();
            HashMap hashMap = JSONObject.parseObject(execute.body(), HashMap.class);
            if (new Integer(0).equals(hashMap.get("code"))){
                HashMap data = JSONObject.parseObject(hashMap.get("data").toString(), HashMap.class);
                ShipLockStatistic shipLockShipStatus = JSONObject.parseObject(hashMap.get("data").toString(), ShipLockStatistic.class);
                List<ShipLockStatisticDetail> details = JSONObject.parseArray(data.get("details").toString(), ShipLockStatisticDetail.class);
                this.saveOrUpdate(shipLockShipStatus);
                shipLockStatisticDetailService.saveOrUpdateBatch(details);
            }
            return ReturnT.FAIL;
        } catch (HttpException e) {
            XxlJobLogger.log(e.getCause() + "----" + e.getMessage());
            return ReturnT.FAIL;
        }
    }
}




