package org.springblade.datamigration.controller;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.AllArgsConstructor;
import org.springblade.community.entity.Residential;
import org.springblade.community.entity.Unit;
import org.springblade.community.feign.IResidentialClient;
import org.springblade.community.feign.IUnitClient;
import org.springblade.core.tool.api.R;
import org.springblade.datamigration.constant.UrlConstants;
import org.springblade.datamigration.util.TokenUtil;
import org.springblade.datamigration.util.WuyeSystemHttpUtil;
import org.springblade.device.entity.DoorDevice;
import org.springblade.device.entity.IotDevice;
import org.springblade.device.feign.IDoorDeviceClient;
import org.springblade.device.feign.IIotDeviceClient;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lidexi
 * @date 2021/6/11 11:29
 * 设备数据迁移控制层
 */
@AllArgsConstructor
@RequestMapping("/data/migration/device")
@RestController
public class DeviceDataMigrationController  {

	private final RestTemplate restTemplate = new RestTemplate();
	private final IDoorDeviceClient doorDeviceClient;
	private final IResidentialClient residentialClient;
	private final IUnitClient unitClient;
	private final IIotDeviceClient iotDeviceClient;


	/**                        物业系统数据迁移                    **/

	/**
	 * 门禁设备数据迁移
	 * @return
	 */
	@PostMapping("/doorDevice")
	public R doorDevice(){
		String token = TokenUtil.getWuyeSystemToken();
		Map<String, Object> map = new HashMap<>();
		R r = WuyeSystemHttpUtil.postQuery(JSONUtil.toJsonStr(map), UrlConstants.deviceService.DOORDEVICE.getUrl() + "?size=" + Integer.MAX_VALUE + "&current=1", token);
		Map data = (Map) r.getData();
		data = (Map) data.get("data");
		JSONArray records = JSONUtil.parseArray(data.get("records"));
		records.forEach(item -> {
			JSONObject jsonObject = JSONUtil.parseObj(item);
			Long oldId = Long.valueOf(jsonObject.get("id").toString());
			DoorDevice isExist = doorDeviceClient.getById(oldId);
			DoorDevice doorDevice = this.buildDoorDevice(jsonObject);
			if (isExist == null) {//新增

				doorDeviceClient.save(doorDevice);
			} else {
				doorDeviceClient.update(doorDevice);
			}
		});
		return R.data(true);
	}

	/**
	 * iot设备数据迁移
	 * @return
	 */
	@PostMapping("/iotDevice")
	public R iotDevice(){

		String token = TokenUtil.getWuyeSystemToken();
		Map<String, Object> map = new HashMap<>();
		R r = WuyeSystemHttpUtil.postQuery(JSONUtil.toJsonStr(map), UrlConstants.deviceService.IOTDEVICE.getUrl() + "?size=" + Integer.MAX_VALUE + "&current=1", token);
		Map data = (Map) r.getData();
		data = (Map) data.get("data");
		JSONArray records = JSONUtil.parseArray(data.get("records"));
		records.forEach(item -> {
			JSONObject jsonObject = JSONUtil.parseObj(item);
			Long oldId = Long.valueOf(jsonObject.get("id").toString());
			IotDevice oldEntity = new IotDevice();
			oldEntity.setDeviceId(jsonObject.get("device_id").toString());
			IotDevice isExist = iotDeviceClient.detail(oldEntity);
			IotDevice iotDevice = this.buildIotDevice(jsonObject);
			if (isExist == null) {//新增

				iotDeviceClient.save(iotDevice);
			}
		});
		return R.data(true);
	}

