package bus.service.impl;


import com.orcas.common.model.ValueLabelObject;
import com.orcas.common.sso.model.LoginRequest;
import com.orcas.common.sso.model.SsoUserAuthDto;
import com.orcas.dictionary.common.config.CodeClient;
import com.orcas.dictionary.common.dto.JsonAreaDto;
import com.orcas.dictionary.common.dto.JsonCodeDto;
import com.orcas.dictionary.common.model.JsonCodeParam;
import com.orcas.iso.service.SsoClient;
import bus.model.dto.CommonLoginDto;
import bus.service.CommonService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
* @Program: bus
* @Description: 描述
* @Author: zy
* @Date: 2025-03-06 22:43:32
**/
@Service
@Transactional
public class CommonServiceImpl implements CommonService {

	@Autowired
	private SsoClient ssoClient;

	@Value("${orcas.productNo}")
	private String productNo;

	@Value("${orcas.expireMinute:30}")
	private Integer expireMinute;

	@Autowired
	private CodeClient codeClient;

	@Override
	public List<ValueLabelObject> getDataDict(String dictCode) {
		if (StringUtils.isBlank(dictCode)) {
			return Collections.emptyList();
		}
		JsonCodeParam param = new JsonCodeParam();
		param.setProductNo(productNo);
		param.setBigCodeKeys(Collections.singletonList(dictCode));
		List<JsonCodeDto> dtos = codeClient.getCodeList(param);
		if (CollectionUtils.isEmpty(dtos) || CollectionUtils.isEmpty(dtos.get(0).getJsonCodeChildes())) {
			return Collections.emptyList();
		}
		return dtos.get(0).getJsonCodeChildes().stream()
				.map(child -> new ValueLabelObject(child.getCodeKey(), child.getCodeName()))
				.collect(Collectors.toList());
	}


	@Override
	public SsoUserAuthDto doLogin(HttpServletRequest request, HttpServletResponse response, CommonLoginDto userLoginRequest) {
		Assert.hasText(userLoginRequest.getAccount(), "账号不能为空！");
		Assert.hasText(userLoginRequest.getPassword(), "密码不能为空！");

		LoginRequest loginRequest = new LoginRequest();
		loginRequest.setAccountName(userLoginRequest.getAccount());
		loginRequest.setAccountPassword(userLoginRequest.getPassword());
		loginRequest.setExpireMinute(expireMinute);
		loginRequest.setTimeStamp(System.currentTimeMillis()+"");

		SsoUserAuthDto ssoUserAuthDto= ssoClient.doLogin(request,response,loginRequest);
		return ssoUserAuthDto;
	}

	@Override
	public List<JsonAreaDto> getAreaDict() {
		return codeClient.getJsonAreaTreeList();
	}
}
