package org.springblade.openinterface.doordevice;

import cn.hutool.core.lang.copier.Copier;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import org.springblade.community.agency.entity.Agency;
import org.springblade.community.residential.entity.Residential;
import org.springblade.community.residential.service.IResidentialService;
import org.springblade.core.tool.api.R;
import org.springblade.openinterface.dto.doordevice.DoorDevicePushDto;
import org.springblade.openinterface.dto.estate.AgencyPushDto;
import org.springblade.openinterface.dto.estate.ResidentialPushDto;
import org.springblade.smartapplication.facedevice.entity.FaceDevice;
import org.springblade.smartapplication.facedevice.service.IFaceDeviceService;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created By lidexi in 2021/1/13
 **/
@RestController
@AllArgsConstructor
@RequestMapping("openinterface/listen/door/device")
public class DoorDeviceOpenController {

	private IFaceDeviceService faceDeviceService;
	private IResidentialService residentialService;

	@PostMapping("/deviceSync")
	public R deviceSync(@RequestBody DoorDevicePushDto doorDevicePushDto) {
		FaceDevice newFaceDevie = this.buildNewFaceDevice(doorDevicePushDto);
		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());
		}

		return R.status(faceDeviceService.saveOrUpdate(newFaceDevie));
	}


	private FaceDevice buildNewFaceDevice(DoorDevicePushDto doorDevicePushDto) {
		FaceDevice faceDevice = new FaceDevice();

		faceDevice.setProvinceCode(doorDevicePushDto.getRegionProvince());
		faceDevice.setMacAddress(doorDevicePushDto.getSerialNumber());
		faceDevice.setOldId(doorDevicePushDto.getId().toString());
		faceDevice.setAreaCode(doorDevicePushDto.getRegionArea());
		faceDevice.setDeviceStatus(doorDevicePushDto.getOnlineStatus());

		List<Residential> residentials = residentialService.getBaseMapper().selectList(new QueryWrapper<>(new Residential()).lambda().eq(Residential::getOldId, doorDevicePushDto.getXqId()));
		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());
		}

		faceDevice.setCityCode(doorDevicePushDto.getRegionCity());
		faceDevice.setCameraName(doorDevicePushDto.getName());
		faceDevice.setCameraCode(doorDevicePushDto.getSerialNumber());//设备编号使用物业系统序列号
		faceDevice.setAddress(doorDevicePushDto.getInstallPath());

		faceDevice.setDeviceFactory(doorDevicePushDto.getDeviceFactory());

		return faceDevice;
	}


	@PostMapping("/pushToEstateSystem")
	public R accessRecordSync() {

		List<FaceDevice> faceDevices = faceDeviceService.getBaseMapper().selectList(new QueryWrapper<>(new FaceDevice()));
		List<DoorDevicePushDto> doorDevicePushDtos = new ArrayList<>();

		for (int i = 0; i < faceDevices.size(); i++) {
			FaceDevice faceDevice = faceDevices.get(i);

			DoorDevicePushDto doorDevicePushDto = new DoorDevicePushDto();
			doorDevicePushDto.setId(faceDevice.getId());
			doorDevicePushDto.setTimeStrategyIsEnable(1);
			doorDevicePushDto.setDeviceFactory("qinlin");
			doorDevicePushDto.setHaveCall(1);
			doorDevicePushDto.setReboot(1);
			doorDevicePushDto.setName(faceDevice.getCameraName());
			doorDevicePushDto.setAlias(faceDevice.getCameraName());
			Residential residential = residentialService.getById(faceDevice.getResidentialId());
			if (null != residential) {
				doorDevicePushDto.setXqName(residential.getName());
				doorDevicePushDto.setXqId(residential.getOldId());
				doorDevicePushDto.setRegionArea(residential.getRegionArea());
				doorDevicePushDto.setRegionCity(residential.getRegionCity());
				doorDevicePushDto.setRegionProvince(residential.getRegionProvince());
			} else {
				doorDevicePushDto.setXqName("找不到小区");
			}

			doorDevicePushDto.setXqSort(1);
			doorDevicePushDto.setSerialNumber(faceDevice.getMacAddress());
			doorDevicePushDto.setTypeNumber(1);
			doorDevicePushDto.setHaveFace(1);
			doorDevicePushDto.setInstallPath(faceDevice.getAddress());
//			doorDevicePushDto.setCreateDate(faceDevice.getCreateTime());
//			doorDevicePushDto.setCreateAccountId(1L);
			doorDevicePushDto.setStatus(0);
			doorDevicePushDto.setIsOut(1);

			doorDevicePushDtos.add(doorDevicePushDto);
		}


		RestTemplate restTemplate = new RestTemplate();
//		HttpHeaders httpHeaders =
		ResponseEntity responseEntity = null;
		HttpHeaders headers = new HttpHeaders();
		headers.add(HttpHeaders.CONTENT_TYPE, "application/json");
		Map<String, Object> map = new HashMap<>();
		map.put("doorDeviceList", doorDevicePushDtos);


		HttpEntity<String> requestEntity = new HttpEntity<String>(JSONUtil.toJsonStr(map), headers);
		ParameterizedTypeReference<Object> reference = new ParameterizedTypeReference<Object>() {
		};
		String url = "http://localhost:2003/device/grid/addEntity";
		URI uri = URI.create(url);
		responseEntity = restTemplate.exchange(uri, HttpMethod.POST, requestEntity, reference);
		return R.status(true);
	}
}
