
package com.tmerclub.cloud.common.security.adapter;

import cn.hutool.core.util.StrUtil;
import com.tmerclub.cloud.api.auth.bo.UidInfoBO;
import com.tmerclub.cloud.api.auth.constant.SysTypeEnum;
import com.tmerclub.cloud.api.auth.feign.AccountFeignClient;
import com.tmerclub.cloud.api.auth.vo.AuthAccountVO;
import com.tmerclub.cloud.common.constant.Constant;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;

/**
 * @author TRACK
 */
@Component
public class DefaultSignAuthAdapter {
    private static final Logger logger = LoggerFactory.getLogger(DefaultSignAuthAdapter.class);

    @DubboReference
    private AccountFeignClient accountFeignClient;

    public ServerResponseEntity<UidInfoBO> loadUserInfoInToken(Map<String, Object> dataMap) {
        UidInfoBO uidInfoBO = new UidInfoBO();
        if (dataMap.isEmpty()) {
            return ServerResponseEntity.success(uidInfoBO);
        }
        Object sysType = dataMap.get("sysType");
        if (Objects.isNull(sysType) || Objects.isNull(SysTypeEnum.instance(sysType.toString()))) {
            return ServerResponseEntity.showFailMsg("sysType is empty or wrong");
        }
        SysTypeEnum sysTypeEnum = SysTypeEnum.instance(sysType.toString());
        ServerResponseEntity<UidInfoBO> response = getUserInfoInTokenServerResponseEntity(dataMap, uidInfoBO, sysTypeEnum);
        if (Objects.nonNull(response)) {
            return response;
        }
        return ServerResponseEntity.success(uidInfoBO);
    }

    private ServerResponseEntity<UidInfoBO> getUserInfoInTokenServerResponseEntity(Map<String, Object> dataMap, UidInfoBO uidInfoBO, SysTypeEnum sysTypeEnum) {
        // 用户端
        if (Objects.equals(sysTypeEnum, SysTypeEnum.ORDINARY)) {
            logger.info("用户端签名验签:{}", dataMap);
            Object userIdObj = dataMap.get("userId");
            if (Objects.nonNull(userIdObj) && StrUtil.isNotBlank(userIdObj.toString())) {
                ServerResponseEntity<AuthAccountVO> response = accountFeignClient.getByUserIdAndType(Long.valueOf(userIdObj.toString()), SysTypeEnum.ORDINARY.value());
                if (!response.isSuccess()) {
                    return ServerResponseEntity.showFailMsg(response.getMsg());
                }
                if (Objects.isNull(response.getData())) {
                    return ServerResponseEntity.showFailMsg("userId is error");
                }
                getUserToken(uidInfoBO, response);
            }
        }
        // 商家
        else if (Objects.equals(sysTypeEnum, SysTypeEnum.MULTISHOP)) {
            logger.info("商家端签名验签:{}", dataMap);
            long shopId = getShopId(dataMap);
            // 默认是店铺超级管理员
            ServerResponseEntity<AuthAccountVO> response = accountFeignClient.getBySysTypeAndIsAdminAndTenantId(SysTypeEnum.MULTISHOP.value(), 1, shopId);
            if (!response.isSuccess()) {
                return ServerResponseEntity.showFailMsg(response.getMsg());
            }
            if (Objects.isNull(response.getData())) {
                return ServerResponseEntity.showFailMsg("shopId is error");
            }
            getTenantUserInfoToken(uidInfoBO, sysTypeEnum, response, shopId);
        }
        // 平台
        else if (Objects.equals(sysTypeEnum, SysTypeEnum.PLATFORM)) {
            logger.info("平台端签名验签:{}", dataMap);
            long sysUserId = getSysUserId(dataMap);
            ServerResponseEntity<AuthAccountVO> response = accountFeignClient.getByUserIdAndType(sysUserId, SysTypeEnum.PLATFORM.value());
            if (!response.isSuccess()) {
                return ServerResponseEntity.showFailMsg(response.getMsg());
            }
            if (Objects.isNull(response.getData())) {
                return ServerResponseEntity.showFailMsg("sysUserId is error");
            }
            getPlatformToken(uidInfoBO, response);
        }
        // 供应商
        else if (Objects.equals(sysTypeEnum, SysTypeEnum.SUPPLIER)) {
            logger.info("供应商端签名验签:{}", dataMap);
            Object supplierIdObj = dataMap.get("supplierId");
            if (Objects.nonNull(supplierIdObj) && StrUtil.isNotBlank(supplierIdObj.toString())) {
                Long supplierId = Long.valueOf(supplierIdObj.toString());
                // 默认是超级管理员
                ServerResponseEntity<AuthAccountVO> response = accountFeignClient.getBySysTypeAndIsAdminAndTenantId(SysTypeEnum.SUPPLIER.value(), 1, supplierId);
                if (!response.isSuccess()) {
                    return ServerResponseEntity.showFailMsg(response.getMsg());
                }
                if (Objects.isNull(response.getData())) {
                    return ServerResponseEntity.showFailMsg("supplierId is error");
                }
                getTenantUserInfoToken(uidInfoBO, sysTypeEnum, response, supplierId);
            }
        }
        // 自提
        else if (Objects.equals(sysTypeEnum, SysTypeEnum.STATION)) {
            logger.info("自提端签名验签:{}", dataMap);
            Object stationIdObj = dataMap.get("stationId");
            if (Objects.nonNull(stationIdObj) && StrUtil.isNotBlank(stationIdObj.toString())) {
                Long stationId = Long.valueOf(stationIdObj.toString());
                // 默认是超级管理员
                ServerResponseEntity<AuthAccountVO> response = accountFeignClient.getBySysTypeAndIsAdminAndTenantId(sysTypeEnum.value(), 1, stationId);
                if (!response.isSuccess()) {
                    return ServerResponseEntity.showFailMsg(response.getMsg());
                }
                if (Objects.isNull(response.getData())) {
                    return ServerResponseEntity.showFailMsg("stationId is error");
                }
                getTenantUserInfoToken(uidInfoBO, sysTypeEnum, response, stationId);
            }
        }
        return null;
    }

