package com.sky.ioc.service.parking.impl;

import com.sky.ioc.config.RestTemplateConfig;
import com.sky.ioc.entity.domain.parking.IllegalParking;
import com.sky.ioc.mapper.IllegalParkingMapper;
import com.sky.ioc.service.parking.IllegalParkingService;
import com.sky.ioc.tool.ReturnMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;

@Service
@Slf4j
public class IllegalParkingServiceImpl implements IllegalParkingService {


    @Autowired
    RestTemplateConfig restTemplateConfig;

    @Autowired
    IllegalParkingMapper illegalParkingMapper;

    final static  String ILLEGAL_PARKING_URL="/api/parking/PARKING/illegalParking/list";
    @Override
    public ReturnMsg getIllegalParkingData() {
        String url = restTemplateConfig.addBaseUrl(ILLEGAL_PARKING_URL)+"?pageNum=1&pageSize=1000";
        RestTemplate restTemplate = restTemplateConfig.build();
        // 发送GET请求
        ResponseEntity<Map> responseEntity = restTemplate.getForEntity(url, Map.class);
        // 获取响应对象里的 body 对象
        Map<String, Object> body = responseEntity.getBody();
        // 获取状态码
        Integer code = (Integer)body.get("code");
        // 获取响应信息
        String message = (String)body.get("msg");
        if(code==200){
            ThreadLocalRandom random = ThreadLocalRandom.current();
            ArrayList list = (ArrayList) body.get("rows");
            if(list!=null&&list.size()>0){
                illegalParkingMapper.delete(null);
                for (int i=0;i<list.size();i++){
                    LinkedHashMap json = (LinkedHashMap) list.get(i);
                    IllegalParking illegalParking = new IllegalParking();
                    illegalParking.setId((Integer) json.get("id"));
                    illegalParking.setLicencePlate(String.valueOf(json.get("illegalCardnumber")));
                    illegalParking.setIllegalTime(String.valueOf(json.get("illegalTime")));
                    illegalParking.setManagerTime(String.valueOf(json.get("managerTime")));
                    illegalParking.setIllegalReason(String.valueOf(json.get("illegalReason")));
                    illegalParkingMapper.insert(illegalParking);
                }
            }
            return ReturnMsg.ok();

        }else{
            log.info("获取违停数据："+message);
            return  ReturnMsg.fail(message);
        }
    }
}
