package org.springblade.timedtask;


//import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
//import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.models.auth.In;
import lombok.AllArgsConstructor;
import org.json.JSONArray;
import org.springblade.community.accessrecord.entity.AccessRecord;
import org.springblade.community.accessrecord.service.IAccessRecordService;
import org.springblade.community.agency.entity.Agency;
import org.springblade.community.agency.service.IAgencyService;
import org.springblade.community.building.entity.Building;
import org.springblade.community.building.service.IBuildingService;
import org.springblade.community.floor.entity.Floor;
import org.springblade.community.floor.service.IFloorService;
import org.springblade.community.houseuser.entity.Houseuser;
import org.springblade.community.houseuser.service.IHouseuserService;
import org.springblade.community.personsetting.entity.PersonSetting;
import org.springblade.community.personsetting.service.IPersonSettingService;
import org.springblade.community.residential.entity.Residential;
import org.springblade.community.residential.service.IResidentialService;
import org.springblade.community.room.entity.Room;
import org.springblade.community.room.service.IRoomService;
import org.springblade.community.unit.entity.Unit;
import org.springblade.community.unit.service.IUnitService;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.jobs.personjob.entity.PersonJob;
import org.springblade.jobs.personjob.service.IPersonJobService;
import org.springblade.openinterface.dto.doordevice.DoorDevicePushDto;
import org.springblade.smartapplication.devicelog.entity.DeviceLog;
import org.springblade.smartapplication.devicelog.service.IDeviceLogService;
import org.springblade.smartapplication.facedevice.entity.FaceDevice;
import org.springblade.smartapplication.facedevice.service.IFaceDeviceService;
import org.springblade.smartapplication.smartsmoke.entity.SmartDevice;
import org.springblade.smartapplication.smartsmoke.service.ISmartDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.ws.rs.Path;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Type;
import java.net.URI;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;


@Component
@EnableScheduling
@RestController
@RequestMapping("sync")
//@Profile({"prod"})
public class TimeDTask {

	@Autowired
	private IAgencyService agencyService;

	@Autowired
	private IResidentialService residentialService;

	@Autowired
	private IBuildingService buildingService;

	@Autowired
	private IUnitService unitService;

	@Autowired
	private IFloorService floorService;

	@Autowired
	private IRoomService roomService;

	@Autowired
	private ISmartDeviceService smartDeviceService;

	@Autowired
	private IDeviceLogService deviceLogService;

	@Autowired
	private IFaceDeviceService faceDeviceService;


	@Autowired
	private IHouseuserService houseuserService;

	@Autowired
	private RedisTemplate redisTemplate;
	@Autowired
	private IPersonSettingService personSettingService;
	@Autowired
	private IAccessRecordService accessRecordService;
	@Autowired
	private IPersonJobService personJobService;


	@Scheduled(cron = "0 0 0 * * ?")
	public  void clearRedis() {
		Set<String> keys = redisTemplate.keys("sms:times:" + "*");
		redisTemplate.delete(keys);
		Set keys1 = redisTemplate.keys("ycwg:electricstatic:" + "*");
		redisTemplate.delete(keys1);
		Set<String> keys2 = redisTemplate.keys("loginerror:" + "*");
		redisTemplate.delete(keys2);
	}


	/**
	 * 同步小区数据
	 */
//	@Scheduled(cron =  "0 0 * * * ? ")
	@GetMapping("/syncAgency")
	public  void syncAgency() {
		System.out.println("定时同步社区");
		RestTemplate restTemplate = new RestTemplate();
		ResponseEntity responseEntity = null;
		ParameterizedTypeReference<Object> reference = new ParameterizedTypeReference<Object>() {
		};
		String url = "http://192.168.0.185:9083/grid/estate/syncResidential";
		URI uri = URI.create(url);
		responseEntity = restTemplate.exchange(uri, HttpMethod.GET, null, reference);

		List<Map> map1 = (List<Map>) responseEntity.getBody();

		map1.parallelStream().forEach(map -> {
			Residential residential = new Residential();
			if(map.get("longitude")!=null){
				residential.setLongitude(map.get("longitude").toString());
			}
			if(map.get("latitude")!=null){
				residential.setLatitude(map.get("latitude").toString());
			}

			if(map.get("propertyCompanyId") != null){
				residential.setEstatePid(Long.valueOf(map.get("propertyCompanyId").toString()));
			}
			if(map.get("propertyName") != null){
				residential.setEstatePidName(map.get("propertyName").toString());
			}
			if(map.get("propertyPhone") != null){
				residential.setEstatePidPhone(map.get("propertyPhone").toString());
			}

			residential.setName(map.get("name").toString());
			residential.setRegionProvince(map.get("regionProvince").toString());
			residential.setRegionCity(map.get("regionCity").toString());
			residential.setRegionArea(map.get("regionArea").toString());
			if(map.get("address")!=null){
				residential.setAddress(map.get("address").toString());
			}

			residential.setBuildingNumber((Integer) map.get("buildingNumber"));
			residential.setUnitNumber((Integer) map.get("unitNumber"));
			residential.setFloorNumber((Integer) map.get("floorNumber"));
			residential.setRoomNumber((Integer) map.get("roomNumber"));
			residential.setUserNumber((Integer) map.get("userNumber"));

			residential.setOldId(Long.valueOf(map.get("id").toString()));
			Residential one = residentialService.getOne(new QueryWrapper<>(new Residential()).lambda().eq(Residential::getOldId, residential.getOldId()));
			if(one != null){
				residential.setId(one.getId());
				residentialService.updateById(residential);
			}else {
				residentialService.save(residential);
			}








		});
	}

