package shop.alien.lawyer.util;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import shop.alien.entity.store.LawyerUser;
import shop.alien.entity.store.LifeLikeRecord;
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;
import shop.alien.util.type.PhoneTypeIdResult;
import shop.alien.util.type.TypeUtil;

import java.util.Objects;

/**
 * alien-lawyer：life_like_record 点赞人身份工具。
 */
@Component
@RequiredArgsConstructor
public class LawyerLikeRecordIdentityHelper {

    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 LawyerLikerScope {
        private final String legacyDianzanId;
        private final Integer dianzanUserType;
        private final Integer dianzanRefId;

        public LawyerLikerScope(String legacyDianzanId, Integer dianzanUserType, Integer dianzanRefId) {
            this.legacyDianzanId = legacyDianzanId;
            this.dianzanUserType = dianzanUserType;
            this.dianzanRefId = dianzanRefId;
        }

        public String getLegacyDianzanId() {
            return legacyDianzanId;
        }

        public Integer getDianzanUserType() {
            return dianzanUserType;
        }

        public Integer getDianzanRefId() {
            return dianzanRefId;
        }

        public boolean hasTypeRef() {
            return dianzanUserType != null && dianzanRefId != null;
        }
    }

    public LawyerLikerScope resolveFromDianzanId(String dianzanId) {
        if (!StringUtils.hasText(dianzanId)) {
            return new LawyerLikerScope(null, null, null);
        }
        String trimmed = dianzanId.trim();
        if (typeUtil.containsUnderscore(trimmed)) {
            PhoneTypeIdResult resolved = typeUtil.resolveTypeAndId(trimmed);
            if (resolved != null) {
                return new LawyerLikerScope(trimmed, resolved.getType(), resolved.getId());
            }
            return new LawyerLikerScope(trimmed, null, null);
        }
        try {
            int refId = Integer.parseInt(trimmed);
            return new LawyerLikerScope(trimmed, TYPE_USER, refId);
        } catch (NumberFormatException e) {
            return new LawyerLikerScope(trimmed, null, null);
        }
    }

    public LawyerLikerScope fromLifeUserId(Integer lifeUserId) {
        if (lifeUserId == null) {
            return new LawyerLikerScope(null, null, null);
        }
        return new LawyerLikerScope(String.valueOf(lifeUserId), TYPE_USER, lifeUserId);
    }

    public LawyerLikerScope fromStoreUserId(Integer storeUserId) {
        if (storeUserId == null) {
            return new LawyerLikerScope(null, null, null);
        }
        StoreUser storeUser = storeUserMapper.selectById(storeUserId);
        String legacy = storeUser != null && StringUtils.hasText(storeUser.getPhone())
                ? "store_" + storeUser.getPhone()
                : String.valueOf(storeUserId);
        return new LawyerLikerScope(legacy, TYPE_STORE, storeUserId);
    }

    public LawyerLikerScope resolveFromRecord(LifeLikeRecord record) {
        if (record == null
                || record.getDianzanUserType() == null
                || record.getDianzanRefId() == null) {
            return new LawyerLikerScope(null, null, null);
        }
        String legacy = buildLegacyDianzanId(record.getDianzanUserType(), record.getDianzanRefId());
        return new LawyerLikerScope(legacy, record.getDianzanUserType(), record.getDianzanRefId());
    }

    public void normalizeBeforeSave(LifeLikeRecord record) {
        if (record == null) {
            return;
        }
        if (record.getDianzanUserType() == null || record.getDianzanRefId() == null) {
            LawyerLikerScope scope = resolveFromDianzanId(record.getDianzanId());
            if (scope.hasTypeRef()) {
                record.setDianzanUserType(scope.getDianzanUserType());
                record.setDianzanRefId(scope.getDianzanRefId());
            }
        }
        record.setDianzanId(null);
    }

    public void applyLikerFilter(LambdaQueryWrapper<LifeLikeRecord> wrapper, LawyerLikerScope scope) {
        if (wrapper == null || scope == null || !scope.hasTypeRef()) {
            return;
        }
        wrapper.eq(LifeLikeRecord::getDianzanUserType, scope.getDianzanUserType())
                .eq(LifeLikeRecord::getDianzanRefId, scope.getDianzanRefId());
    }

    public void applyLikerFilter(LambdaUpdateWrapper<LifeLikeRecord> wrapper, LawyerLikerScope scope) {
        if (wrapper == null || scope == null || !scope.hasTypeRef()) {
            return;
        }
        wrapper.eq(LifeLikeRecord::getDianzanUserType, scope.getDianzanUserType())
                .eq(LifeLikeRecord::getDianzanRefId, scope.getDianzanRefId());
    }

    public void applyLikerFilter(QueryWrapper<LifeLikeRecord> wrapper, LawyerLikerScope scope) {
        applyLikerFilter(wrapper, scope, null);
    }

    public void applyLikerFilter(QueryWrapper<LifeLikeRecord> wrapper, LawyerLikerScope scope, String tableAlias) {
        if (wrapper == null || scope == null || !scope.hasTypeRef()) {
            return;
        }
        String prefix = StringUtils.hasText(tableAlias) ? tableAlias + "." : "";
        wrapper.eq(prefix + "dianzan_user_type", scope.getDianzanUserType())
                .eq(prefix + "dianzan_ref_id", scope.getDianzanRefId());
    }

    public String resolveComparableDianzanId(LifeLikeRecord record) {
        LawyerLikerScope scope = resolveFromRecord(record);
        if (scope.hasTypeRef()) {
            String legacy = buildLegacyDianzanId(scope.getDianzanUserType(), scope.getDianzanRefId());
            if (legacy != null) {
                return legacy;
            }
            if (Objects.equals(scope.getDianzanUserType(), TYPE_USER)) {
                return String.valueOf(scope.getDianzanRefId());
            }
        }
        return record != null ? record.getDianzanId() : null;
    }

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

    public void ensureEntityLegacyDianzanId(LifeLikeRecord record) {
        if (record == null || record.getDianzanUserType() == null || record.getDianzanRefId() == null) {
            return;
        }
        String legacy = buildLegacyDianzanId(record.getDianzanUserType(), record.getDianzanRefId());
        if (legacy != null) {
            record.setDianzanId(legacy);
        }
    }
}
