package com.ruoyi.web.work.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.web.work.api.config.TokenServices;
import com.ruoyi.web.work.api.util.AppUtil;
import com.ruoyi.web.work.domain.BindUser;
import com.ruoyi.web.work.domain.User;
import com.ruoyi.web.work.domain.dto.LoginDto;
import com.ruoyi.web.work.domain.dto.UserEditDto;
import com.ruoyi.web.work.mapper.UserMapper;
import com.ruoyi.web.work.service.IBindUserService;
import com.ruoyi.web.work.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.rmi.ServerException;
import java.util.List;

/**
 * @author lsw
 * @date 2024-07-16
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private TokenServices tokenService;

    @Autowired
    IBindUserService bindUserService;

    @Autowired
    private Environment env;

    @Override
    public List<User> selectList(User user) {
        return userMapper.selectList(user);
    }

    @Override
    public AjaxResult login(LoginDto dto) throws ServerException {
        JSONObject res = JSON.parseObject(HttpUtils.sendGet("https://api.weixin.qq.com/sns/jscode2session?appid=" + env.getProperty("wx.appid") + "&secret=" + env.getProperty("wx.appSecret") + "&js_code=" + dto.getCode() + "&grant_type=authorization_code", null));
        if (StringUtils.isNotEmpty(res.getString("errmsg"))) {
            return AjaxResult.error("获取openid失败");
        }
        User user = userMapper.selectByOpenId(res.getString("openid"));
        if (user == null) {
            user = new User();
            user.setOpenId(res.getString("openid"));
            user.setState(0);
            if (!save(user)) {
                throw new ServerException("登录失败,请联系管理员");
            }
            return AjaxResult.success(new AjaxResult().put("token", tokenService.createToken(user)));
        }
        if (user.getState() == 1) {
            return AjaxResult.error(403, "你的账号被锁定，请联系管理员");
        }
        if (!updateById(user)) {
            throw new ServerException("登录失败,请联系管理员");
        }
        return AjaxResult.success(new AjaxResult().put("token", tokenService.createToken(user)));
    }

    @Override
    public AjaxResult edit(UserEditDto dto) {
        User user = new User();
        BeanUtils.copyProperties(dto, user);
        user.setId(AppUtil.getUser().getId());
        if (!updateById(user)) {
            throw new ServiceException("编辑用户信息失败");
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult exit() {
        try {
            tokenService.delLoginUser(AppUtil.getUser().getToken());
            return AjaxResult.success();
        } catch (Exception e) {
            return AjaxResult.error("退出登录失败");
        }
    }

    @Override
    public AjaxResult info() {
        User user =getById(AppUtil.getUser().getId());
        user.setBindUserList(bindUserService.selectList(new BindUser().setUserId(user.getId())));
        return AjaxResult.success(user);
    }
}