	/**
	 * 同步小区数据
	 */
//	@Scheduled(cron =  "0 0 * * * ? ")
	@GetMapping("/syncResidential")
	public  void syncResidential() {
		System.out.println("定时同步小区");
		RestTemplate restTemplate = new RestTemplate();
		ResponseEntity responseEntity = null;
		ParameterizedTypeReference<Object> reference = new ParameterizedTypeReference<Object>() {
		};
		String url = "http://192.168.0.185:9083/grid/estate/syncResidential";
		URI uri = URI.create(url);
		responseEntity = restTemplate.exchange(uri, HttpMethod.GET, null, reference);

		List<Map> map1 = (List<Map>) responseEntity.getBody();

		map1.parallelStream().forEach(map -> {
			Residential residential = new Residential();
			if(map.get("longitude")!=null){
				residential.setLongitude(map.get("longitude").toString());
			}
			if(map.get("latitude")!=null){
				residential.setLatitude(map.get("latitude").toString());
			}

			if(map.get("propertyCompanyId") != null){
				residential.setEstatePid(Long.valueOf(map.get("propertyCompanyId").toString()));
			}
			if(map.get("propertyName") != null){
				residential.setEstatePidName(map.get("propertyName").toString());
			}
			if(map.get("propertyPhone") != null){
				residential.setEstatePidPhone(map.get("propertyPhone").toString());
			}

			residential.setName(map.get("name").toString());
			residential.setRegionProvince(map.get("regionProvince").toString());
			residential.setRegionCity(map.get("regionCity").toString());
			residential.setRegionArea(map.get("regionArea").toString());
			if(map.get("address")!=null){
				residential.setAddress(map.get("address").toString());
			}

			residential.setBuildingNumber((Integer) map.get("buildingNumber"));
			residential.setUnitNumber((Integer) map.get("unitNumber"));
			residential.setFloorNumber((Integer) map.get("floorNumber"));
			residential.setRoomNumber((Integer) map.get("roomNumber"));
			residential.setUserNumber((Integer) map.get("userNumber"));

				residential.setOldId(Long.valueOf(map.get("id").toString()));
				Residential one = residentialService.getOne(new QueryWrapper<>(new Residential()).lambda().eq(Residential::getOldId, residential.getOldId()));
				if(one != null){
					residential.setId(one.getId());
					residentialService.updateById(residential);
				}else {
					residentialService.save(residential);
				}








		});
	}

	@PostMapping("/syncHouseInfoAndUser")
	public R syncHouseInfoAndUserByResidentialId(@RequestParam(required = true) String oldIds){
		List<Long> oldIdList = Func.toLongList(oldIds);
		for (int i = 0; i < oldIdList.size(); i++) {
			Long oldId = oldIdList.get(i);
			this.syncBuilding(oldId);
			this.syncUnit(oldId);
			this.syncFloor(oldId);
			this.syncRoom(oldId);

			try {
				this.syncUser(oldId);
			}catch (Exception e){

			}

		}

		return R.status(true);
	}

	/**
	 * 定时同步楼栋
	 */
//	@Scheduled(cron =  "0 0 0 * * ? ")
	@PostMapping("/syncBuilding/{residentialOldId}")
	public  void syncBuilding(@PathVariable("residentialOldId")Long residentialOldId) {
		System.out.println("同步楼栋");
		RestTemplate restTemplate = new RestTemplate();
		ResponseEntity responseEntity = null;
		ParameterizedTypeReference<Object> reference = new ParameterizedTypeReference<Object>() {
		};
//		String url = "http://192.168.0.167:9083/grid/building/syncBuilding/"+residentialOldId;
		String url = "http://192.168.0.185:9083/grid/building/syncBuilding/"+residentialOldId;
		URI uri = URI.create(url);
		responseEntity = restTemplate.exchange(uri, HttpMethod.GET, null, reference);

		List<Map> map1 = (List<Map>) responseEntity.getBody();

		for(int i=0;i<map1.size();i++){
			Map map = map1.get(i);
			Building building = new Building();

			building.setOldId(Long.valueOf(map.get("id").toString()));
			building.setName(map.get("name").toString());
			building.setUnitNumber((Integer)map.get("unitNumber"));
			building.setRoomNumber((Integer) map.get("roomNumber"));
			building.setPersonNumber((Integer)map.get("personNumber"));
//			building.setResidentialId(Long.valueOf(map.get("residentialId").toString()));

			Residential residential = residentialService.getOne(new QueryWrapper<>(new Residential()).lambda().eq(Residential::getOldId,Long.valueOf(map.get("residentialId").toString())));
			if(residential !=null){
				building.setResidentialId(residential.getId());
				building.setResidentialName(residential.getName());
				building.setAgencyId(residential.getAgencyId());
				building.setOrgPosition(residential.getOrgPosition());
				building.setTenantId(residential.getTenantId());
			}
//			building.setResidentialName(map.get("residentialName").toString());
			building.setFloorNumber((Integer)map.get("floorNumber"));

			Building one = buildingService.getOne(new QueryWrapper<>(new Building()).lambda().eq(Building::getOldId, building.getOldId()));
			if(one != null){
				building.setId(one.getId());
				building.setOrgPosition(residential.getOrgPosition()+"/"+building.getId());
				buildingService.updateById(building);
			}else {
				buildingService.save(building);
				building.setOrgPosition(building.getOrgPosition()+"/"+building.getId());
				buildingService.updateById(building);
			}


		}
	}

