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

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.DateUtils;
import com.ruoyi.web.work.api.util.AppUtil;
import com.ruoyi.web.work.domain.Resume;
import com.ruoyi.web.work.domain.User;
import com.ruoyi.web.work.mapper.ResumeMapper;
import com.ruoyi.web.work.service.IResumeService;
import com.ruoyi.web.work.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Validator;
import java.util.List;

/**
 * @author lsw
 * @date 2024-06-04
 */
@Service
public class ResumeServiceImpl extends ServiceImpl<ResumeMapper, Resume> implements IResumeService {
    @Autowired
    private ResumeMapper resumeMapper;

    @Autowired
    private IUserService userService;

    @Autowired
    protected Validator validator;

    @Override
    public List<Resume> selectList(Resume resume) {
        return resumeMapper.selectList(resume);
    }

    @Override
    public AjaxResult index() {
        Resume resume = getById(AppUtil.getUser().getId());
        if (resume == null) {
            resume = new Resume();
            resume.setId(AppUtil.getUser().getId());
            if (!save(resume)) {
                throw new ServiceException("创建简历失败");
            }
        }
        return AjaxResult.success(resume);
    }

    @Transactional
    @Override
    public AjaxResult edit(Resume resume) {
        resume.setId(AppUtil.getUser().getId());
        resume.setAge(Integer.parseInt(DateUtils.getYear()) - Integer.parseInt(resume.getBirthday().substring(0, 4)));
        if (!updateById(resume)) {
            throw new ServiceException("编辑简历失败");
        }
        User user = new User();
        user.setId(AppUtil.getUser().getId());
        user.setAvatar(resume.getAvatar());
        if (!userService.updateById(user)) {
            throw new ServiceException("同步简历头像失败");
        }
        return AjaxResult.success();
    }
}
