package com.qunzhixinxi.hnqz.admin.aspect;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qunzhixinxi.hnqz.admin.api.constant.CacheConstants;
import com.qunzhixinxi.hnqz.admin.api.entity.SysDept;
import com.qunzhixinxi.hnqz.admin.api.entity.SysSocialDetails;
import com.qunzhixinxi.hnqz.admin.api.entity.SysUser;
import com.qunzhixinxi.hnqz.admin.mapper.SysSocialDetailsMapper;
import com.qunzhixinxi.hnqz.common.core.constant.enums.LoginTypeEnum;
import com.qunzhixinxi.hnqz.common.taxhelper.annotation.TaxHelper;
import com.qunzhixinxi.hnqz.common.taxhelper.config.TaxHelperConfig;
import com.qunzhixinxi.hnqz.common.taxhelper.entity.model.TaxHelperLoginModel;
import com.qunzhixinxi.hnqz.common.taxhelper.entity.model.TaxHelperModel;
import com.qunzhixinxi.hnqz.common.taxhelper.entity.request.TaxHelperLoginRequest;
import com.qunzhixinxi.hnqz.common.taxhelper.entity.request.TaxHelperRequest;
import com.qunzhixinxi.hnqz.common.taxhelper.entity.response.TaxHelperResponse;
import com.qunzhixinxi.hnqz.common.taxhelper.service.TaxHelperService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * {@code TaxHelperAdvice} 税邦云通知，用户前置登录操作
 *
 * @author Hengchen.Sun
 * @version 1.0.0
 * @date 2021-02-24
 * @since ver.1.0.0
 */
@Aspect
@Component
@AllArgsConstructor
@Slf4j
public class TaxHelperAspect {

	private final TaxHelperService taxHelperService;
	private final RedisTemplate redisTemplate;
	private final SysSocialDetailsMapper sysSocialDetailsMapper;

	@Pointcut(value = "@annotation(com.qunzhixinxi.hnqz.common.taxhelper.annotation.TaxHelper)")
	public void doBeforeOperation() {
		log.warn("税邦云业务前置登录操作");
	}

	@Before("doBeforeOperation()")
	public void before(JoinPoint joinPoint) {

		// 获取税邦云登录key
		SysSocialDetails condition = new SysSocialDetails();
		condition.setType(LoginTypeEnum.TAX_HELPER.getType());
		SysSocialDetails socialDetails = sysSocialDetailsMapper.selectOne(new QueryWrapper<>(condition));
		String randomKey = socialDetails.getRandomKey();

		// 获取request
		TaxHelperRequest request = null;
		Object[] args = joinPoint.getArgs();
		for (Object arg : args) {
			if (arg instanceof TaxHelperRequest) {
				request = (TaxHelperRequest) arg;
				// 设置登录时的key
				request.setKey(randomKey);
				break;
			}
		}

		// 税邦云登录有效期是2小时，如果缓存为null，则重新登录
		TaxHelperModel model = request.getBizModel();
		final String cacheKey = CacheConstants.TAX_HELPER_LOGIN_KEY + model.getAppId();
		if (!redisTemplate.hasKey(cacheKey)) {

			// 封装税邦云账号
			TaxHelperConfig taxHelperConfig = new TaxHelperConfig();
			taxHelperConfig.setAppId(model.getAppId());
			taxHelperConfig.setAppSecrete(model.getAppSecrete());
			taxHelperConfig.setQueryUrl(model.getQueryUrl());

			TaxHelperLoginModel loginModel = new TaxHelperLoginModel(taxHelperConfig);
			TaxHelperLoginRequest loginRequest = new TaxHelperLoginRequest(loginModel);
			loginRequest.setKey(randomKey);
			TaxHelperResponse loginResponse = taxHelperService.login(loginRequest);
			if (loginResponse.success()) {
				// 缓存登录的秘钥（随机秘钥全程唯一），过期时间为2小时
				redisTemplate.opsForValue().set(cacheKey, randomKey, 2, TimeUnit.HOURS);
			} else {
				throw new RuntimeException("税邦云登录异常：【" + loginResponse.getMessage() + "】");
			}
		}
	}
}