	/**
	 * 定时同步单元
	 */
//	@Scheduled(cron =  "0 0 0 * * ? ")
	@PostMapping("/syncUnit/{residentialOldId}")
	public  void syncUnit(@PathVariable("residentialOldId")Long residentialOldId) {
		System.out.println("同步单元");
		RestTemplate restTemplate = new RestTemplate();
		ResponseEntity responseEntity = null;
		ParameterizedTypeReference<Object> reference = new ParameterizedTypeReference<Object>() {
		};
		String url = "http://192.168.0.185:9083/grid/unit/syncUnit/"+residentialOldId;
		URI uri = URI.create(url);
		responseEntity = restTemplate.exchange(uri, HttpMethod.GET, null, reference);

		List<Map> map1 = (List<Map>) responseEntity.getBody();

		map1.parallelStream().forEach(map->{

			Unit unit = new Unit();
			unit.setName(map.get("name").toString());
			//单元关联的小区楼栋id改为新平台id,\

			Residential residential = residentialService.getOne(new QueryWrapper<>(new Residential()).lambda().eq(Residential::getOldId,Long.valueOf(map.get("residentialId").toString())));
			if(residential !=null){
				unit.setResidentialId(residential.getId());
				unit.setResidentialName(residential.getName());
				unit.setAgencyId(residential.getAgencyId());
				unit.setTenantId(residential.getTenantId());
			}
			Building building = buildingService.getOne(new QueryWrapper<>(new Building()).lambda().eq(Building::getOldId,map.get("buildingId").toString()));
			if(building != null){
				unit.setBuildingId(building.getId());
				unit.setBuildingName(building.getName());
			}
//			unit.setResidentialId(Long.valueOf(map.get("residentialId").toString()));
//			unit.setResidentialName(map.get("residentialName").toString());
			unit.setRoomNumber((Integer) map.get("roomNumber"));
			unit.setUserNumber((Integer)map.get("userNumber"));
			unit.setOldId(Long.valueOf(map.get("id").toString()));
			unit.setFloorNumber((Integer) map.get("floorNumber"));


			Unit one = unitService.getOne(new QueryWrapper<>(new Unit()).lambda().eq(Unit::getOldId, unit.getOldId()));
			if(one != null){
				unit.setId(one.getId());
				if(building == null){
					System.out.println(map.get("buildingId").toString()+"2此单元找不到楼栋信息："+unit.toString());
				}
				unit.setOrgPosition(building.getOrgPosition()+"/"+unit.getId());
				unitService.updateById(unit);
			}else {
				unitService.save(unit);
				if(building == null){
					System.out.println(map.get("buildingId").toString()+"1此单元找不到楼栋信息："+unit.toString());
				}
				unit.setOrgPosition(building.getOrgPosition()+"/"+unit.getId());
				unitService.updateById(unit);
			}


		});
	}

	/**
	 * 定时同步楼层
	 */
//	@Scheduled(cron =  "0 0 0 * * ? ")
	@PostMapping("/syncFloor/{residentialOldId}")
	public  void syncFloor(@PathVariable("residentialOldId")Long residentialOldId) {
		System.out.println("同步楼层");
		RestTemplate restTemplate = new RestTemplate();
		ResponseEntity responseEntity = null;
		ParameterizedTypeReference<Object> reference = new ParameterizedTypeReference<Object>() {
		};
		String url = "http://192.168.0.185:9083/grid/floor/syncFloor/"+residentialOldId;
		URI uri = URI.create(url);
		responseEntity = restTemplate.exchange(uri, HttpMethod.GET, null, reference);

		List<Map> map1 = (List<Map>) responseEntity.getBody();

		map1.parallelStream().forEach(map -> {
			Floor floor = new Floor();
			floor.setName(map.get("name").toString());
			//单元关联的小区楼栋id改为新平台id,\
			Residential residential = residentialService.getOne(new QueryWrapper<>(new Residential()).lambda().eq(Residential::getOldId,Long.valueOf(map.get("residentialId").toString())));
			if(residential !=null){
				floor.setResidentialId(residential.getId());
				floor.setResidentialName(residential.getName());
				floor.setAgencyId(residential.getAgencyId());
				floor.setTenantId(residential.getTenantId());
			}
			Building building = buildingService.getOne(new QueryWrapper<>(new Building()).lambda().eq(Building::getOldId,map.get("buildingId").toString()));
			if(building != null){
				floor.setBuildingId(building.getId());
				floor.setBuildingName(building.getName());
			}
			Unit unit = unitService.getOne(new QueryWrapper<>(new Unit()).lambda().eq(Unit::getOldId,Long.valueOf(map.get("unitId").toString())));
			if(unit != null){
				floor.setUnitId(unit.getId());
				floor.setUnitName(unit.getName());
			}
			floor.setRoomNumber((Integer) map.get("roomNumber"));
			floor.setUserNumber((Integer)map.get("userNumber"));
			floor.setOldId(map.get("id").toString());






			Floor one = floorService.getOne(new QueryWrapper<>(new Floor()).lambda().eq(Floor::getOldId, floor.getOldId()));
			if(one != null){
				floor.setId(one.getId());
				floor.setOrgPosition(unit.getOrgPosition()+"/"+floor.getId());
				floorService.updateById(floor);
			}else {
				floorService.save(floor);
				floor.setOrgPosition(unit.getOrgPosition()+"/"+floor.getId());
				floorService.updateById(floor);
			}


		});
	}

