package com.jeeplus.modules.sg.project.service;

import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.service.CrudService;
import com.jeeplus.modules.sg.project.entity.WbsItem;
import com.jeeplus.modules.sg.project.entity.WbsProject;
import com.jeeplus.modules.sg.project.entity.WbsSelection;
import com.jeeplus.modules.sg.project.mapper.ItemMapper;
import com.jeeplus.modules.sg.project.mapper.ProjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional(readOnly = true)
public class ProjectService extends CrudService<ProjectMapper, WbsProject> {
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private ItemService itemService;


    public WbsProject get(String id) {
        WbsProject wbsProject =  super.get(id);
        WbsSelection wbsSelection = new WbsSelection();
        wbsSelection.setProjectId(id);
        List<WbsItem> items = itemService.findList(wbsSelection);
        wbsProject.setWbsItems(items);
        return wbsProject;
    }


    public List<WbsProject> findList(WbsSelection wbsSelection) {
        List<WbsProject> list =  projectMapper.getList(wbsSelection);
            for(WbsProject wbsProject1 : list){
                String id = wbsProject1.getId();
                wbsSelection.setProjectId(id);
                List<WbsItem> items = itemService.findList(wbsSelection);
                wbsProject1.setWbsItems(items);
            }
         if(StringUtils.isNoneBlank(wbsSelection.getItemName()) || wbsSelection.getItemStartDate() != null || wbsSelection.getItemEndDate() != null || StringUtils.isNoneBlank(wbsSelection.getUnit()) || StringUtils.isNoneBlank(wbsSelection.getType())){
             List<WbsProject> wbsProjects = new ArrayList<>();
             for(WbsProject wbsProject : list){
                 if(wbsProject.getWbsItems().size()>0){
                     wbsProjects.add(wbsProject);
                 }
             }
             return wbsProjects;
         }
        return list;
    }

    public Page<WbsProject> findPage(Page<WbsProject> page, WbsProject wbsProject) {
        return super.findPage(page, wbsProject);
    }

    @Transactional(readOnly = false)
    public void save(WbsProject wbsProject) {
        super.save(wbsProject);
    }




    @Transactional(readOnly = false)
    public void updateNum(int number,String id){
        projectMapper.updateNum(number,id);
    }


    @Transactional(readOnly = false)
    public void delete(WbsProject wbsProject) {
        super.delete(wbsProject);
    }
}
