package shop.alien.store.util;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
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.LifeUserDynamics;
import shop.alien.entity.store.StoreUser;
import shop.alien.entity.store.vo.LifeUserDynamicsVo;
import shop.alien.mapper.LawyerUserMapper;
import shop.alien.mapper.LifeUserMapper;
import shop.alien.mapper.StoreUserMapper;
import shop.alien.util.type.PhoneTypeIdResult;
import shop.alien.util.type.TypeUtil;

import java.util.Objects;

/**
 * life_user_dynamics 发布人身份工具。
 * <p>
 * 入参：仅兼容前端传入的 legacy {@code phoneId}（解析为 type+refId）。<br>
 * 库表：查询/新增/修改只使用 {@code phone_user_type} + {@code phone_ref_id}，不读写 {@code phone_id} 列。<br>
 * 响应：由 type+refId 合成 {@code phoneId} 返回给前端。
 * </p>
 */
@Component
@RequiredArgsConstructor
public class LifeDynamicsIdentityHelper {

    public static final int TYPE_USER = 1;
    public static final int TYPE_STORE = 2;
    public static final int TYPE_LAWYER = 3;

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

    public static final class PublisherScope {
        private final String legacyPhoneId;
        private final Integer phoneUserType;
        private final Integer phoneRefId;

        public PublisherScope(String legacyPhoneId, Integer phoneUserType, Integer phoneRefId) {
            this.legacyPhoneId = legacyPhoneId;
            this.phoneUserType = phoneUserType;
            this.phoneRefId = phoneRefId;
        }

        public String getLegacyPhoneId() {
            return legacyPhoneId;
        }

        public Integer getPhoneUserType() {
            return phoneUserType;
        }

        public Integer getPhoneRefId() {
            return phoneRefId;
        }

        public boolean hasTypeRef() {
            return phoneUserType != null && phoneRefId != null;
        }

        public boolean isEmpty() {
            return !hasTypeRef();
        }
    }

    /** 将前端传入的 legacy phoneId 解析为 type+refId（仅入参侧兼容）。 */
    public PublisherScope resolveFromPhoneId(String phoneId) {
        if (!StringUtils.hasText(phoneId)) {
            return new PublisherScope(null, null, null);
        }
        String trimmed = phoneId.trim();
        if (!typeUtil.containsUnderscore(trimmed)) {
            return new PublisherScope(trimmed, null, null);
        }
        PhoneTypeIdResult resolved = typeUtil.resolveTypeAndId(trimmed);
        if (resolved == null) {
            return new PublisherScope(trimmed, null, null);
        }
        return new PublisherScope(trimmed, resolved.getType(), resolved.getId());
    }

    /** 从库表记录解析发布人（仅认 phone_user_type + phone_ref_id）。 */
    public PublisherScope resolveFromDynamics(LifeUserDynamics dynamics) {
        if (dynamics == null
                || dynamics.getPhoneUserType() == null
                || dynamics.getPhoneRefId() == null) {
            return new PublisherScope(null, null, null);
        }
        String legacy = buildLegacyPhoneId(dynamics.getPhoneUserType(), dynamics.getPhoneRefId());
        return new PublisherScope(legacy, dynamics.getPhoneUserType(), dynamics.getPhoneRefId());
    }

    /** 写入前：由前端 phoneId 或显式 type+refId 填充新字段，不落库 phone_id。 */
    public void normalizePublisherFields(LifeUserDynamics dynamics) {
        if (dynamics == null) {
            return;
        }
        if (dynamics.getPhoneUserType() == null || dynamics.getPhoneRefId() == null) {
            if (StringUtils.hasText(dynamics.getPhoneId())) {
                PhoneTypeIdResult resolved = typeUtil.resolveTypeAndId(dynamics.getPhoneId().trim());
                if (resolved != null) {
                    dynamics.setPhoneUserType(resolved.getType());
                    dynamics.setPhoneRefId(resolved.getId());
                }
            }
        }
        dynamics.setPhoneId(null);
    }

