package shop.alien.storeplatform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import shop.alien.entity.result.R;
import shop.alien.entity.store.LifeUser;
import shop.alien.entity.store.StoreInfo;
import shop.alien.entity.store.StoreUser;
import shop.alien.mapper.LifeUserMapper;
import shop.alien.mapper.StoreInfoMapper;
import shop.alien.mapper.StoreUserMapper;
import shop.alien.storeplatform.service.MerchantAuthService;
import shop.alien.storeplatform.util.AliApiUtil;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * web端商户身份验证服务实现类
 *
 * @author ssk
 * @since 2025-01-xx
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class MerchantAuthServiceImpl implements MerchantAuthService {

    private final AliApiUtil aliApiUtil;

    private final LifeUserMapper lifeUserMapper;

    private final StoreUserMapper storeUserMapper;

    private final StoreInfoMapper storeInfoMapper;

    @Override
    public R<String> verifyIdInfo(String name, String idCard, Integer appType) {
        log.info("MerchantAuthServiceImpl.verifyIdInfo?name={}&idCard={}&appType={}", name, idCard, appType);
        
        // 根据端类型查询是否已实名认证
        int size = 0;
        if (appType == 0) {
            // 用户端：查询未注销的用户
            LambdaQueryWrapper<LifeUser> userWrapper = new LambdaQueryWrapper<>();
            userWrapper.eq(LifeUser::getIdCard, idCard)
                       .eq(LifeUser::getRealName, name)
                       .eq(LifeUser::getLogoutFlag, 0);  // 只查询未注销的用户
            size = lifeUserMapper.selectCount(userWrapper);
        } else {
            // 商家端：查询已入住或审核中的商家
            // 1. 先根据身份证和姓名查询商户用户
            LambdaQueryWrapper<StoreUser> storeUserWrapper = new LambdaQueryWrapper<>();
            storeUserWrapper.eq(StoreUser::getIdCard, idCard)
                           .eq(StoreUser::getName, name);
            List<StoreUser> storeUserList = storeUserMapper.selectList(storeUserWrapper);
            
            // 2. 获取这些商户用户绑定的店铺ID
            List<Integer> storeIds = storeUserList.stream()
                    .map(StoreUser::getStoreId)
                    .filter(Objects::nonNull)  // 过滤掉空的店铺ID
                    .collect(Collectors.toList());
            
            // 3. 如果有店铺ID，查询非审核失败状态的店铺
            if (!storeIds.isEmpty()) {
                LambdaQueryWrapper<StoreInfo> storeInfoWrapper = new LambdaQueryWrapper<>();
                storeInfoWrapper.in(StoreInfo::getId, storeIds)
                               .notIn(StoreInfo::getStoreApplicationStatus, 2);  // 排除审核失败的店铺（状态2）
                size = storeInfoMapper.selectCount(storeInfoWrapper);
            }
        }
        
        if (size > 0) {
            return R.fail("该身份证已实名认证过");
        }
        
        // 调用支付宝身份验证接口
        if (aliApiUtil.verifyIdCard(name, idCard)) {
            return R.success("身份验证成功");
        }
        
        return R.fail("身份证号与姓名不一致，请检查后重新填写");
    }
}

