package com.hotent.portal.persistence.manager.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.hotent.base.context.BaseContext;
import com.hotent.base.feign.UCFeignService;
import com.hotent.base.model.CommonResult;
import com.hotent.base.util.AppUtil;
import com.hotent.base.util.BeanUtils;
import com.hotent.portal.model.PortalBizSystem;
import com.hotent.portal.model.PortalBizSystemAuth;
import com.hotent.portal.persistence.dao.PortalBizSystemAuthDao;
import com.hotent.portal.persistence.manager.PortalBizSystemAuthManager;
import com.hotent.base.manager.impl.BaseManagerImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *  服务实现类
 *
 * @company 广州宏天软件股份有限公司
 * @author cola
 * @since 2021-12-03
 */
@Service
public class PortalBizSystemAuthManagerImpl extends BaseManagerImpl<PortalBizSystemAuthDao, PortalBizSystemAuth> implements PortalBizSystemAuthManager {

	private Logger logger= LoggerFactory.getLogger(PortalBizSystemAuthManagerImpl.class);

	@Autowired
	private BaseContext baseContext;
	@Autowired
	private PortalBizSystemAuthDao portalBizSystemAuthDao;

	@Override
	public PortalBizSystemAuth getDetail(String id) {
    	PortalBizSystemAuth portalBizSystemAuth = this.get(id);
		return portalBizSystemAuth;
	}
	@Override
	@Transactional
	public void createOrUpdate(PortalBizSystemAuth portalBizSystemAuth) {
		//新建或更新
		this.saveOrUpdate(portalBizSystemAuth);
	}

	@Override
	public void batchSave(PortalBizSystem portalBizSystem) {
		UCFeignService ucFeignService = AppUtil.getBean(UCFeignService.class);
		if (BeanUtils.isEmpty(portalBizSystem.getManagerList())){
			return;
		}
		for (PortalBizSystemAuth manager : portalBizSystem.getManagerList()) {
			PortalBizSystemAuth auth = new PortalBizSystemAuth();
			auth.setCreateBy(baseContext.getCurrentUserId());
			auth.setManagerId(manager.getManagerId());
			auth.setManagerName(manager.getManagerName());
			auth.setIsDele("0");
			auth.setSysName(portalBizSystem.getSysName());
			auth.setSysCode(portalBizSystem.getSysCode());
			auth.setCreateOrgId(baseContext.getCurrentOrgId());
			CommonResult<JsonNode> user = ucFeignService.getUserById(manager.getManagerId());
			auth.setAccount(user.getValue().get("account").asText());
			try {
				portalBizSystemAuthDao.insert(auth);
			}catch (Exception e){
				if(e instanceof DuplicateKeyException){
					// 唯一索引的预期异常
					logger.error("插入管理员授权时，出现异常：{}",e.getMessage());
				}else {
					throw e;
				}
			}
		}
	}


}