    public void applyPublisherFilter(LambdaQueryWrapper<LifeUserDynamics> wrapper, PublisherScope scope) {
        if (wrapper == null || scope == null || !scope.hasTypeRef()) {
            return;
        }
        wrapper.eq(LifeUserDynamics::getPhoneUserType, scope.getPhoneUserType())
                .eq(LifeUserDynamics::getPhoneRefId, scope.getPhoneRefId());
    }

    public void applyPublisherFilter(QueryWrapper<LifeUserDynamics> wrapper, PublisherScope scope) {
        applyPublisherFilter(wrapper, scope, null);
    }

    public void applyPublisherFilter(QueryWrapper<LifeUserDynamics> wrapper, PublisherScope scope, String tableAlias) {
        if (wrapper == null || scope == null || !scope.hasTypeRef()) {
            return;
        }
        String colPrefix = StringUtils.hasText(tableAlias) ? tableAlias + "." : "";
        wrapper.eq(colPrefix + "phone_user_type", scope.getPhoneUserType())
                .eq(colPrefix + "phone_ref_id", scope.getPhoneRefId());
    }

    public PublisherScope resolveStorePublisherByStorePhone(String storePhone) {
        if (!StringUtils.hasText(storePhone)) {
            return new PublisherScope(null, null, null);
        }
        String rawPhone = storePhone.trim();
        if (rawPhone.startsWith("store_")) {
            rawPhone = rawPhone.substring(6);
        }
        StoreUser storeUser = storeUserMapper.selectOne(
                new LambdaQueryWrapper<StoreUser>()
                        .eq(StoreUser::getPhone, rawPhone)
                        .eq(StoreUser::getDeleteFlag, 0)
                        .last("LIMIT 1"));
        if (storeUser != null && storeUser.getId() != null) {
            return new PublisherScope("store_" + rawPhone, TYPE_STORE, storeUser.getId());
        }
        return resolveFromPhoneId("store_" + rawPhone);
    }

    public boolean isSamePublisher(LifeUserDynamics dynamics, PublisherScope scope) {
        if (dynamics == null || scope == null || !scope.hasTypeRef()) {
            return false;
        }
        PublisherScope itemScope = resolveFromDynamics(dynamics);
        return itemScope.hasTypeRef()
                && Objects.equals(scope.getPhoneUserType(), itemScope.getPhoneUserType())
                && Objects.equals(scope.getPhoneRefId(), itemScope.getPhoneRefId());
    }

    public boolean isSamePublisher(LifeUserDynamicsVo vo, PublisherScope scope) {
        if (vo == null || scope == null || !scope.hasTypeRef()) {
            return false;
        }
        if (vo.getPhoneUserType() != null && vo.getPhoneRefId() != null) {
            return Objects.equals(scope.getPhoneUserType(), vo.getPhoneUserType())
                    && Objects.equals(scope.getPhoneRefId(), vo.getPhoneRefId());
        }
        return isSamePublisher(copyToEntity(vo), scope);
    }

    /** 用于与 life_fans / life_like_record 等仍使用 legacy phoneId 的模块比对。 */
    public String resolveComparablePhoneId(LifeUserDynamics dynamics) {
        PublisherScope scope = resolveFromDynamics(dynamics);
        if (scope.hasTypeRef()) {
            return buildLegacyPhoneId(scope.getPhoneUserType(), scope.getPhoneRefId());
        }
        return resolveFromPhoneId(dynamics != null ? dynamics.getPhoneId() : null).getLegacyPhoneId();
    }

    public String resolveComparablePhoneId(LifeUserDynamicsVo vo) {
        if (vo == null) {
            return null;
        }
        if (vo.getPhoneUserType() != null && vo.getPhoneRefId() != null) {
            return buildLegacyPhoneId(vo.getPhoneUserType(), vo.getPhoneRefId());
        }
        if (StringUtils.hasText(vo.getPhoneId())) {
            return vo.getPhoneId();
        }
        return resolveComparablePhoneId(copyToEntity(vo));
    }

