package com.shcd.service.impl;

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.ShipIllegalArtificial;
import com.shcd.entity.ShipIllegalAuto;
import com.shcd.service.ShipIllegalArtificialService;
import com.shcd.service.ShipIllegalAutoService;
import com.shcd.mapper.ShipIllegalAutoMapper;
import com.xxl.job.core.biz.model.ReturnT;
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 ShipIllegalAutoServiceImpl extends ServiceImpl<ShipIllegalAutoMapper, ShipIllegalAuto> implements ShipIllegalAutoService {
    @Value("${illegalInfoUrl}")
    private String illegalInfoUrl;
    @Value("${infoSecretId}")
    private String infoSecretId;
    @Value("${infoSecretKey}")
    private String infoSecretKey;
    @Autowired
    private ShipIllegalArtificialService shipIllegalArtificialService;

    @Override
    public ReturnT<String> saveShipIllegalInfo() {
        try {
            Date date = new Date();
            String end = DateUtils.dateToString(date, "yyyy-MM-dd HH:mm");
            String start = DateUtils.dateToString(new Date(date.getTime() - 5 * 60 * 1000), "yyyy-MM-dd HH:mm");
            HttpResponse execute = HttpUtil.createGet(illegalInfoUrl + "start=" + start + "&end=" + end).
                    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 hashMap1 = JSONObject.parseObject(hashMap.get("data").toString(), HashMap.class);
                List<ShipIllegalAuto> auto = JSONObject.parseArray(hashMap1.get("auto").toString(), ShipIllegalAuto.class);
                List<ShipIllegalArtificial> artificial = JSONObject.parseArray(hashMap1.get("handle").toString(), ShipIllegalArtificial.class);
                if (!auto.isEmpty()) {
                    auto.forEach(i->i.setIndext(i.getIndex()));
                    this.saveOrUpdateBatch(auto);
                }
                if (!artificial.isEmpty()) {
                    artificial.forEach(i->i.setIndext(i.getIndex()));
                    shipIllegalArtificialService.saveOrUpdateBatch(artificial);
                }
            }
            return ReturnT.FAIL;
        } catch (Exception e) {
            return ReturnT.FAIL;
        }
    }
}