	/**
	 * 定时同步房间
	 */
//	@Scheduled(cron =  "0 0 0 * * ? ")
	@PostMapping("/syncRoom/{residentialOldId}")
	public  void syncRoom(@PathVariable("residentialOldId")Long residentialOldId) {
		System.out.println("同步房间");
		RestTemplate restTemplate = new RestTemplate();
		ResponseEntity responseEntity = null;
		ParameterizedTypeReference<Object> reference = new ParameterizedTypeReference<Object>() {
		};
		String url = "http://192.168.0.185:9083/grid/room/syncRoom/"+residentialOldId;
		URI uri = URI.create(url);
		responseEntity = restTemplate.exchange(uri, HttpMethod.GET, null, reference);

		List<Map> map1 = (List<Map>) responseEntity.getBody();

		map1.parallelStream().forEach(map -> {
			Room room = new Room();
			room.setName(map.get("name").toString());
			//单元关联的小区楼栋id改为新平台id,\
			Residential residential = residentialService.getOne(new QueryWrapper<>(new Residential()).lambda().eq(Residential::getOldId,Long.valueOf(map.get("residentialId").toString())));
			if(residential !=null){
				room.setResidentialId(residential.getId());
				room.setResidentialName(residential.getName());
				room.setAgencyId(residential.getAgencyId());
			}
			Building building = buildingService.getOne(new QueryWrapper<>(new Building()).lambda().eq(Building::getOldId,map.get("buildingId").toString()));
			if(building != null){
				room.setBuildingId(building.getId());
				room.setBuildingName(building.getName());
			}
			Unit unit = unitService.getOne(new QueryWrapper<>(new Unit()).lambda().eq(Unit::getOldId,Long.valueOf(map.get("unitId").toString())));
			if(unit != null){
				room.setUnitId(unit.getId());
				room.setUnitName(unit.getName());
			}
			Floor floor = floorService.getOne(new QueryWrapper<>(new Floor()).lambda().eq(Floor::getOldId,map.get("floorId").toString()));
			if(floor != null){
				room.setFloorId(floor.getId());
				room.setFloorName(floor.getName());
			}
			room.setOldId(Long.valueOf(map.get("id").toString()));
			room.setUserNumber(Integer.valueOf(map.get("personNumber").toString()));
			Room one = roomService.getOne(new QueryWrapper<>(new Room()).lambda().eq(Room::getOldId, room.getOldId()));
			if(one != null){
				room.setId(one.getId());
				room.setOrgPosition(floor.getOrgPosition()+"/"+room.getId());
				roomService.updateById(room);
			}else {
				roomService.save(room);
				room.setOrgPosition(floor.getOrgPosition()+"/"+room.getId());
				roomService.updateById(room);
			}

		});
	}

