package com.ruoyi.project.service.impl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.project.domain.ProjectStaff;
import com.ruoyi.project.domain.ProjectStaffRecord;
import com.ruoyi.project.mapper.ProjectStaffMapper;
import com.ruoyi.project.mapper.ProjectStaffRecordMapper;
import com.ruoyi.project.mapper.ProjectTaskMapper;
import com.ruoyi.project.service.ProjectStaffService;
import com.ruoyi.system.mapper.SysUserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ProjectStaffServiceImpl implements ProjectStaffService {

    Logger log = LoggerFactory.getLogger(ProjectStaffServiceImpl.class);
    @Autowired
    private ProjectStaffMapper projectStaffMapper;
    @Autowired
    private ProjectTaskMapper projectTaskMapper;
    @Autowired
    private ProjectStaffRecordMapper projectStaffRecordMapper;
    @Autowired
    private SysUserMapper userMapper;


    @Override
    public AjaxResult addStaff(ProjectStaff in) {
        List<ProjectStaff> projectStaffs = projectStaffMapper.selectBypid(in.getPid());
        for (ProjectStaff projectStaff : projectStaffs) {
            if (projectStaff.getAid().equals(in.getAid())){
                String name = projectStaff.getName();
                String errorStr=String.format("项目成员[%s]已存在.",name);
                log.error(errorStr);
                return AjaxResult.error(errorStr);
            }
        }
        projectStaffMapper.insertSelective(in);
        userMapper.updateUserProjectSum(in.getAid(),0);
        projectTaskMapper.updateStaffName(in.getPid());
        return AjaxResult.success();
    }

    @Override
    public AjaxResult deleteStaff(ProjectStaff in) {
        int sum = projectStaffRecordMapper.selectById(in.getId());
        if (sum > 0) {
            return AjaxResult.error("已存在打卡,请不要删除人员.");
        }
        userMapper.updateUserProjectSum(in.getAid(),1);
        int i = projectStaffMapper.deleteByPrimaryKey(in.getId());
        if (i>0){
            projectTaskMapper.updateStaffName(in.getPid());
            return AjaxResult.success();
        }
        return AjaxResult.error("编号不存在");
    }
}
