package shop.alien.util.type;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import shop.alien.entity.store.LawyerUser;
import shop.alien.entity.store.LifeUser;
import shop.alien.entity.store.StoreUser;
import shop.alien.mapper.LawyerUserMapper;
import shop.alien.mapper.LifeUserMapper;
import shop.alien.mapper.StoreUserMapper;

/**
 * phoneId（type_phone）解析工具：根据前缀查询对应用户表并返回 type + id
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class TypeUtil {

    /** 普通用户 life_user */
    private static final int TYPE_USER = 1;
    /** 商户 store_user */
    private static final int TYPE_STORE = 2;
    /** 律师 lawyer_user */
    private static final int TYPE_LAWYER = 3;

    private final LifeUserMapper lifeUserMapper;
    private final StoreUserMapper storeUserMapper;
    private final LawyerUserMapper lawyerUserMapper;

    /**
     * 根据 type_phone 格式的 phoneId 查询对应用户 id
     * <p>
     * 示例：user_13800138000 → life_user.user_phone = 13800138000 → {type:1, id:?}<br>
     * store_13800138000 → store_user.phone = 13800138000 → {type:2, id:?}<br>
     * lawyer_13800138000 → lawyer_user.phone = 13800138000 → {type:3, id:?}
     * </p>
     *
     * @param typePhone phoneId，格式为 type + "_" + 手机号
     * @return 解析成功返回 type 与 id；格式非法或未查到用户时返回 null
     */
    public PhoneTypeIdResult resolveTypeAndId(String typePhone) {
        if (!StringUtils.hasText(typePhone) || !typePhone.contains("_")) {
            log.warn("resolveTypeAndId 入参非法: typePhone={}", typePhone);
            return null;
        }

        String[] parts = typePhone.split("_", 2);
        if (parts.length < 2 || !StringUtils.hasText(parts[1])) {
            log.warn("resolveTypeAndId 无法解析手机号: typePhone={}", typePhone);
            return null;
        }

        String typePrefix = parts[0];
        String phone = parts[1];

        try {
            switch (typePrefix) {
                case "user":
                    return queryLifeUserId(phone);
                case "store":
                    return queryStoreUserId(phone);
                case "lawyer":
                    return queryLawyerUserId(phone);
                default:
                    log.warn("resolveTypeAndId 不支持的用户类型前缀: typePrefix={}, typePhone={}", typePrefix, typePhone);
                    return null;
            }
        } catch (Exception e) {
            log.error("resolveTypeAndId 查询失败: typePhone={}", typePhone, e);
            return null;
        }
    }

    private PhoneTypeIdResult queryLifeUserId(String phone) {
        LambdaQueryWrapper<LifeUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LifeUser::getUserPhone, phone)
                .eq(LifeUser::getDeleteFlag, 0)
                .last("LIMIT 1");
        LifeUser lifeUser = lifeUserMapper.selectOne(wrapper);
        if (lifeUser == null) {
            log.warn("未找到普通用户: phone={}", phone);
            return null;
        }
        log.debug("解析普通用户成功: phone={}, id={}", phone, lifeUser.getId());
        return new PhoneTypeIdResult(TYPE_USER, lifeUser.getId());
    }

    private PhoneTypeIdResult queryStoreUserId(String phone) {
        LambdaQueryWrapper<StoreUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StoreUser::getPhone, phone)
                .eq(StoreUser::getDeleteFlag, 0)
                .last("LIMIT 1");
        StoreUser storeUser = storeUserMapper.selectOne(wrapper);
        if (storeUser == null) {
            log.warn("未找到商户用户: phone={}", phone);
            return null;
        }
        log.debug("解析商户用户成功: phone={}, id={}", phone, storeUser.getId());
        return new PhoneTypeIdResult(TYPE_STORE, storeUser.getId());
    }

    private PhoneTypeIdResult queryLawyerUserId(String phone) {
        LambdaQueryWrapper<LawyerUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LawyerUser::getPhone, phone)
                .eq(LawyerUser::getDeleteFlag, 0)
                .last("LIMIT 1");
        LawyerUser lawyerUser = lawyerUserMapper.selectOne(wrapper);
        if (lawyerUser == null) {
            log.warn("未找到律师用户: phone={}", phone);
            return null;
        }
        log.debug("解析律师用户成功: phone={}, id={}", phone, lawyerUser.getId());
        return new PhoneTypeIdResult(TYPE_LAWYER, lawyerUser.getId());
    }

    public boolean containsUnderscore(String input) {
        if (input == null) {
            return false;
        }
        return input.contains("_");
    }
}