	/**
	 * 同步亲邻智能物联网平台住户数据
	 * @return
	 */
	@PostMapping("/syncUser/{residentialOldId}")
	public int syncUser(@PathVariable(value = "residentialOldId") Long residentialOldId) throws ParseException {

		System.out.println("同步住户");
		RestTemplate restTemplate = new RestTemplate();
		ResponseEntity responseEntity = null;
		ParameterizedTypeReference<Object> reference = new ParameterizedTypeReference<Object>() {
		};
		String url = "http://192.168.0.185:9083/grid/user/syncUser/"+residentialOldId;
		URI uri = URI.create(url);
		responseEntity = restTemplate.exchange(uri, HttpMethod.GET, null, reference);

		List<Map> userMapList = (List<Map>) responseEntity.getBody();
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

//		userMapList.parallelStream().forEach(userMap -> {
		for(int i = 0;i<userMapList.size();i++){
			Map userMap = userMapList.get(i);
			Houseuser houseuser = new Houseuser();
			houseuser.setOldId(userMap.get("id").toString());
			houseuser.setPersonType(1);//默认为常住人员
			try {
				houseuser.setCreateDate(sf.parse(userMap.get("createDate").toString()));
				houseuser.setName(userMap.get("name").toString());
				houseuser.setSex(Integer.valueOf(userMap.get("sex").toString()));
				houseuser.setRegionProvince(userMap.get("regionProvince").toString());

				houseuser.setRegionCity(userMap.get("regionCity").toString());
				houseuser.setRegionArea(userMap.get("regionArea").toString());
				if(userMap.get("tel")!=null)
				houseuser.setTel(userMap.get("tel").toString());

//				String residentialOldId = userMap.get("residentialId").toString();
				Residential residential1 = residentialService.getBaseMapper().selectOne(new QueryWrapper<>(new Residential()).lambda().eq(Residential::getOldId, residentialOldId));

				if(residential1 != null){
					houseuser.setResidentialId(residential1.getId());
					houseuser.setResidentialName(residential1.getName());
					houseuser.setAgencyId(residential1.getAgencyId());
					Agency agency = agencyService.getById(residential1.getAgencyId());
					houseuser.setAgencyName(agency.getAgencyName());
				}
				if (userMap.get("idCard")!=null)
				houseuser.setIdCard(userMap.get("idCard").toString());
				Houseuser one = houseuserService.getBaseMapper().selectOne(new QueryWrapper<>(new Houseuser()).lambda().eq(Houseuser::getOldId, houseuser.getOldId()));
				if(one != null){
					houseuser.setId(one.getId());
					houseuser.setOrgPosition(residential1.getOrgPosition()+"/"+one.getId());
					houseuserService.updateById(houseuser);
				}else {
					houseuserService.save(houseuser);
					houseuser.setOrgPosition(residential1.getOrgPosition() + "/" + houseuser.getId());
					houseuserService.updateById(houseuser);
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		return 1;
	}



	/**
	 * 定时同步设备列表
	 */
//	@Scheduled(cron =  "0 0 0 * * ? ")
	@GetMapping("/syncDevice")
	public  void syncDevice() {
		RestTemplate restTemplate = new RestTemplate();
		ResponseEntity responseEntity = null;
		ParameterizedTypeReference<Object> reference = new ParameterizedTypeReference<Object>() {
		};
		String url = "http://192.168.0.185:9083/grid/iot/device/list";
		URI uri = URI.create(url);
		responseEntity = restTemplate.exchange(uri, HttpMethod.GET, null, reference);

		Map body = (Map) responseEntity.getBody();
		Map data = (Map)body.get("data");
		List<Map> deviceList = (List<Map>)data.get("records");


		deviceList.parallelStream().forEach(map -> {
			SmartDevice smartDevice = new SmartDevice();
			smartDevice.setDeviceId(map.get("device_id").toString());
			smartDevice.setDeviceName(map.get("device_name").toString());
			smartDevice.setManufacturersNo(map.get("manufacturers_no").toString());
			smartDevice.setManufacturers(map.get("manufacturer").toString());
			smartDevice.setDefenseStatus((Integer) map.get("defense_status"));
			smartDevice.setOldId(Long.valueOf(map.get("id").toString()));
			smartDevice.setDeviceStatus(Integer.valueOf(map.get("status").toString()));
			smartDevice.setLatitudeLongitude(map.get("latitude_longitude").toString());
			if(map.get("device_install_address")!=null){
				smartDevice.setDeviceInstallAddress(map.get("device_install_address").toString());
			}

			smartDevice.setIsAep(Integer.valueOf(map.get("is_aep").toString()));
			if(map.get("tag")!=null){
				smartDevice.setTag(Integer.valueOf(map.get("tag").toString()));
			}

			if(map.get("device_specld")!=null){
				smartDevice.setDeviceSpecld(map.get("device_specld").toString());
			}
			if(map.get("product_id")!=null){
				smartDevice.setProductId(map.get("product_id").toString());
			}
			if(map.get("area")!=null){
				smartDevice.setArea(map.get("area").toString());
			}
			if(map.get("person_id")!=null){
				smartDevice.setPerson(map.get("person_id").toString());
			}
			if(map.get("organization")!=null){
				smartDevice.setOrganization(map.get("organization").toString());
			}
			if(map.get("uuid")!=null){
				smartDevice.setUuid(map.get("uuid").toString());
			}
			if(map.get("did")!=null){
				smartDevice.setDid(map.get("did").toString());
			}
			if(map.get("appId")!=null){
				smartDevice.setAppId(map.get("appId").toString());
			}

//			if(map.get("prefix").toString().contains("smoke3")){
//				smartDevice.setDeviceType(1);
//			}else if(map.get("prefix").toString().contains("gasmonitoring")){
//				smartDevice.setDeviceType(2);
//			}
			if (map.get("prefix") != null){
				smartDevice.setPrefix(map.get("prefix").toString());
			}
			if (map.get("device_type") != null){
				smartDevice.setDeviceType(map.get("device_type").toString());
			}
			smartDevice.setDeviceUsage(20);

			DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
			smartDevice.setLastUpdateTime( LocalDateTime.parse(map.get("lastSyncDate").toString(),df));
			if(map.get("battery_value")!=null){
				smartDevice.setBattery(map.get("battery_value").toString());
			}
			if(map.get("battery_voltage")!=null){
				smartDevice.setBatteryVoltage(map.get("battery_voltage").toString());
			}
			if(map.get("imei")!=null){
				smartDevice.setImei(map.get("imei").toString());
			}
			if(map.get("iccid")!=null){
				smartDevice.setIccid(map.get("iccid").toString());
			}
			if(map.get("imsi")!=null){
				smartDevice.setImsi(map.get("imsi").toString());
			}


			SmartDevice one = smartDeviceService.getBaseMapper().selectOne(new QueryWrapper<>(new SmartDevice()).lambda().eq(SmartDevice::getOldId,smartDevice.getOldId()));

			if(null != one){
				smartDevice.setId(one.getId());
				smartDeviceService.updateById(smartDevice);
			}else{
				smartDeviceService.save(smartDevice);
			}
		});
	}

	/**
	 * 定时同步房间
	 */
//	@Scheduled(cron =  "0 0 0 * * ? ")
	@GetMapping("/syncDeviceLog")
	public  void syncDeviceLog() {
		System.out.println("同步设备日志");
		RestTemplate restTemplate = new RestTemplate();
		ResponseEntity responseEntity = null;
		ParameterizedTypeReference<Object> reference = new ParameterizedTypeReference<Object>() {
		};
		String url = "http://192.168.0.185:9083/grid/iot/apiLog/list";
		URI uri = URI.create(url);
		responseEntity = restTemplate.exchange(uri, HttpMethod.GET, null, reference);

		List<Map> map1 = (List<Map>) responseEntity.getBody();

		map1.parallelStream().forEach(map -> {
			DeviceLog deviceLog = new DeviceLog();
			deviceLog.setOldId(Long.valueOf(map.get("id").toString()));
			deviceLog.setCode(map.get("code").toString());
			deviceLog.setMsg(map.get("msg").toString());
			deviceLog.setApiMethod(map.get("apiMethod").toString());
			if(deviceLog.getApiMethod().contains("heartbeat")){
				deviceLog.setLogType(1);
			}else  if(deviceLog.getApiMethod().contains("alarm")){
				deviceLog.setLogType(2);
			}else if(deviceLog.getApiMethod().contains("deviceStatus")){
				deviceLog.setLogType(3);
			}
			deviceLog.setData(map.get("reqData").toString());
			if(deviceLog.getData().startsWith("[")&&deviceLog.getData().endsWith("]")){
				JSONArray array = new JSONArray(deviceLog.getData());

				if(array.length()>0){
					String deviceId=array.getJSONObject(0).get("device_id").toString();
					if(deviceId != null){
						deviceLog.setDeviceId(deviceId);
					}
				}

			}else if(deviceLog.getData().startsWith("{")&&deviceLog.getData().endsWith("}")){
				JSONObject jsonObject = JSONObject.parseObject(deviceLog.getData());
				Object device_id = jsonObject.get("device_id");
				if (device_id!=null){
					deviceLog.setDeviceId(device_id.toString());
				}
			}

			DeviceLog deviceLog1 = deviceLogService.getOne(new QueryWrapper<>(new DeviceLog()).lambda().eq(DeviceLog::getOldId,deviceLog.getOldId()));
			if(null != deviceLog1){
				deviceLog.setId(deviceLog1.getId());
				deviceLogService.updateById(deviceLog);
			}else{
				deviceLogService.save(deviceLog);
			}


		});
	}

	@PostMapping("/syncVCDevice")
	public void syncVCDevice(){
		RestTemplate restTemplate = new RestTemplate();
		ResponseEntity responseEntity = null;
		ParameterizedTypeReference<Object> reference = new ParameterizedTypeReference<Object>() {

		};
		String url = "http://192.168.0.185:9083/grid/videoCloud/device/list";
		URI uri = URI.create(url);
		responseEntity = restTemplate.exchange(uri, HttpMethod.GET, null, reference);

		List<Map> map1 = (List<Map>) responseEntity.getBody();
	}


	/**
	 * 同步亲邻智能物联网平台人脸设备数据
	 * @return
	 */
	@GetMapping("/facedevice")
	public int syncFaceDevice() throws ParseException {

		int result = 0;
//		IResidentialService residentialService =new ResidentialServiceImpl();
		RestTemplate restTemplate = new RestTemplate();
//		HttpHeaders httpHeaders =
		ResponseEntity responseEntity = null;
		HttpHeaders headers = new HttpHeaders();
		headers.add(HttpHeaders.CONTENT_TYPE, "text/plain");
		headers.add(HttpHeaders.HOST, "qiotapi.qinlinkeji.com");
		headers.add("Cookie", "acw_tc=2760821216040233709218017edfed503c3f299563c0716431831777dc716e");
		Map<String, Object> map = new HashMap<>();
		map.put("pageNum", 1);
		map.put("pageSize", 1000);

		HttpEntity<String> requestEntity = new HttpEntity<String>(JSONUtil.toJsonStr(map), headers);
		ParameterizedTypeReference<Object> reference = new ParameterizedTypeReference<Object>() {
		};
		String url = "https://qiotapi.qinlinkeji.com/admin/hardware/faceCemera/findListPage?sessionId=admin:2c94812e75fa974901762dc0b4b503ad";
		URI uri = URI.create(url);
		responseEntity = restTemplate.exchange(uri, HttpMethod.POST, requestEntity, reference);


		Map body = (Map) responseEntity.getBody();
		Map data = (Map) body.get("data");
		List<Map> list = (List<Map>) data.get("list");
		for(int i = 0;i<list.size();i++){
			int res = syncFaceDeviceDetail(Integer.valueOf(list.get(i).get("id").toString()));
			result = res+result;
		}


		return result;
	}

	private int syncFaceDeviceDetail(Integer faceCameraId) throws ParseException {

		RestTemplate restTemplate = new RestTemplate();
//		HttpHeaders httpHeaders =
		ResponseEntity responseEntity = null;
		HttpHeaders headers = new HttpHeaders();
		headers.add(HttpHeaders.CONTENT_TYPE, "text/plain");
		headers.add(HttpHeaders.HOST, "qiotapi.qinlinkeji.com");
		headers.add("Cookie", "acw_tc=2760821216040233709218017edfed503c3f299563c0716431831777dc716e");
		Map<String, Object> map = new HashMap<>();


		HttpEntity<String> requestEntity = new HttpEntity<String>(JSONUtil.toJsonStr(map), headers);
		ParameterizedTypeReference<Object> reference = new ParameterizedTypeReference<Object>() {
		};
		String url = "https://qiotapi.qinlinkeji.com/admin/hardware/faceCemera/findById?sessionId=admin:2c94812e75fa974901762dc0b4b503ad&faceCameraId=" + faceCameraId;
		URI uri = URI.create(url);
		responseEntity = restTemplate.exchange(uri, HttpMethod.POST, requestEntity, reference);


		Map body = (Map) responseEntity.getBody();

		Map data = (Map) body.get("data");

		FaceDevice faceDevice = new FaceDevice();

		faceDevice.setAddress(data.get("address").toString());
		faceDevice.setCameraCode(data.get("cameraCode").toString());
		faceDevice.setCameraName(data.get("cameraName").toString());
		faceDevice.setCityCode(data.get("cityCode").toString());

		//绑定小区
		Residential residential = residentialService.getBaseMapper().selectOne(new QueryWrapper<>(new Residential()).lambda().eq(Residential::getOldId, data.get("communityId").toString()));
		if(null != residential){
			faceDevice.setResidentialId(residential.getId());

		}

		faceDevice.setDeviceStatus(Integer.valueOf(data.get("deviceStatus").toString()));
		faceDevice.setAreaCode(data.get("districtCode").toString());
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		faceDevice.setCreateTime(sf.parse(data.get("gmtCreate").toString()));
		faceDevice.setOldId(data.get("id").toString());
		faceDevice.setLatitude(data.get("latitude").toString());
		faceDevice.setLongitude(data.get("longitude").toString());
		faceDevice.setMacAddress(data.get("macAddress").toString());
		faceDevice.setProvinceCode(data.get("provinceCode").toString());



		FaceDevice one = faceDeviceService.getBaseMapper().selectOne(new QueryWrapper<>(new FaceDevice()).lambda().eq(FaceDevice::getOldId, faceDevice.getOldId()));
		if(null != one){
			faceDevice.setId(one.getId());
			if(residential !=null){
				faceDevice.setOrgPosition(residential.getOrgPosition()+"/"+faceDevice.getId());
			}
			return faceDeviceService.updateById(faceDevice)?1:0;
		}else{
			faceDeviceService.save(faceDevice);
			if(residential !=null){
				faceDevice.setOrgPosition(residential.getOrgPosition()+"/"+faceDevice.getId());
			}
			return faceDeviceService.updateById(faceDevice)?1:0;
		}



	}



	/**
	 * 根据小区id同步物业系统门禁设备列表
	 */
//	@Scheduled(cron =  "0 0 0 * * ? ")
	@PostMapping("/syncDoorDevice/{residentialOldId}")
	public  R syncDoorDevice(@PathVariable(value = "residentialOldId") Long residentialOldId) {
		RestTemplate restTemplate = new RestTemplate();
		ResponseEntity responseEntity = null;
		ParameterizedTypeReference<Object> reference = new ParameterizedTypeReference<Object>() {
		};
		String url = "http://192.168.0.185:9083/grid/doordevice/syncDoorDevice/"+residentialOldId;
		URI uri = URI.create(url);
		responseEntity = restTemplate.exchange(uri, HttpMethod.GET, null, reference);

		Map body = (Map) responseEntity.getBody();
		Map data = (Map)body.get("data");
		List<Map> deviceList = (List<Map>)data.get("records");

		for(Map map:deviceList){

			FaceDevice newFaceDevie = this.buildNewFaceDevice(map);
			List<FaceDevice> faceDevices = faceDeviceService.getBaseMapper().selectList(new QueryWrapper<>(new FaceDevice()).lambda().eq(FaceDevice::getMacAddress, newFaceDevie.getMacAddress()));
			if (faceDevices.size() > 0) {//修改门禁设备信息
				FaceDevice oldFaceDevice = faceDevices.get(0);
				//将旧对象的id复制给新对象，根据id修改门禁设备的信息
				newFaceDevie.setId(oldFaceDevice.getId());
			}

			boolean b = faceDeviceService.saveOrUpdate(newFaceDevie);
			System.out.println(b);

		}

		return R.status(true);
	}

	/**
	 * 人员异常
	 */
	@Scheduled(cron =  "0 0 18 * * ?")
	@GetMapping("/personTask")
	public  R personAlarm() {

		PersonSetting globalSetting = personSettingService.getOne(new QueryWrapper<>(new PersonSetting()).lambda().eq(PersonSetting::getLevel, 1).eq(PersonSetting::getTypeId, 1));

		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		List<Residential> residentialList = residentialService.list();
		residentialList.parallelStream().forEach(residential -> {

			PersonSetting itemSetting = personSettingService.getOne(new QueryWrapper<>(new PersonSetting()).lambda().eq(PersonSetting::getLevel, 2).eq(PersonSetting::getResidentialId, residential.getId()));
			String value = globalSetting.getValue();
			if (itemSetting == null || itemSetting.getValue() == null){

			}else{
				value = itemSetting.getValue();
			}
			List<Houseuser> userList = houseuserService.list(new QueryWrapper<>(new Houseuser()).lambda().eq(Houseuser::getResidentialId, residential.getId()));
			if (userList != null && userList.size() > 0){
				String finalValue = value;
				userList.parallelStream().forEach(user -> {
					LambdaQueryWrapper<AccessRecord> eq = new QueryWrapper<>(new AccessRecord()).lambda().eq(AccessRecord::getResidentialId, residential.getId())
						.like(AccessRecord::getOrgPosition, residential.getOrgPosition()).eq(AccessRecord::getUserId, user.getId())
						.orderByDesc(AccessRecord::getCreateTime);
					List<AccessRecord> recordlist = accessRecordService.list(eq);
					if (recordlist != null && recordlist.size() > 0){
						AccessRecord last = recordlist.get(0);

						PersonJob one = personJobService.getOne(new QueryWrapper<>(new PersonJob()).lambda().eq(PersonJob::getRecordId, last.getId()));

						if (one == null){

							String openTime = last.getOpenTime();
							Date lastTime = null;
							try {
								lastTime = formatter.parse(openTime);
							} catch (ParseException e) {
								e.printStackTrace();
							}
							Calendar calendar = new GregorianCalendar();
							calendar.setTime(lastTime);
							calendar.add(calendar.DATE,Integer.valueOf(finalValue)); //把日期往后增加一天,整数  往后推,负数往前移动
							Date time = calendar.getTime();
							Date now = new Date(System.currentTimeMillis());
							if (time.before(now)){
								// 人员异常，久居未出
								PersonJob personJob = new PersonJob();
								personJob.setOrgPosition(user.getOrgPosition());
								personJob.setPersonId(user.getId());
								personJob.setPerson(user.getName());
								personJob.setPhone(user.getTel());
								personJob.setJobContent("久居未出");
								personJob.setJobStatus(0);
								personJob.setReportTime(now.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
								personJob.setRecordId(last.getId());
								personJob.setHandler(residential.getPersonName());
								personJob.setHandlerPhone(residential.getPersonTel());
								personJobService.save(personJob);
							}

						}


					}

				});
			}

		});

		return R.status(true);
	}





	private FaceDevice buildNewFaceDevice(Map map) {
		FaceDevice faceDevice = new FaceDevice();
		if(map.get("regionProvince") != null){
			faceDevice.setProvinceCode(map.get("regionProvince").toString());
		}
		if(map.get("serialNumber") != null){
			faceDevice.setMacAddress(map.get("serialNumber").toString());
			faceDevice.setCameraCode(map.get("serialNumber").toString());
		}

		faceDevice.setOldId(map.get("id").toString());
		if(map.get("regionArea") != null){
			faceDevice.setAreaCode(map.get("regionArea").toString());
		}
		if(map.get("onlineStatus") != null){
			faceDevice.setDeviceStatus(Integer.valueOf(map.get("onlineStatus").toString()));
		}

		if(map.get("xqId") != null){
			List<Residential> residentials = residentialService.getBaseMapper().selectList(new QueryWrapper<>(new Residential()).lambda().eq(Residential::getOldId, map.get("xqId")));
			if (residentials.size() == 0){
				faceDevice.setResidentialId(0L);//门禁设备的小区信息在数字平台找不到设置为0
			}else{
				faceDevice.setResidentialId(residentials.get(0).getId());
				faceDevice.setOrgPosition(residentials.get(0).getOrgPosition());
				faceDevice.setAgencyId(residentials.get(0).getAgencyId());
				faceDevice.setTenantId(residentials.get(0).getTenantId());
			}
		}

		if(map.get("regionCity") != null){
			faceDevice.setCityCode(map.get("regionCity").toString());
		}

		if(map.get("name") != null){
			faceDevice.setCameraName(map.get("name").toString());
		}

		if(map.get("installPath") != null){
			faceDevice.setAddress(map.get("installPath").toString());
		}

		if(map.get("deviceFactory") != null){
			faceDevice.setDeviceFactory(map.get("deviceFactory").toString());
		}


		return faceDevice;
	}



}
