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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.hash.Hashing;
import com.hotent.base.conf.SaaSConfig;
import com.hotent.base.constants.SystemConstants;
import com.hotent.base.context.BaseContext;
import com.hotent.base.handler.MultiTenantHandler;
import com.hotent.base.handler.MultiTenantIgnoreResult;
import com.hotent.base.jwt.JwtTokenHandler;
import com.hotent.base.model.CommonResult;
import com.hotent.base.query.PageBean;
import com.hotent.base.query.PageList;
import com.hotent.base.query.QueryFilter;
import com.hotent.base.query.QueryOP;
import com.hotent.base.util.AppUtil;
import com.hotent.base.util.BeanUtils;
import com.hotent.base.util.StringUtil;
import com.hotent.base.util.UniqueIdUtil;
import com.hotent.base.util.time.TimeUtil;
import com.hotent.uc.api.impl.util.ContextUtil;
import com.hotent.uc.api.model.IUser;
import com.hotent.uc.api.service.IUserService;
import org.springframework.stereotype.Service;

import com.hotent.base.manager.impl.BaseManagerImpl;
import com.hotent.portal.model.ShorturlManage;
import com.hotent.portal.persistence.dao.ShorturlManageDao;
import com.hotent.portal.persistence.manager.ShorturlManageManager;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

/**
 *  服务实现类
 *
 * @company 广州宏天软件股份有限公司
 * @author 超级管理员
 * @since 2020-12-01
 */
@Service
public class ShorturlManageManagerImpl extends BaseManagerImpl<ShorturlManageDao, ShorturlManage> implements ShorturlManageManager {
	@Resource
	JwtTokenHandler jwtTokenHandler;
	@Resource
	SaaSConfig saaSConfig;
	@Resource
	BaseContext baseContext;

	@Override
	public ShorturlManage getByShortUrl(String shortUrl) {
		return baseMapper.getByShortUrl(shortUrl);
	}

	@Override
	public CommonResult<ShorturlManage> getLongUrlByShortUrl(String shortUrl) throws Exception{
		ShorturlManage shortUrlManage = null;
		if(saaSConfig.isEnable()){
			//由于这里是未登录状态，也无法获取租户ID，只能通过短链接的租户ID来识别租户。
			try(MultiTenantIgnoreResult multiTenantIgnoreResult = MultiTenantHandler.setThreadLocalIgnore()) {
				QueryWrapper<ShorturlManage> wrapper = new QueryWrapper<>();
				wrapper.eq("SHORT_URL_", shortUrl);
				shortUrlManage = getOne(wrapper);
			}
		}else{
			shortUrlManage = getByShortUrl(shortUrl);
		}

		String errorMsg = "";
		if (BeanUtils.isEmpty(shortUrlManage)) {
			errorMsg = "2";
		} else if ("2".equals(shortUrlManage.getEnabled())) {
			errorMsg = "3";
		} else if (BeanUtils.isNotEmpty(shortUrlManage.getLoseTime()) && TimeUtil.getTimeMillis(shortUrlManage.getLoseTime())< TimeUtil.getTimeMillis(LocalDateTime.now())) {
			errorMsg = "4";
		}
		if (StringUtil.isNotEmpty(errorMsg)) {
			return new CommonResult<>(false, errorMsg);
		}
		if (saaSConfig.isEnable()) {
			//设置当前的租户ID
			baseContext.setTempTenantId(shortUrlManage.getTenantId());
			IUserService userService = AppUtil.getBean(IUserService.class);
			IUser userByAccount = userService.getUserByAccount(SystemConstants.GUEST_ACCOUNT);
			shortUrlManage.setGuestToken(jwtTokenHandler.generateToken(userByAccount));
		}else{
			shortUrlManage.setGuestToken(jwtTokenHandler.generateToken(SystemConstants.GUEST_ACCOUNT));
		}


		return new CommonResult<>(true, "获取成功", shortUrlManage);
	}

	@Override
	public CommonResult<ShorturlManage> getShortUrlByLong(ShorturlManage vo) {
		CommonResult<ShorturlManage> rtn = null;
		try {
			String shourtUrl = "";
			if(saaSConfig.isEnable()){
				//不同租户下，可能会生成多个相同的短链接
				shourtUrl = "surl/" + Hashing.murmur3_32().hashString(vo.getUrl() + ContextUtil.getCurrentUser().getTenantId(), StandardCharsets.UTF_8).toString();
			}else{
				shourtUrl = "surl/" + Hashing.murmur3_32().hashString(vo.getUrl(), StandardCharsets.UTF_8).toString();
			}

			QueryFilter<ShorturlManage> queryFilter = QueryFilter.build();
			queryFilter.withPage(new PageBean(1, -1));
			queryFilter.addFilter("short_url_", shourtUrl, QueryOP.RIGHT_LIKE);
			PageList<ShorturlManage> query = query(queryFilter);
			//如果生成的短链接已存在，并且长url和当前url一致。则直接返回已有配置
			if (BeanUtils.isNotEmpty(query) && BeanUtils.isNotEmpty(query.getRows())) {
				for (ShorturlManage shorturlManage : query.getRows()) {
					if (vo.getUrl().equals(shorturlManage.getUrl())) {
						return new CommonResult<ShorturlManage>(true, "获取短链接成功",shorturlManage);
					}
				}
				//短链接在库里已存在，但是长连接不一样。则为其拼接后缀，保证短链接的唯一性
				shourtUrl += query.getRows().size();
			}
			vo.setShortUrl(shourtUrl);
			vo.setId(UniqueIdUtil.getSuid());
			save(vo);
			rtn = new CommonResult<ShorturlManage>(true, "根据长连接获取！",vo);
		} catch (Exception e) {
			e.printStackTrace();
			rtn = new CommonResult<ShorturlManage>(false, "根据长连接获取!",null);
		}
		return rtn;
	}

}
