package com.artfess.yhxt.basedata.manager.impl;

import com.artfess.base.context.BaseContext;
import com.artfess.base.query.PageList;
import com.artfess.base.query.QueryFilter;
import com.artfess.base.util.StringUtil;
import com.artfess.uc.dao.OrgDao;
import com.artfess.uc.manager.OrgManager;
import com.artfess.uc.model.Org;
import com.artfess.yhxt.basedata.manager.AccessoryManager;
import com.artfess.yhxt.basedata.manager.BizVehicleManager;
import com.artfess.yhxt.basedata.manager.RoadManager;
import com.artfess.yhxt.basedata.model.Accessory;
import com.artfess.yhxt.basedata.model.BizVehicle;
import com.artfess.yhxt.basedata.model.MigrantBuildersInformation;
import com.artfess.yhxt.basedata.dao.MigrantBuildersInformationDao;
import com.artfess.yhxt.basedata.manager.MigrantBuildersInformationManager;
import com.artfess.base.manager.impl.BaseManagerImpl;
import com.artfess.yhxt.basedata.model.Road;
import com.artfess.yhxt.basedata.vo.HumanCountVo;

import com.artfess.yhxt.basedata.vo.MigrantBuildersInformationVo;
import com.artfess.yhxt.basedata.vo.VehicleCountVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 施工人员管理表 服务实现类
 *
 * @company 阿特菲斯信息技术有限公司
 * @author xzh
 * @since 2021-10-12
 */
@Service
public class MigrantBuildersInformationManagerImpl extends BaseManagerImpl<MigrantBuildersInformationDao, MigrantBuildersInformation> implements MigrantBuildersInformationManager {

    @Autowired
    private AccessoryManager accessoryManager;

    @Resource
    private BaseContext baseContext;
    @Resource
    private MigrantBuildersInformationManager migrantBuildersInformationManager;
    @Resource
    private OrgDao orgDao;

    @Resource
    private RoadManager roadManager;
    @Resource
    private OrgManager orgManager;
    @Resource
    private BizVehicleManagerImpl bizVehicleManagerImpl;

    @Override
    public PageList<MigrantBuildersInformation> queryMigrantBuildersInformation(QueryFilter<MigrantBuildersInformation> queryFilter) {
        IPage<MigrantBuildersInformation> result = baseMapper.queryMigrantBuildersInformation(convert2IPage(queryFilter.getPageBean()),convert2Wrapper(queryFilter,currentModelClass()));
        return new PageList<>(result);
    }

    @Override
    public MigrantBuildersInformation getMigrantBuildersById(String id) {
        return baseMapper.selectById(id);
    }

    @Override
    public void saveVo(MigrantBuildersInformationVo migrantBuildersInformationVo) {
        //施工人员信息
        MigrantBuildersInformation migrantBuildersInformation = migrantBuildersInformationVo.getMigrantBuildersInformation();
        //附件信息
        List<Accessory> accessoryList = migrantBuildersInformationVo.getAccessoryList();
        //保存施工人员信息

        this.create(migrantBuildersInformation);
        //资源ID
        String id = migrantBuildersInformation.getId();
        if (accessoryList.size()>0) {
            //设置附件资源ID
            accessoryList.forEach(s -> s.setSourceId(id));
            this.accessoryManager.saveBatch(accessoryList);
        }
    }

    @Override
    public void updateVo(MigrantBuildersInformationVo migrantBuildersInformationVo) {
        //施工人员信息
        MigrantBuildersInformation migrantBuildersInformation = migrantBuildersInformationVo.getMigrantBuildersInformation();
        //附件信息
        List<Accessory> accessoryList = migrantBuildersInformationVo.getAccessoryList();
        //修改施工人员信息
        this.update(migrantBuildersInformation);
        //资源ID
        String id = migrantBuildersInformation.getId();
        if (accessoryList.size()>0) {
            this.accessoryManager.delAccessoryBySourceId(id);
            //获取附件信息
            accessoryList.forEach(s -> s.setSourceId(id));
            this.accessoryManager.saveOrUpdateBatch(accessoryList);
        }
    }

