package com.yc.ship.module.trade.utils;

import cn.hutool.core.map.MapUtil;
import com.yc.ship.framework.common.lang.Asserts;
import com.yc.ship.framework.common.util.json.JsonUtils;
import com.yc.ship.framework.security.core.LoginUser;
import com.yc.ship.framework.security.core.util.SecurityFrameworkUtils;
import com.yc.ship.framework.tenant.core.context.TenantContextHolder;
import com.yc.ship.module.ota.api.OtaDistributorApi;
import com.yc.ship.module.ota.api.dto.DistributorRespDTO;
import com.yc.ship.module.otc.api.agency.AgencyAuthApi;
import com.yc.ship.module.otc.api.agency.dto.AgencyUserLoginInfoReqDTO;
import com.yc.ship.module.otc.api.agency.dto.AgencyUserLoginInfoRespDTO;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * &#064;Description ：旅行社认证服务工具
 *
 * @author ：qsl
 * &#064;Date ：2025/6/11 10:33
 */
@Component
public class AgencyAuthUtils {

    @Resource
    private AgencyAuthApi agencyAuthApi;

    @Resource
    private OtaDistributorApi otaDistributorApi;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    private final static String AGENCY_LOGIN_INFO_KEY = "agency_login_info:%s:%s";
    public final static String AGENCY_LOGIN_INFO = "agencyLoginInfo";
    public final static String DISTRIBUTOR_LOGIN_INFO = "distributorLoginInfo";

    public LoginUser getAgencyLoginUser() {
        //获取当前登录用户
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        if (loginUser != null) {
            loginUser.setDistributorId(MapUtil.getLong(loginUser.getInfo(), LoginUser.INFO_KEY_DISTRIBUTOR_ID));
            loginUser.setStoreId(MapUtil.getLong(loginUser.getInfo(), LoginUser.INFO_KEY_STORE_ID));
        }
        if (loginUser != null && loginUser.getDistributorId() != null) {
            AgencyUserLoginInfoRespDTO agencyLoginInfo = getAgencyLoginInfoFromCache(loginUser.getId(), loginUser.getAccessToken());
            if (agencyLoginInfo == null) {
                AgencyUserLoginInfoReqDTO reqDTO = new AgencyUserLoginInfoReqDTO();
                reqDTO.setUserId(loginUser.getId());
                reqDTO.setAccessToken(loginUser.getAccessToken());
                agencyLoginInfo = agencyAuthApi.getStoreSellerLoginInfo(reqDTO);
                setAgencyLoginInfo(agencyLoginInfo, loginUser);
            }
            loginUser.setContext(AGENCY_LOGIN_INFO, agencyLoginInfo);
        }
        return loginUser;
    }

    public Long getLoginStoreId() {
        return SecurityFrameworkUtils.getLoginStoreId();
    }

    public LoginUser getLoginUser() {
        //获取当前登录用户
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        if (loginUser == null) {
            return null;
        }
        AgencyUserLoginInfoRespDTO agencyLoginInfo = getAgencyLoginInfoFromCache(loginUser.getId(), loginUser.getAccessToken());
        if (agencyLoginInfo == null) {
            AgencyUserLoginInfoReqDTO reqDTO = new AgencyUserLoginInfoReqDTO();
            reqDTO.setUserId(loginUser.getId());
            reqDTO.setAccessToken(loginUser.getAccessToken());
            Long tenantId = TenantContextHolder.getTenantId();
            try {
                TenantContextHolder.setTenantId(loginUser.getTenantId());
                agencyLoginInfo = agencyAuthApi.getStoreSellerLoginInfo(reqDTO);
                setAgencyLoginInfo(agencyLoginInfo, loginUser);
            } finally {
                TenantContextHolder.setTenantId(tenantId);
            }
        }
        loginUser.setContext(AGENCY_LOGIN_INFO, agencyLoginInfo);
        return loginUser;
    }

    public DistributorRespDTO getLoginUserDistributorData() {
        LoginUser loginUser = getDistributorLoginUser();
        return loginUser.getContext(DISTRIBUTOR_LOGIN_INFO, DistributorRespDTO.class);
    }

    public LoginUser getDistributorLoginUser() {
        //获取当前登录用户
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        Asserts.isTrue(loginUser != null, "无登录信息，请先登录");
        DistributorRespDTO distributorRespDTO = getDistributorData(loginUser);
        loginUser.setContext(DISTRIBUTOR_LOGIN_INFO, distributorRespDTO);
        return loginUser;
    }

    @Cacheable(cacheNames = "getDistributorData#300", key = "#loginUser.id")
    public DistributorRespDTO getDistributorData(LoginUser loginUser) {
        AgencyUserLoginInfoReqDTO reqDTO = new AgencyUserLoginInfoReqDTO();
        reqDTO.setUserId(loginUser.getId());
        reqDTO.setAccessToken(loginUser.getAccessToken());
        return otaDistributorApi.getDistributorByLoginUserId(loginUser.getId());
    }


    private AgencyUserLoginInfoRespDTO getAgencyLoginInfoFromCache(Long userId, String token) {
        String key = String.format(AGENCY_LOGIN_INFO_KEY, userId, token);
        return JsonUtils.parseObject(stringRedisTemplate.opsForValue().get(key), AgencyUserLoginInfoRespDTO.class);
    }

    private void setAgencyLoginInfo(AgencyUserLoginInfoRespDTO agencyLoginInfo, LoginUser loginUser) {
        String key = String.format(AGENCY_LOGIN_INFO_KEY, loginUser.getId(), loginUser.getAccessToken());
        stringRedisTemplate.opsForValue().set(key, JsonUtils.toJsonString(agencyLoginInfo), 600, TimeUnit.SECONDS);
    }


}
