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

import com.sky.ioc.config.RestTemplateConfig;
import com.sky.ioc.entity.domain.security.SecurityDoor;
import com.sky.ioc.mapper.security.SecurityDoorMapper;
import com.sky.ioc.service.security.SecurityDoorService;
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 SecurityDoorServiceImpl implements SecurityDoorService {
    @Autowired
    RestTemplateConfig restTemplateConfig;

    @Autowired
    SecurityDoorMapper securityDoorMapper;

    final static  String SECURITY_DOOR_URL="/api/safety/Hikvision/door/list";
    @Override
    public ReturnMsg getSecurityDoorData() {
        String url = restTemplateConfig.addBaseUrl(SECURITY_DOOR_URL)+"?pageNum=1&pageSize=1000";
        RestTemplate restTemplate = restTemplateConfig.build();
        ResponseEntity<Map> responseEntity = restTemplate.getForEntity(url, Map.class);
        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){
                securityDoorMapper.delete(null);
                for (int i=0;i<list.size();i++){
                    LinkedHashMap json = (LinkedHashMap) list.get(i);
                    SecurityDoor securityDoor = new SecurityDoor();
                    securityDoor.setId((Integer) json.get("id"));
                    securityDoor.setName(String.valueOf(json.get("doorName")));
                    securityDoor.setCode(String.valueOf(json.get("doorIndexCode")));
                    securityDoor.setType(String.valueOf(json.get("channelType")));
                    securityDoor.setNumber(String.valueOf(json.get("channelNo")));
                    securityDoor.setRegionId(Integer.parseInt(String.valueOf(json.get("regionId"))));
                    securityDoorMapper.insert(securityDoor);
                }
            }
            return ReturnMsg.ok();

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

}