    private static long getShopId(Map<String, Object> dataMap) {
        Object shopIdObj = dataMap.get("shopId");
        long shopId = Constant.MAIN_SHOP;
        if (Objects.nonNull(shopIdObj) && StrUtil.isNotBlank(shopIdObj.toString())) {
            shopId = Long.parseLong(shopIdObj.toString());
        }
        return shopId;
    }

    private static long getSysUserId(Map<String, Object> dataMap) {
        Object sysUserIdObj = dataMap.get("sysUserId");
        // 默认是平台超级管理员
        long sysUserId = Constant.SUPER_ADMIN_ID;
        if (Objects.nonNull(sysUserIdObj) && StrUtil.isNotBlank(sysUserIdObj.toString())) {
            sysUserId = Long.parseLong(sysUserIdObj.toString());
        }
        return sysUserId;
    }

    private static void getUserToken(UidInfoBO uidInfoBO, ServerResponseEntity<AuthAccountVO> response) {
        AuthAccountVO authAccountVO = response.getData();
        uidInfoBO.setUserId(authAccountVO.getUserId());
        uidInfoBO.setAccountUid(authAccountVO.getUid());
        uidInfoBO.setIsAdmin(0);
        uidInfoBO.setUsername(authAccountVO.getUsername());
        uidInfoBO.setSysType(SysTypeEnum.ORDINARY.value());
    }

    private static void getPlatformToken(UidInfoBO uidInfoBO, ServerResponseEntity<AuthAccountVO> response) {
        AuthAccountVO authAccountVO = response.getData();
        uidInfoBO.setUserId(authAccountVO.getUserId());
        uidInfoBO.setTenantId(Constant.PLATFORM_SHOP_ID);
        uidInfoBO.setAccountUid(authAccountVO.getUid());
        uidInfoBO.setIsAdmin(authAccountVO.getIsAdmin());
        uidInfoBO.setUsername(authAccountVO.getUsername());
        uidInfoBO.setSysType(SysTypeEnum.PLATFORM.value());
    }

    private static void getTenantUserInfoToken(UidInfoBO uidInfoBO, SysTypeEnum sysTypeEnum, ServerResponseEntity<AuthAccountVO> response, Long tenantId) {
        AuthAccountVO authAccountVO = response.getData();
        uidInfoBO.setUserId(authAccountVO.getUserId());
        uidInfoBO.setTenantId(tenantId);
        uidInfoBO.setAccountUid(authAccountVO.getUid());
        uidInfoBO.setIsAdmin(1);
        uidInfoBO.setUsername(authAccountVO.getUsername());
        uidInfoBO.setIsPassShop(authAccountVO.getIsPassShop());
        uidInfoBO.setSysType(sysTypeEnum.value());
    }
}
