package org.dromara.talk.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.stp.parameter.SaLoginParameter;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.constant.SystemConstants;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.core.enums.UserType;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.MessageUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.domain.vo.SysClientVo;
import org.dromara.system.service.ISysClientService;
import org.dromara.talk.domain.TalkUser;
import org.dromara.talk.domain.bo.TalkUserBo;
import org.dromara.talk.domain.vo.TalkUserVo;
import org.dromara.talk.mapper.TalkUserMapper;
import org.dromara.talk.service.ITalkUserService;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 对话用户Service业务层处理
 *
 * @author Lion Li
 *  2026-01-28
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class TalkUserServiceImpl implements ITalkUserService {

    private final TalkUserMapper baseMapper;
    private final ISysClientService clientService;

    /**
     * 查询对话用户
     *
     * @param id 主键
     * @return 对话用户
     */
    @Override
    public TalkUserVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询对话用户列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 对话用户分页列表
     */
    @Override
    public TableDataInfo<TalkUserVo> queryPageList(TalkUserBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TalkUser> lqw = buildQueryWrapper(bo);
        Page<TalkUserVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的对话用户列表
     *
     * @param bo 查询条件
     * @return 对话用户列表
     */
    @Override
    public List<TalkUserVo> queryList(TalkUserBo bo) {
        LambdaQueryWrapper<TalkUser> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<TalkUser> buildQueryWrapper(TalkUserBo bo) {
        LambdaQueryWrapper<TalkUser> lqw = Wrappers.lambdaQuery();
        lqw.eq(TalkUser::getUserType, "talk_web_user");
        lqw.orderByDesc(TalkUser::getId);
        lqw.like(StringUtils.isNotBlank(bo.getUsername()), TalkUser::getUsername, bo.getUsername());
        lqw.eq(StringUtils.isNotBlank(bo.getPassword()), TalkUser::getPassword, bo.getPassword());
        lqw.like(StringUtils.isNotBlank(bo.getNickname()), TalkUser::getNickname, bo.getNickname());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), TalkUser::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增对话用户
     *
     * @param bo 对话用户
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(TalkUserBo bo) {
        TalkUser add = MapstructUtils.convert(bo, TalkUser.class);
        add.setUserType("talk_web_user");
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改对话用户
     *
     * @param bo 对话用户
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(TalkUserBo bo) {
        TalkUser update = MapstructUtils.convert(bo, TalkUser.class);
        return baseMapper.updateById(update) > 0;
    }


    /**
     * 校验并批量删除对话用户信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        return baseMapper.deleteByIds(ids) > 0;
    }
    @Override
    public TalkUser queryByUsernameWithPassword(String username) {
        return baseMapper.selectOne(new LambdaQueryWrapper<TalkUser>()
            .eq(TalkUser::getUserType, "talk_web_user")
            .eq(TalkUser::getUsername, username));
    }

    @Override
    public TalkUserVo queryByUsername(String username) {
        return baseMapper.selectVoOne(new LambdaQueryWrapper<TalkUser>()
            .eq(TalkUser::getUserType, "talk_web_user")
            .eq(TalkUser::getUsername, username));
    }

    @Override
    public Map<String, Object> login(String username, String password, String clientId) {
        // 验证 clientId 是否存在
        if (ObjectUtil.isNull(clientId)) {
            log.info("客户端id为空");
            throw new IllegalArgumentException("客户端ID不能为空");
        }

        // 查询客户端配置
        SysClientVo client = clientService.queryByClientId(clientId);
        if (ObjectUtil.isNull(client)) {
            log.info("客户端id: {} 不存在", clientId);
            throw new IllegalArgumentException(MessageUtils.message("auth.grant.type.error"));
        } else if (!SystemConstants.NORMAL.equals(client.getStatus())) {
            throw new IllegalArgumentException(MessageUtils.message("auth.grant.type.blocked"));
        }

        // 查询用户（包含密码）
        TalkUser user = queryByUsernameWithPassword(username);
        if (user == null) {
            throw new IllegalArgumentException("用户名或密码错误");
        }

        // 验证密码
        if (!password.equals(user.getPassword())) {
            throw new IllegalArgumentException("用户名或密码错误");
        }

        // 检查用户状态
        if ("1".equals(user.getStatus())) {
            throw new IllegalArgumentException("用户已被停用");
        }

        // 创建 LoginUser 对象（不包含任何权限）
        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(user.getId());
        loginUser.setUsername(user.getUsername());
        loginUser.setUserType(UserType.APP_USER.getUserType());
        loginUser.setMenuPermission(Collections.emptySet());
        loginUser.setRolePermission(Collections.emptySet());
        loginUser.setClientKey(client.getClientKey());
        loginUser.setDeviceType(client.getDeviceType());

        // 使用 LoginHelper 登录
        SaLoginParameter model = new SaLoginParameter();
        model.setDeviceType(client.getDeviceType());
        model.setTimeout(client.getTimeout());
        model.setActiveTimeout(client.getActiveTimeout());
        model.setExtra(LoginHelper.CLIENT_KEY, client.getClientId());
        LoginHelper.login(loginUser, model);

        // 返回token和用户信息
        TalkUserVo userVo = queryByUsername(username);
        Map<String, Object> result = new HashMap<>();
        result.put("token", StpUtil.getTokenValue());
        result.put("user", userVo);
        result.put("clientId", client.getClientId());

        return result;
    }

}
