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.Enterprise;
import com.ruoyi.web.work.domain.Resume;
import com.ruoyi.web.work.domain.User;
import com.ruoyi.web.work.domain.dto.AuthDto;
import com.ruoyi.web.work.domain.dto.ChoiceDto;
import com.ruoyi.web.work.domain.dto.LoginDto;
import com.ruoyi.web.work.domain.dto.UserDto;
import com.ruoyi.web.work.mapper.UserMapper;
import com.ruoyi.web.work.service.IEnterpriseService;
import com.ruoyi.web.work.service.IResumeService;
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 org.springframework.transaction.annotation.Transactional;

import java.util.List;

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

    @Autowired
    private TokenServices tokenService;

    @Autowired
    private IResumeService resumeService;

    @Autowired
    private IEnterpriseService enterpriseService;

    @Autowired
    private Environment env;

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

    @Override
    public AjaxResult login(LoginDto dto) {
        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.setIsCompany(0);
            user.setIsContract(0);
            user.setIsAuthentication(0);
            user.setState(0);
            user.setIsEnterprise(0);
            save(user);
            return AjaxResult.success(new AjaxResult().put("token", tokenService.createToken(user)));
        }
        if (user.getState() == 1) {
            return AjaxResult.error(403, "你的账号被锁定，请联系管理员");
        }
        updateById(user);
        return AjaxResult.success(new AjaxResult().put("token", tokenService.createToken(user)));
    }

    @Override
    public AjaxResult auth(AuthDto dto) {
        if (AppUtil.getUser().getIsAuthentication() == 1) {
            return AjaxResult.error("你的信息已认证通过");
        }
        User user = new User();
        BeanUtils.copyProperties(dto, user);
        user.setId(AppUtil.getUser().getId());
        user.setIsAuthentication(1);
        if (!updateById(user)) {
            return AjaxResult.error("实名认证失败，请联系客服");
        }
        tokenService.setLoginUser(getById(AppUtil.getUser().getId()).setToken(AppUtil.getUser().getToken()));
        return AjaxResult.success();
    }

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

    @Transactional
    @Override
    public AjaxResult choice(ChoiceDto dto) {
        User user = new User();
        user.setId(AppUtil.getUser().getId());
        user.setType(dto.getType());
        if (!updateById(user)) {
            throw new ServiceException("选择用户类型失败");
        }
        //个人用户
        if (user.getType() == 0) {
            Resume resume = resumeService.getById(AppUtil.getUser().getId());
            if (resume == null) {
                resume = new Resume();
                resume.setId(AppUtil.getUser().getId());
                if (!resumeService.save(resume)) {
                    throw new ServiceException("选择用户类型创建简历失败");
                }
            }
        }
        //企业用户
        if (user.getType() == 1) {
            Enterprise enterprise = enterpriseService.getById(AppUtil.getUser().getId());
            if (enterprise == null) {
                enterprise = new Enterprise();
                enterprise.setId(AppUtil.getUser().getId());
                if (!enterpriseService.save(enterprise)) {
                    throw new ServiceException("选择用户类型创建企业信息失败");
                }
            }
        }
        tokenService.setLoginUser(getById(AppUtil.getUser().getId()).setToken(AppUtil.getUser().getToken()));
        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() {
        return AjaxResult.success(userMapper.selectUser(AppUtil.getUser().getId()));
    }
}
