package com.yh.saas.platform.service.impl;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.util.UriUtils;

import com.winsea.svc.base.security.util.AuthSecurityUtils;
import com.yh.saas.common.support.util.StringUtils;
import com.yh.saas.platform.properties.BIProperties;
import com.yh.saas.platform.service.IBIService;

/**
 * BI服务实现
 * 
 * @author SunTianjun
 */
@Service
public class BIServiceImpl implements IBIService {

	@Autowired
	private BIProperties.BIServerProperties serverProperties;

	@Autowired
	private BIProperties.BIReportProperties reportProperties;

	@Override
	public String getReportUrl(String operation, String reportName, String exportFormat, Map<String, String> params) {
		if (null == params) {
			params = new HashMap<>();
		}

		String reportSubPath = null;
		switch (operation) {
		case "view":
			reportSubPath = reportProperties.getView().get(reportName);
			params.put("op", "view");
			break;
		case "export":
			reportSubPath = reportProperties.getExport().get(reportName);
			params.put("format", !StringUtils.isEmpty(exportFormat) ? exportFormat : "excel");
			break;
		default:
			// do nothing
		}

		if (null == reportSubPath) {
			return null;
		}

		String compId = AuthSecurityUtils.getCurrentUserInfo().getCompId();
		String protocol = serverProperties.getProtocol();
		String ip = serverProperties.getIp();
		String port = serverProperties.getPort();
		String contextPath = serverProperties.getContextPath();
		String reportBasePath = serverProperties.getReportBasePath().replace("{compId}", compId);
		String reportPath = UriUtils.encode(reportBasePath + reportSubPath, "UTF-8");
		String paramsStr = params.entrySet().stream().map(entrySet -> entrySet.getKey() + "=" + entrySet.getValue())
				.collect(Collectors.joining("&"));

		return MessageFormat.format("{0}://{1}:{2}{3}?reportlet={4}&{5}", protocol, ip, port, contextPath, reportPath,
				paramsStr);
	}
}
