package com.persagy.adm.server.custom.controller;

import cn.hutool.core.util.StrUtil;
import com.persagy.adm.server.custom.common.AdmRequest;
import com.persagy.adm.server.custom.datatx.DataTxHandler;
import com.persagy.adm.server.custom.entity.ConfigData;
import com.persagy.adm.server.custom.entity.Dict;
import com.persagy.adm.server.custom.entity.DownLoadData;
import com.persagy.adm.server.custom.entity.UploadRtn;
import com.persagy.adm.server.custom.service.ISyncApp;
import com.persagy.adm.server.custom.service.ServiceUtil;
import com.persagy.dmp.common.model.response.CommonResult;
import com.persagy.dmp.common.utils.ResultHelper;
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 java.util.HashMap;
import java.util.Map;

/**
 * APP离线数据服务
 */
@RestController
@RequestMapping("/adm")
public class AppController {

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

	@Autowired
	private DataTxHandler dataTxHandler;

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

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

	@RequestMapping("/config")
	public CommonResult<ConfigData> config(@RequestBody AdmRequest req){
		return ResultHelper.single(syncApp.downloadConfig(req.getGroupCode(), req.getProjectId(), req.getUserId()));
	}

	@RequestMapping("/frame")
	public CommonResult<Map<String, Object>> frame(@RequestBody AdmRequest req){
		return ResultHelper.single(syncApp.downloadFrameData(req.getGroupCode(), req.getProjectId(), req.getUserId()));
	}

	@RequestMapping("/download")
	public CommonResult<DownLoadData> download(@RequestBody AdmRequest req){
		DownLoadData data;
		if(StrUtil.isNotBlank(req.getBuildingId())) {
			data = syncApp.downloadBuildingData(req.getGroupCode(), req.getProjectId(), req.getUserId(), req.getClientId(), req.getBuildingId(), req.getBdtpDownloadTs(), req.getAdmDownloadTs());
		} else
			data = syncApp.downloadProjectData(req.getGroupCode(), req.getProjectId(), req.getUserId(), req.getClientId(), req.getBdtpDownloadTs(), req.getAdmDownloadTs());
		return ResultHelper.single(data);
	}


	@RequestMapping("/upload")
	public CommonResult<UploadRtn> upload(HttpServletRequest request){
		AdmRequest admRequest = dataTxHandler.handleRequest(request);
		return ResultHelper.single(syncApp.uploadData(admRequest.getUploadData(), admRequest.getGroupCode(), admRequest.getProjectId(), admRequest.getUserId(), admRequest.getClientId()));
	}

}
