package com.gxwebsoft.app.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.app.mapper.AppUserMapper;
import com.gxwebsoft.app.service.AppUserService;
import com.gxwebsoft.app.entity.AppUser;
import com.gxwebsoft.app.param.AppUserParam;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.common.system.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 应用成员Service实现
 *
 * @author 科技小王子
 * @since 2026-03-28 21:29:44
 */
@Slf4j
@Service
public class AppUserServiceImpl extends ServiceImpl<AppUserMapper, AppUser> implements AppUserService {

    /** 注入同 jar 包内的 UserService，用于写入冗余用户信息，不做跨库 JOIN */
    @Resource
    private UserService userService;

    @Override
    public PageResult<AppUser> pageRel(AppUserParam param) {
        PageParam<AppUser, AppUserParam> page = new PageParam<>(param);
        page.setDefaultOrder("sort_number asc, create_time asc");
        List<AppUser> list = baseMapper.selectPageRel(page, param);
        return new PageResult<>(list, page.getTotal());
    }

    @Override
    public List<AppUser> listRel(AppUserParam param) {
        List<AppUser> list = baseMapper.selectListRel(param);
        PageParam<AppUser, AppUserParam> page = new PageParam<>();
        page.setDefaultOrder("sort_number asc, create_time asc");
        return page.sortRecords(list);
    }

    @Override
    public AppUser getByIdRel(Integer id) {
        AppUserParam param = new AppUserParam();
        param.setId(id.longValue());
        return param.getOne(baseMapper.selectListRel(param));
    }

    @Override
    public AppUser inviteUser(Long websiteId, Integer userId, String role, Integer inviteBy) {
        // 检查是否已经是成员
        if (isMember(websiteId, userId)) {
            throw new RuntimeException("该用户已经是应用成员");
        }

        // 查询用户基础信息并冗余写入，避免跨库 JOIN
        User sysUser = userService.getByIdIgnoreTenant(userId);
        if (sysUser == null) {
            throw new RuntimeException("用户不存在，userId=" + userId);
        }

        AppUser appUser = new AppUser();
        appUser.setWebsiteId(websiteId);
        appUser.setUserId(userId);
        appUser.setRole(role != null ? role : "developer");
        appUser.setInviteBy(inviteBy.longValue());
        appUser.setInviteTime(LocalDateTime.now());
        appUser.setStatus(0);
        appUser.setSortNumber(0);
        // 冗余写入用户基础信息，彻底解除跨库 JOIN 依赖
        appUser.setUsername(sysUser.getUsername());
        appUser.setNickname(sysUser.getNickname());
        appUser.setAvatar(sysUser.getAvatar());
        appUser.setPhone(sysUser.getPhone());

        save(appUser);
        log.info("邀请成员成功，websiteId={}, userId={}, username={}, role={}", websiteId, userId, sysUser.getUsername(), role);
        return appUser;
    }

    @Override
    public boolean updateRole(Long id, String role) {
        return update(new LambdaUpdateWrapper<AppUser>()
                .eq(AppUser::getId, id)
                .set(AppUser::getRole, role));
    }

    @Override
    public boolean isMember(Long websiteId, Integer userId) {
        long count = count(new LambdaQueryWrapper<AppUser>()
                .eq(AppUser::getWebsiteId, websiteId)
                .eq(AppUser::getUserId, userId)
                .eq(AppUser::getStatus, 0));
        return count > 0;
    }

    @Override
    public User findUserByPhone(String phone) {
        return userService.getByPhone(phone);
    }

}
