package com.jeequan.jeepay.mch.ctrl.anon;

import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.db.entity.AgentConfig;
import com.jeequan.jeepay.mch.ctrl.CommonCtrl;
import com.jeequan.jeepay.service.impl.AgentConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 服务政策 隐私协议ctrl
 *
 * @author xiaoyu
 * 
 * @date 2022/2/16 14:51
 */
@RestController
@RequestMapping("/api/anon/treaty")
public class TreatyController extends CommonCtrl {

	@Autowired
	private AgentConfigService agentConfigService;


	@GetMapping(value = "")
	public ApiRes getTreaty() throws BizException {
		Map<String,Object> result = new HashMap<>();
		//获取域名
		String headerDomainName = getdomainName();
		if (headerDomainName != null && headerDomainName.contains("//")) {
			int startIndex = headerDomainName.indexOf("//") + 2; // 获取第一个 "//" 后的位置
			int endIndex = headerDomainName.indexOf("/", startIndex); // 获取从 startIndex 开始的第一个 "/"
			if (endIndex != -1) {
				String domainName = headerDomainName.substring(startIndex, endIndex);
				AgentConfig agentConfig = agentConfigService.getOne(AgentConfig.gw().eq(AgentConfig::getGroupKey, "agentSiteConfig")
						.eq(AgentConfig::getConfigVal,domainName)
						.last("limit 1"));
				if (agentConfig == null){
					//该域名没配置，取总后台数据
					return ApiRes.ok(sysConfigService.getTreatyConfig());
				}
				List<AgentConfig> treatyConfigList = agentConfigService.list(AgentConfig.gw().eq(AgentConfig::getGroupKey, "treatyConfig")
						.eq(AgentConfig::getAgentNo,agentConfig.getAgentNo()));
				if(treatyConfigList.isEmpty()){
					//贴牌数据为空，取总后台数据
					return ApiRes.ok(sysConfigService.getTreatyConfig());
				}else {
					for (AgentConfig config : treatyConfigList) {
						result.put(config.getConfigKey(), config.getConfigVal());
					}
					return ApiRes.ok(result);
				}
			}
		}
		return ApiRes.ok(sysConfigService.getTreatyConfig());

	}

}
