package com.ruoyi.bst.userApp.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.ruoyi.bst.userApp.domain.UserApp;
import com.ruoyi.bst.userApp.domain.UserAppQuery;
import com.ruoyi.bst.userApp.domain.UserAppVO;
import com.ruoyi.bst.userApp.mapper.UserAppMapper;
import com.ruoyi.bst.userApp.service.UserAppService;
import com.ruoyi.bst.userApp.service.UserAppValidator;
import com.ruoyi.common.core.redis.RedisLock;
import com.ruoyi.common.core.redis.enums.RedisLockKey;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ServiceUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.collection.CollectionUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * 用户APP关联Service业务层处理
 *
 * @author ruoyi
 * @date 2025-03-14
 */
@Service
@Slf4j
public class UserAppServiceImpl implements UserAppService
{

    @Autowired
    private UserAppMapper userAppMapper;

    @Autowired
    private RedisLock redisLock;
    
    @Autowired
    private UserAppValidator userAppValidator;

    /**
     * 查询用户APP关联
     *
     * @param id 用户APP关联主键
     * @return 用户APP关联
     */
    @Override
    public UserAppVO selectUserAppById(Long id)
    {
        return userAppMapper.selectUserAppById(id);
    }

    /**
     * 查询用户APP关联列表
     *
     * @param userApp 用户APP关联
     * @return 用户APP关联
     */
    @Override
    public List<UserAppVO> selectUserAppList(UserAppQuery userApp)
    {
        return userAppMapper.selectUserAppList(userApp);
    }

    /**
     * 新增用户APP关联
     *
     * @param userApp 用户APP关联
     * @return 结果
     */
    @Override
    public int insertUserApp(UserApp userApp)
    {

        ServiceUtil.assertion(userAppValidator.isBind(userApp.getUserId(), userApp.getAppId()),
         "用户%s已与应用%s绑定", userApp.getUserId(), userApp.getAppId());

        userApp.setCreateTime(DateUtils.getNowDate());
        return userAppMapper.insertUserApp(userApp);
    }

    /**
     * 修改用户APP关联
     *
     * @param userApp 用户APP关联
     * @return 结果
     */
    @Override
    public int updateUserApp(UserApp userApp)
    {
        return userAppMapper.updateUserApp(userApp);
    }

    /**
     * 批量删除用户APP关联
     *
     * @param ids 需要删除的用户APP关联主键
     * @return 结果
     */
    @Override
    public int deleteUserAppByIds(Long[] ids)
    {
        return userAppMapper.deleteUserAppByIds(ids);
    }

    /**
     * 删除用户APP关联信息
     *
     * @param id 用户APP关联主键
     * @return 结果
     */
    @Override
    public int deleteUserAppById(Long id)
    {
        return userAppMapper.deleteUserAppById(id);
    }

    @Override
    public int bind(Long userId, Long appId, String openId) {
        if (userId == null || appId == null || StringUtils.isBlank(openId)) {
            return 0;
        }
        String key = userId + ":" + appId;
        boolean lock = redisLock.lock(RedisLockKey.USER_APP_BIND, key);
        if (!lock) {
            log.error("用户{}绑定APP {} 失败，锁获取失败", userId, appId);
            return 0;
        }
        try {
            UserApp userApp = new UserApp();
            userApp.setUserId(userId);
            userApp.setAppId(appId);
            userApp.setOpenId(openId);
            return this.insertUserApp(userApp);
        } finally {
            redisLock.unlock(RedisLockKey.USER_APP_BIND, key);
        }
    }

    @Override
    public UserAppVO selectByUserApp(Long userId, Long appId) {
        if (userId == null || appId == null) {
            return null;
        }
        UserAppQuery query = new UserAppQuery();
        query.setUserId(userId);
        query.setAppId(appId);
        return this.selectOne(query);
    }

    private UserAppVO selectOne(UserAppQuery query) {
        PageHelper.startPage(1, 1);
        List<UserAppVO> list = userAppMapper.selectUserAppList(query);
        return CollectionUtils.firstElement(list);
    }
}
