package com.persagy.bdtp.adm.controller;

import cn.hutool.core.util.StrUtil;
import com.persagy.bdtp.adm.client.ImageServiceClient;
import com.persagy.bdtp.adm.client.OldAdmClient;
import com.persagy.bdtp.adm.common.AdmRequest;
import com.persagy.bdtp.adm.common.AdmResult;
import com.persagy.bdtp.adm.datatx.DataTxHandler;
import com.persagy.bdtp.adm.entity.Dict;
import com.persagy.bdtp.adm.entity.DownLoadData;
import com.persagy.bdtp.adm.entity.UploadRtn;
import com.persagy.bdtp.adm.service.ISyncApp;
import com.persagy.bdtp.adm.service.ServiceUtil;
import feign.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/adm")
public class AppController {

	@Autowired
	private ImageServiceClient imageServiceClient;

	@Autowired
	private OldAdmClient admClient;

	@Autowired
	@Qualifier(ServiceUtil.SYNC_APP_IMPL)
	private ISyncApp syncApp;

	@Autowired
	private DataTxHandler dataTxHandler;

	@RequestMapping("/clientId")
	public AdmResult<Map<String, Object>> clientId(@RequestBody AdmRequest req){
		HashMap<String, Object> rtn = new HashMap<>();
		rtn.put("clientId", syncApp.getClientId(req.getUserId()));
		return AdmResult.success(rtn);
	}

	@RequestMapping("/dict")
	public AdmResult<Dict> dict(@RequestBody AdmRequest req){
		return AdmResult.success(syncApp.downloadDict(req.getGroupCode(), req.getProjectId(), req.getUserId()));
	}

	@RequestMapping("/config")
	public AdmResult<Map<String, Object>> config(@RequestBody AdmRequest req){
		return AdmResult.success(syncApp.downloadConfig(req.getGroupCode(), req.getProjectId(), req.getUserId()));
	}

	@RequestMapping("/frame")
	public AdmResult<Map<String, Object>> frame(@RequestBody AdmRequest req){
//		ObjectMapper objectMapper = SpringHelper.getBean(ObjectMapper.class);
//
//		List<ObjectNode> prjList = ServiceUtil.call(() -> objClient.query(req.getGroupCode(), req.getProjectId(), AdmConst.APP_ID, req.getUserId(), getQueryCriteria("project", objectMapper)));
//
//		//建筑和楼层，暂时从dbtp获取
//		List<ObjectNode> bdList = ServiceUtil.call(() -> objClient.query(req.getGroupCode(), req.getProjectId(), AdmConst.APP_ID, req.getUserId(), getQueryCriteria("building", objectMapper)));
//
//		QueryCriteria flCriteria = getQueryCriteria("floor", objectMapper);
//		flCriteria.getCriteria().putObject("relationTo").put("graphCode", "ArchSubset").put("relCode", "Bd2Fl");
//		List<ObjectNode> flList = ServiceUtil.call(() -> objClient.query(req.getGroupCode(), req.getProjectId(), AdmConst.APP_ID, req.getUserId(), flCriteria));
//
//		QueryCriteria relCriteria = getQueryCriteria(null, objectMapper);
//		relCriteria.getCriteria().put("graphCode", "ArchSubset").put("relCode", "Bd2Fl");
//		List<ObjectRelation> relList = ServiceUtil.call(() -> relationClient.query(req.getGroupCode(), req.getProjectId(), AdmConst.APP_ID, req.getUserId(), relCriteria));
//
//		//为楼层数据设置buildingId
//		for(ObjectNode n : flList){
//			String flId = n.get("id").asText();
//			for(ObjectRelation r : relList){
//				if(r.getObjTo().equals(flId)){
//					n.put("buildingId", r.getObjFrom());
//					relList.remove(r);
//					break;
//				}
//			}
//		}
//
//		HashMap<String, Object> data = new HashMap<>();
//		data.put("projects", prjList);
//		data.put("buildings", bdList);
//		data.put("floors", flList);
//		return AdmResult.success(data);

		return AdmResult.success(syncApp.downloadFrameData(req.getGroupCode(), req.getProjectId(), req.getUserId()));
	}

	@RequestMapping("/download")
	public AdmResult<DownLoadData> download(@RequestBody AdmRequest req){
		DownLoadData data;
		if(StrUtil.isNotBlank(req.getBuildingId())) {
			if(ServiceUtil.SYNC_APP_IMPL.equals("syncAppImpl")) //临时兼容
				data = syncApp.downloadBuildingData(req.getGroupCode(), req.getProjectId(), req.getUserId(), req.getClientId(), req.getBuildingId(), req.getBdtpDownloadTs(), req.getAdmDownloadTs());
			else
				data = syncApp.downloadBuildingData(req.getProjectId(), req.getBuildingId(), req.getUploadFlag(), req.getLastDownloadTime());
		} else
			data = syncApp.downloadProjectData(req.getGroupCode(), req.getProjectId(), req.getUserId(), req.getClientId(), req.getBdtpDownloadTs(), req.getAdmDownloadTs());
		return AdmResult.success(data);
	}

//	@RequestMapping("/downloadFl")
//	public AdmResult<Map<String, Object>> downloadFl(@RequestBody AdmRequest req){
//		return AdmResult.success(syncApp.downloadFloorData(req.getProjectId(), req.getFloorId(), req.getUploadFlag(), req.getLastDownloadTime()));
//	}

	@RequestMapping("/downloadMap")
	public void downloadMap(HttpServletRequest request, HttpServletResponse response, @RequestParam String key){
		InputStream inputStream = null;
		try {
			Response serviceResponse;
			if(ServiceUtil.SYNC_APP_IMPL.equals("syncAppImpl")) //临时兼容
				serviceResponse = imageServiceClient.fileGet(key, "revit");
			else
				serviceResponse = admClient.getFloorMap(key, "revit");

			Response.Body body = serviceResponse.body();

			inputStream = body.asInputStream();
			BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
			Object o = serviceResponse.headers().get("Content-Disposition");
			String contentDisposition = o != null ? o.toString().replace("[","").replace("]","") : "attachment;filename=map.jsonz";
			response.setHeader("Content-Disposition", contentDisposition);
			BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
			int length = 0;
			byte[] temp = new byte[1024 * 10];
			while ((length = bufferedInputStream.read(temp)) != -1) {
				bufferedOutputStream.write(temp, 0, length);
			}
			bufferedOutputStream.flush();
			bufferedOutputStream.close();
			bufferedInputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@RequestMapping("/upload")
	public AdmResult<UploadRtn> upload(HttpServletRequest request){
		AdmRequest admRequest = dataTxHandler.handleRequest(request);
		if(ServiceUtil.SYNC_APP_IMPL.equals("syncAppImpl")) //临时兼容
			return AdmResult.success(syncApp.uploadData(admRequest.getUploadData(), admRequest.getGroupCode(), admRequest.getProjectId(), admRequest.getUserId(), admRequest.getClientId()));
		else
			return AdmResult.success(syncApp.uploadData(admRequest.getUploadData(), admRequest.getGroupCode(), admRequest.getProjectId(), admRequest.getUserId(), admRequest.getUploadFlag()));
	}

	@PostMapping("/uploadFile")
	public AdmResult uploadFile(){
		//TODO
		return null;
	}

}