    @Override
    public MigrantBuildersInformationVo getByIdVo(String id) {
        MigrantBuildersInformationVo migrantBuildersInformationVo = new MigrantBuildersInformationVo();
        //获取施工人员信息
        MigrantBuildersInformation migrantBuildersInformation = this.baseMapper.selectById(id);
        //获取附件信息
        List<Accessory> accessoryList = this.accessoryManager.getAccessoryBySourceId(id);
        migrantBuildersInformationVo.setMigrantBuildersInformation(migrantBuildersInformation);
        migrantBuildersInformationVo.setAccessoryList(accessoryList);
        return migrantBuildersInformationVo;
    }


    /**
     * 养护人员数量统计
     * @return
     */
    @Override
    public List<HumanCountVo> getCountVo() {
        String orgId ;
        if (StringUtils.isNotEmpty(baseContext.getCurrentOrgId())&&!"0".equals(baseContext.getCurrentOrgId())){
            orgId = baseContext.getCurrentOrgId();
        }else {
            orgId = "1419863231459102720";
        }


        List<Org> rtnList = new ArrayList<>();

        QueryWrapper<Org> rgQueryWrapper = new QueryWrapper<>();
        rgQueryWrapper.eq("is_dele_","0");
        List<Org> allList = orgDao.selectList(rgQueryWrapper);

        List<HumanCountVo> vos = new ArrayList<>();
        List<Org> list = bizVehicleManagerImpl.getOrgChild(allList, orgId, rtnList);
        for (Org org: list){
            HumanCountVo vo = new HumanCountVo();
            BeanUtils.copyProperties(org,vo);
            vos.add(vo);
        }

        List<HumanCountVo> returnList = this.getHumanCountChild(vos, orgId);


        countCompanyCount(returnList);
        return returnList;
    }

    private List<HumanCountVo> getHumanCountChild(List<HumanCountVo> vos, String orgId) {
        List<HumanCountVo> returnList = new ArrayList<>();
        for (HumanCountVo entity : vos){
            if (orgId.equals(entity.getParentId())) {
                entity.setChirldren(getHumanCountChild(vos, entity.getId()));
                returnList.add(entity);
            }
        }
        return returnList;

    }


    /**
     * 最上级
     * @param vos
     * @param vos
     */
    private void countCompanyCount(List<HumanCountVo> vos ){

        // 获取迭代器
        Iterator<HumanCountVo> it = vos.iterator();

        while(it.hasNext()){
            HumanCountVo countVo = it.next();
            Integer grade = Integer.valueOf(countVo.getGrade());
            List<String> roadList = new ArrayList<>();
            if (grade<4){
                QueryWrapper<Road> roadQueryWrapper = new QueryWrapper<>();
                roadQueryWrapper.like( "COMPANY_IDS_", countVo.getId());
                roadList = roadManager.list(roadQueryWrapper).stream().map(Road::getId).collect(Collectors.toList());
            }else if (grade==4){
                QueryWrapper<Road> roadByNameQueryWrapper = new QueryWrapper<>();
                roadByNameQueryWrapper.eq("NAME_",countVo.getName());
                roadList = roadManager.list(roadByNameQueryWrapper).stream().map(Road::getId).collect(Collectors.toList());
            }
            if (roadList.size()>0){
                countVo = this.newCountHuman(roadList,countVo);
            }else {
                it.remove();
            }
            if (countVo.getChirldren().size()>0&&Integer.valueOf(countVo.getGrade())<4){
                this.countCompanyCount(countVo.getChirldren());
            }
        }
    }

    //统计养护人员
    public HumanCountVo newCountHuman(List<String> ids,HumanCountVo vo) {


        QueryWrapper<MigrantBuildersInformation> migrantBuildersInformationQueryWrapper = new QueryWrapper<>();
            String companyId = vo.getId();
            HashMap<String, String> map = new HashMap<>();
            map.put("id",companyId);
            Map<String, Set<String>> childrenIds = orgManager.getChildrenIds(map);
            Set<String> companyIds = childrenIds.get("id");
        migrantBuildersInformationQueryWrapper.in("COMPANY_ID_", companyIds);

        List<MigrantBuildersInformation> list = migrantBuildersInformationManager.list(migrantBuildersInformationQueryWrapper);



        if (list.size()>0){

            vo.setMigrantHumanNum(list.size());

            if ("4".equals(vo.getGrade())){
                vo.setRoadSegmentId(list.get(0).getCompanyId());
            }

        }else {
            vo.setMigrantHumanNum(0);
        }
        return vo;
    }

}