    public String resolveBlacklistBlockedType(LifeUserDynamics dynamics) {
        if (dynamics == null || dynamics.getPhoneUserType() == null) {
            return "0";
        }
        if (dynamics.getPhoneUserType() == TYPE_STORE) {
            return "1";
        }
        if (dynamics.getPhoneUserType() == TYPE_USER) {
            return "2";
        }
        return "0";
    }

    public Integer resolveStoreIdFromDynamics(LifeUserDynamics dynamics) {
        if (dynamics == null
                || dynamics.getPhoneUserType() == null
                || dynamics.getPhoneUserType() != TYPE_STORE
                || dynamics.getPhoneRefId() == null) {
            return null;
        }
        StoreUser storeUser = storeUserMapper.selectById(dynamics.getPhoneRefId());
        return storeUser != null ? storeUser.getStoreId() : null;
    }

    /** 埋点等场景：优先认库表 type+refId，否则从入参 phoneId 解析。 */
    public Integer resolveStoreIdForTrack(LifeUserDynamics dynamics) {
        if (dynamics == null) {
            return null;
        }
        Integer storeId = resolveStoreIdFromDynamics(dynamics);
        if (storeId != null) {
            return storeId;
        }
        PublisherScope scope = resolveFromPhoneId(dynamics.getPhoneId());
        if (scope.hasTypeRef() && scope.getPhoneUserType() == TYPE_STORE) {
            StoreUser storeUser = storeUserMapper.selectById(scope.getPhoneRefId());
            return storeUser != null ? storeUser.getStoreId() : null;
        }
        return null;
    }

    public String buildLegacyPhoneId(Integer phoneUserType, Integer phoneRefId) {
        if (phoneUserType == null || phoneRefId == null) {
            return null;
        }
        switch (phoneUserType) {
            case TYPE_USER: {
                LifeUser user = lifeUserMapper.selectById(phoneRefId);
                return user != null && StringUtils.hasText(user.getUserPhone())
                        ? "user_" + user.getUserPhone() : null;
            }
            case TYPE_STORE: {
                StoreUser storeUser = storeUserMapper.selectById(phoneRefId);
                return storeUser != null && StringUtils.hasText(storeUser.getPhone())
                        ? "store_" + storeUser.getPhone() : null;
            }
            case TYPE_LAWYER: {
                LawyerUser lawyerUser = lawyerUserMapper.selectById(phoneRefId);
                return lawyerUser != null && StringUtils.hasText(lawyerUser.getPhone())
                        ? "lawyer_" + lawyerUser.getPhone() : null;
            }
            default:
                return null;
        }
    }

    /** 响应侧：由 type+refId 合成 phoneId 供旧客户端展示，不读库表 phone_id。 */
    public void ensureVoLegacyPhoneId(LifeUserDynamicsVo vo) {
        if (vo == null || vo.getPhoneUserType() == null || vo.getPhoneRefId() == null) {
            return;
        }
        vo.setPhoneId(buildLegacyPhoneId(vo.getPhoneUserType(), vo.getPhoneRefId()));
    }

    public void ensureEntityLegacyPhoneId(LifeUserDynamics dynamics) {
        if (dynamics == null || dynamics.getPhoneUserType() == null || dynamics.getPhoneRefId() == null) {
            return;
        }
        dynamics.setPhoneId(buildLegacyPhoneId(dynamics.getPhoneUserType(), dynamics.getPhoneRefId()));
    }

    private LifeUserDynamics copyToEntity(LifeUserDynamicsVo vo) {
        LifeUserDynamics d = new LifeUserDynamics();
        d.setPhoneUserType(vo.getPhoneUserType());
        d.setPhoneRefId(vo.getPhoneRefId());
        d.setPhoneId(vo.getPhoneId());
        return d;
    }
}