	private IotDevice buildIotDevice(JSONObject jsonObject) {

		IotDevice iotDevice = new IotDevice();
		iotDevice.setId(jsonObject.getLong("id"));
//		iotDevice.setOldId(jsonObject.getLong("id"));
		iotDevice.setDeviceId(jsonObject.get("device_id") != null ? jsonObject.getStr("device_id") : null);
		iotDevice.setDeviceName(jsonObject.get("device_name") != null ? jsonObject.getStr("device_name") : null);
//		iotDevice.setManufacturersNo(jsonObject.get("manufacturers_no") != null ? jsonObject.getStr("manufacturers_no") : null);
//		iotDevice.setManufacturer(jsonObject.get("manufacturer") != null ? jsonObject.getStr("manufacturer") : null);
//		iotDevice.setDefenseStatus(jsonObject.get("defense_status") != null ? jsonObject.getInt("defense_status") : null);
		iotDevice.setDeviceType(jsonObject.get("device_type") != null ? jsonObject.getStr("device_type") : null);
		iotDevice.setDeviceStatus(jsonObject.get("status") != null ? jsonObject.getInt("status") : null);
//		iotDevice.setLatitudeLongitude(jsonObject.get("latitude_longitude") != null ?jsonObject.getStr("latitude_longitude") : null);
		iotDevice.setDeviceInstallAddress(jsonObject.get("device_install_address") != null ? jsonObject.getStr("device_install_address") : null);
//		iotDevice.setDistLocate(jsonObject.get("dist_locate") != null ? jsonObject.getStr("dist_locate") : null);
//		iotDevice.setIsAep(jsonObject.get("is_aep") != null ? jsonObject.getInt("is_aep") : null);
//		iotDevice.setDeviceSpecld(jsonObject.get("device_specld") != null ? jsonObject.getStr("device_specld") : null);
//		iotDevice.setProtocolType(jsonObject.get("protocol_type") != null ? jsonObject.getInt("protocol_type"): null);
//		iotDevice.setArea(jsonObject.get("area") != null ? jsonObject.getStr("area") : null);
		iotDevice.setDeviceImage(jsonObject.get("device_image") != null ? jsonObject.getStr("device_image") : null);
//		iotDevice.setUuid(jsonObject.get("uuid") != null ? jsonObject.getStr("uuid") : null);
//		iotDevice.setDid(jsonObject.get("did") != null ? jsonObject.getStr("did") : null);
//		iotDevice.setAppId(jsonObject.get("appId") != null ? jsonObject.getStr("appId") : null);
//		iotDevice.setPrefix(jsonObject.get("prefix") != null ? jsonObject.getStr("prefix") : null);
//		iotDevice.setTag(jsonObject.get("tag") != null ? jsonObject.getInt("tag") : null);
//		iotDevice.setMasterKey(jsonObject.get("master_key") != null ? jsonObject.getStr("master_key") : null);
		iotDevice.setProductId(jsonObject.get("product_id") != null ? jsonObject.getStr("product_id") : null);
		iotDevice.setImei(jsonObject.get("imei") != null ? jsonObject.getStr("imei") : null);
		iotDevice.setImsi(jsonObject.get("imsi") != null ? jsonObject.getStr("imsi") : null);
//		iotDevice.setTenantId("000000");
		return iotDevice;
	}

	private DoorDevice buildDoorDevice(JSONObject jsonObject) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		DoorDevice doorDevice = new DoorDevice();

		doorDevice.setId(jsonObject.getLong("id"));
		try {
			if (null != jsonObject.get("createDate")){
				doorDevice.setCreateTime(sdf.parse(jsonObject.getStr("createDate")));
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		doorDevice.setName(jsonObject.getStr("name"));
		doorDevice.setSerialNum(jsonObject.getStr("serialNumber"));
		doorDevice.setResidentialId(jsonObject.getLong("xqId"));
		Residential residential = this.residentialClient.getById(doorDevice.getResidentialId());
		if(residential != null){
			doorDevice.setTenantId(residential.getTenantId());
			doorDevice.setAgencyId(residential.getAgencyId());
		}else{

		}

		doorDevice.setUnitId(jsonObject.getLong("unitId"));
		if(doorDevice.getUnitId() != null){
			Unit unit = this.unitClient.getById(doorDevice.getUnitId());
			if(unit != null){
				doorDevice.setBuildingId(unit.getBuildingId());
				doorDevice.setTenantId(unit.getTenantId());
			}else{
			}
		}

		doorDevice.setAddress(jsonObject.getStr("installPath"));
		doorDevice.setIsOut(jsonObject.getInt("isOut"));
		doorDevice.setDeviceFactory(jsonObject.getStr("deviceFactory"));


		return doorDevice;
	}











}
