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

import com.artfess.base.context.BaseContext;
import com.artfess.base.model.CommonResult;
import com.artfess.base.query.PageList;
import com.artfess.base.query.QueryFilter;
import com.artfess.poi.util.ExcelUtil;
import com.artfess.uc.dao.OrgDao;
import com.artfess.uc.model.Org;
import com.artfess.yhxt.basedata.manager.BizMaterialsManagementManager;
import com.artfess.yhxt.basedata.manager.BizStructureVehicleManager;
import com.artfess.yhxt.basedata.manager.RoadManager;
import com.artfess.yhxt.basedata.model.*;
import com.artfess.yhxt.basedata.dao.BizEmergeMaterialManagementDao;
import com.artfess.yhxt.basedata.manager.BizEmergeMaterialManagementManager;
import com.artfess.base.manager.impl.BaseManagerImpl;
import com.artfess.yhxt.basedata.vo.BizEmergeMaterialManagementVO;

import com.artfess.yhxt.contract.vo.BizEmergeMaterialManagementDetailExcel;
import com.artfess.yhxt.contract.vo.BizEmergeMaterialManagementGoodsVo;
import com.artfess.yhxt.statistics.vo.Org4culvertVO;
import com.artfess.yhxt.statistics.vo.Org4emergeVO;
import com.artfess.yhxt.util.PermissionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 应急物资库管理 服务实现类
 *
 * @author xmz
 * @company 阿特菲斯信息技术有限公司
 * @since 2022-04-19
 */
@Service
public class BizEmergeMaterialManagementManagerImpl extends BaseManagerImpl<BizEmergeMaterialManagementDao, BizEmergeMaterialManagement> implements BizEmergeMaterialManagementManager {
    @Resource
    BaseContext baseContext;
    @Resource
    PermissionUtils permissionUtils;
    @Resource
    BizMaterialsManagementManager bizMaterialsManagementManager;

    @Resource
    private OrgDao orgDao;

    @Resource
    private RoadManager roadManager;



    @Override
    public List<Org4emergeVO> getEmergeCount() {
        String orgId ;
        if (StringUtils.isNotEmpty(baseContext.getCurrentOrgId())&&!"0".equals(baseContext.getCurrentOrgId())){
            orgId = baseContext.getCurrentOrgId();
        }else {
            orgId = "1419863231459102720";
        }
        List<Org4emergeVO> lists = new ArrayList<>();

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

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

        List<Org> list = getOrgChild(allList, orgId, rtnList);
        for (Org org: list){
            Org4emergeVO fvo = new Org4emergeVO();
            BeanUtils.copyProperties(org,fvo);
            lists.add(fvo);
        }
        lists = getChild(lists,orgId);


        return this.setCount(lists);
    }


    public List<Org4emergeVO> setCount(List<Org4emergeVO> list){
        // 获取迭代器
        Iterator<Org4emergeVO> it = list.iterator();

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

    public Org4emergeVO newCount(List<String> ids, Org4emergeVO orgVO) {

        QueryWrapper<BizEmergeMaterialManagement> wrapper = new QueryWrapper<>();
        wrapper.in("ROAD_SEGMENT_ID_", ids);
        List<BizEmergeMaterialManagement> list = this.list(wrapper);
        orgVO.setCountNum(list.size());

        if ("4".equals(orgVO.getGrade())){
            orgVO.setRoadSegmentId(ids.get(0));
        }

        return orgVO;
    }

    public static List<Org> getOrgChild(List<Org> orgList, String parentId, List<Org> rtnList) {
        for (Org org : orgList) {
            // 遍历出父id等于参数的id，add进子节点集合
            if (parentId.equals(org.getParentId())) {
                // 递归遍历下一级
                getOrgChild(orgList, org.getId(), rtnList);
                rtnList.add(org);
            }
        }
        return rtnList;
    }

    public static List<Org4emergeVO> getChild(List<Org4emergeVO> allList, String pCode) {
        List<Org4emergeVO> returnList = new ArrayList<>();
        for (Org4emergeVO entity : allList){
            if (pCode.equals(entity.getParentId())) {
                entity.setChirldren(getChild(allList, entity.getId()));
                returnList.add(entity);
            }
        }
        return returnList;
    }

    @Override
    public PageList<BizEmergeMaterialManagementVO> queryEmergeMaterialManagement(QueryFilter<BizEmergeMaterialManagement> queryFilter) {
        if (StringUtils.isNotEmpty(baseContext.getCurrentOrgId())) {
//            queryFilter.addFilter("COMPANY_ID_", String.join("','", baseContext.getCurrentOrgId()), QueryOP.IN, FieldRelation.AND);
            permissionUtils.addPermission(queryFilter);
        }
        PageList<BizEmergeMaterialManagement> list = this.query(queryFilter);
        List<BizEmergeMaterialManagementVO> rerurnList = new ArrayList<>();
        for (BizEmergeMaterialManagement model : list.getRows()){
            BizEmergeMaterialManagementVO vo = new BizEmergeMaterialManagementVO();
            BeanUtils.copyProperties(model,vo);
            QueryWrapper<BizMaterialsManagement> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("STRUCTURAL_ID_",vo.getId());
            vo.setMaterialsManagements(bizMaterialsManagementManager.list(queryWrapper));
            rerurnList.add(vo);
        }
        PageList<BizEmergeMaterialManagementVO> pageList = new PageList<>();
        pageList.setPage(list.getPage());
        pageList.setPageSize(list.getPageSize());
        pageList.setTotal(list.getTotal());
        pageList.setRows(rerurnList);
        return pageList;
    }

    @Override
    public void saveOrUpdateManagementGoodsVo(BizEmergeMaterialManagementGoodsVo vo) {
        BizEmergeMaterialManagement bizEmergeMaterialManagement = vo.getBizEmergeMaterialManagement();
        this.saveOrUpdate(bizEmergeMaterialManagement);
        List<BizMaterialsManagement> detailList = vo.getDetailList();
        this.bizMaterialsManagementManager.deleteAllByManId(bizEmergeMaterialManagement.getId());

        detailList.forEach(s -> {
            s.setStructuralId(bizEmergeMaterialManagement.getId());
            this.bizMaterialsManagementManager.save(s);
        });
    }



    @Override
    public CommonResult<String> importData(String manId, MultipartFile file) {
            try {
                List<BizMaterialsManagement> detailList = new ArrayList<>();
                List<BizEmergeMaterialManagementDetailExcel> detailExcels = ExcelUtil.readExcel(BizEmergeMaterialManagementDetailExcel.class, file);
                //方向
                if(null != detailExcels && detailExcels.size() > 0){
                    for (BizEmergeMaterialManagementDetailExcel detailExcel : detailExcels) {
                        if(null != detailExcel.getMaterialTypeValue()){
                            BizMaterialsManagement detail = new BizMaterialsManagement();
                            BeanUtils.copyProperties(detailExcel,detail);
                            detail.setStructuralId(manId);
                            detailList.add(detail);
                        }

                    }
                }
                bizMaterialsManagementManager.saveBatch(detailList);
                return new CommonResult<String>(true,"导入成功");
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("导入失败");
            }


        }
}
