package com.ruoyi.project.service.impl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.UserRolesType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.project.bo.ProjectListInput;
import com.ruoyi.project.bo.ProjectTaskListOut;
import com.ruoyi.project.bo.ProjectTaskOut;
import com.ruoyi.project.domain.ProjectStaff;
import com.ruoyi.project.domain.ProjectTask;
import com.ruoyi.project.mapper.ProjectStaffMapper;
import com.ruoyi.project.mapper.ProjectTaskMapper;
import com.ruoyi.project.service.ProjectTaskService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
public class ProjectTaskServiceImpl   implements ProjectTaskService {

    private static final Logger log = LoggerFactory.getLogger(ProjectTaskServiceImpl.class);
    @Autowired
    private ProjectTaskMapper projectTaskMapper;
    @Autowired
    private ProjectStaffMapper projectStaffMapper;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    protected Validator validator;

    @Override
    public AjaxResult addProjectTask(ProjectTask projectTask) {
        return AjaxResult.success(projectTaskMapper.insertSelective(projectTask));
    }

    @Override
    public AjaxResult deleteProject(ProjectTask in) {
        int i = projectTaskMapper.deleteByPrimaryKey(in.getId());
        if (i>0){
            projectStaffMapper.deleteBypid(in.getId());
            return AjaxResult.success();
        }
        return AjaxResult.error("项目编号不存在");
    }

    @Override
    public AjaxResult details(Long id) {
        ProjectTask projectTask = projectTaskMapper.selectByPrimaryKey(id);
        ProjectTaskOut out=  new ProjectTaskOut();

        if (projectTask!=null){
            BeanUtils.copyBeanProp(out, projectTask);
            List<ProjectStaff> projectStaffs = projectStaffMapper.selectBypid(id);
            if (!projectStaffs.isEmpty())out.setList(projectStaffs);
            return AjaxResult.success(out);
        }
        return AjaxResult.error("项目不存在");
    }

    @Override
    public List<ProjectTaskListOut> list(ProjectListInput in) {
        in.setUid(SecurityUtils.getUserId());
        if (SecurityUtils.hashRoles(UserRolesType.MANAGE.getCode())){
            in.setRolesId(UserRolesType.MANAGE.getCode());
        }else if(SecurityUtils.hashRoles(UserRolesType.COMMON.getCode())){
            in.setRolesId(UserRolesType.COMMON.getCode());
        }
        Long companyId = deptService.selectCompanyByDeptId();
        if (companyId!=null)in.setCompanyId(companyId);
        if (in.getEndTime()!=null)in.setEndTime(in.getEndTime()+" 23:59:59");
        return projectTaskMapper.selectList(in);
    }

    @Override
    public String importProject(List<ProjectTaskListOut> list, boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(list) || list.size() == 0)
        {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (ProjectTaskListOut p : list)
        {
            try
            {
                // 验证是否存在这个用户
                ProjectTask projectTask = projectTaskMapper.selectByPrimaryKey(p.getId());
                if (StringUtils.isNull(projectTask)){
                    BeanValidators.validateWithException(validator, projectTask);
                    projectTaskMapper.insertSelective(projectTask);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、项目： " + projectTask.getName() + " 导入成功");
                }else if (isUpdateSupport){
                    BeanValidators.validateWithException(validator, p);
                    projectTaskMapper.updateByPrimaryKeySelective(p);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、项目： " + projectTask.getName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、项目： " + projectTask.getName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、项目: " + p.getName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
