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

import com.artfess.base.context.BaseContext;
import com.artfess.base.query.*;
import com.artfess.uc.dao.OrgDao;
import com.artfess.uc.model.Org;
import com.artfess.yhxt.basedata.manager.AccessoryManager;
import com.artfess.yhxt.basedata.manager.RoadManager;
import com.artfess.yhxt.basedata.model.*;
import  com.artfess.yhxt.basedata.dao.BizRoadsideFacilitiesDao;
import  com.artfess.yhxt.basedata.manager.BizRoadsideFacilitiesManager;
import com.artfess.base.manager.impl.BaseManagerImpl;
import com.artfess.yhxt.statistics.vo.Org4roadSideVO;
import com.artfess.yhxt.statistics.vo.Org4sideSlopelVO;
import com.artfess.yhxt.util.PermissionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

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

/**
 * 沿线设施 服务实现类
 *
 * @company 阿特菲斯信息技术有限公司
 * @author 王平
 * @since 2021-07-29
 */
@Service
public class BizRoadsideFacilitiesManagerImpl extends BaseManagerImpl<BizRoadsideFacilitiesDao, BizRoadsideFacilities> implements BizRoadsideFacilitiesManager {

    @Resource
    BizRoadsideFacilitiesDao bizRoadsideFacilitiesDao;
    @Resource
    AccessoryManager accessoryManager;
    @Resource
    BaseContext baseContext;
    @Resource
    PermissionUtils permissionUtils;

    @Resource
    private OrgDao orgDao;

    @Resource
    private RoadManager roadManager;

    @Override
    public List<Org4roadSideVO> getRoadSideCount() {
        String orgId ;
        if (StringUtils.isNotEmpty(baseContext.getCurrentOrgId())&&!"0".equals(baseContext.getCurrentOrgId())){
            orgId = baseContext.getCurrentOrgId();
        }else {
            orgId = "1419863231459102720";
        }
        List<Org4roadSideVO> 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){
            Org4roadSideVO fvo = new Org4roadSideVO();
            BeanUtils.copyProperties(org,fvo);
            lists.add(fvo);
        }
        lists = getChild(lists,orgId);


        return this.setCount(lists);
    }

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

        while(it.hasNext()){
            Org4roadSideVO 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 Org4roadSideVO newCount(List<String> ids, Org4roadSideVO orgVO) {

        QueryWrapper<BizRoadsideFacilities> wrapper = new QueryWrapper<>();
        wrapper.in("ROAD_SEGMENT_ID_", ids);
        wrapper.eq("IS_DELE_",0);
        List<BizRoadsideFacilities> sides = this.list(wrapper);

        List<BizRoadsideFacilities> pivot =
                sides.stream().filter(bizRoadsideFacilities -> Objects.equals(bizRoadsideFacilities.getType(),"1")).collect(Collectors.toList());

        List<BizRoadsideFacilities> ringRoad =
                sides.stream().filter(bizRoadsideFacilities -> Objects.equals(bizRoadsideFacilities.getType(),"2")).collect(Collectors.toList());

        List<BizRoadsideFacilities> tollGate =
                sides.stream().filter(bizRoadsideFacilities -> Objects.equals(bizRoadsideFacilities.getType(),"3")).collect(Collectors.toList());

        List<BizRoadsideFacilities> service =
                sides.stream().filter(bizRoadsideFacilities -> Objects.equals(bizRoadsideFacilities.getType(),"4")).collect(Collectors.toList());

        orgVO.setPivotCount(pivot.size());
        orgVO.setTollGateCount(tollGate.size());
        orgVO.setServiceCount(service.size());
        orgVO.setRingRoadCount(ringRoad.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<Org4roadSideVO> getChild(List<Org4roadSideVO> allList, String pCode) {
        List<Org4roadSideVO> returnList = new ArrayList<>();
        for (Org4roadSideVO entity : allList){
            if (pCode.equals(entity.getParentId())) {
                entity.setChirldren(getChild(allList, entity.getId()));
                returnList.add(entity);
            }
        }
        return returnList;
    }

    @Override
    public PageList<BizRoadsideFacilities> queryBizRoadsideFacilities(QueryFilter<BizRoadsideFacilities> queryFilter) {
        PageBean pageBean = queryFilter.getPageBean();
        HashMap<String, Object> map = new HashMap<>();
        Map<String, Object> params = queryFilter.getParams();
        if (params != null) {
            map.putAll(params);
        }
        if (StringUtils.isNotEmpty(baseContext.getCurrentOrgId())) {
//            queryFilter.addFilter("COMPANY_ID_", String.join("','", baseContext.getCurrentOrgId()), QueryOP.IN, FieldRelation.AND);
            permissionUtils.addPermission(queryFilter);
        }
            IPage<BizRoadsideFacilities> result = baseMapper.getBizRoadsideFacilities(convert2IPage(queryFilter.getPageBean()),map, convert2Wrapper(queryFilter, currentModelClass()));
        return new PageList<BizRoadsideFacilities>(result);
    }

    @Override
    public void updateBizRoadsideFacilities(String id) {
        UpdateWrapper<BizRoadsideFacilities> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq(StringUtils.isNotBlank(id), "id_", id);
        updateWrapper.set("is_dele_", "1");
        bizRoadsideFacilitiesDao.update(null, updateWrapper);
    }

    @Override
    public void saveRoadside(BizRoadsideFacilities bizRoadsideFacilities) {
        //正面图:frontView  侧面图:lateralView 二维平面图:twoDimensionalPlan
        this.save(bizRoadsideFacilities);
        //1.保存正面图
        List<Accessory> accessoriesFrontView = bizRoadsideFacilities.getAccessoriesFrontView();
        if (null != accessoriesFrontView && accessoriesFrontView.size() > 0) {
            //设置附件资源ID
            accessoriesFrontView.forEach(s -> {
                s.setSourceId(bizRoadsideFacilities.getId());
                s.setGroup("frontView");
            });
            //保存正面图
            this.accessoryManager.saveBatch(accessoriesFrontView);
        }

        //2.保存侧面图
        List<Accessory> accessoriesLateralView = bizRoadsideFacilities.getAccessoriesLateralView();
        if (null != accessoriesLateralView && accessoriesLateralView.size() > 0) {
            //设置附件资源ID
            accessoriesLateralView.forEach(s -> {
                s.setSourceId(bizRoadsideFacilities.getId());
                s.setGroup("lateralView");
            });
            //保存侧面图
            this.accessoryManager.saveBatch(accessoriesLateralView);
        }

        //1.保存二维平面图
        List<Accessory> accessoriesTwoDimensionalView = bizRoadsideFacilities.getAccessoriesTwoDimensionalView();
        if (null != accessoriesTwoDimensionalView && accessoriesTwoDimensionalView.size() > 0) {
            //设置附件资源ID
            accessoriesTwoDimensionalView.forEach(s -> {
                s.setSourceId(bizRoadsideFacilities.getId());
                s.setGroup("twoDimensionalPlan");
            });
            //保存二维平面图
            this.accessoryManager.saveBatch(accessoriesTwoDimensionalView);
        }
    }

    @Override
    public void updateRoadside(BizRoadsideFacilities bizRoadsideFacilities) {
//正面图:frontView  侧面图:lateralView 二维平面图:twoDimensionalPlan
        this.update(bizRoadsideFacilities);
        //删除附件
        this.accessoryManager.delAccessoryBySourceId(bizRoadsideFacilities.getId());
        //1.保存正面图
        List<Accessory> accessoriesFrontView = bizRoadsideFacilities.getAccessoriesFrontView();
        if (null != accessoriesFrontView && accessoriesFrontView.size() > 0) {
            //设置附件资源ID
            accessoriesFrontView.forEach(s -> {
                s.setSourceId(bizRoadsideFacilities.getId());
                s.setGroup("frontView");
            });
            //保存正面图
            this.accessoryManager.saveBatch(accessoriesFrontView);
        }

        //2.保存侧面图
        List<Accessory> accessoriesLateralView = bizRoadsideFacilities.getAccessoriesLateralView();
        if (null != accessoriesLateralView && accessoriesLateralView.size() > 0) {
            //设置附件资源ID
            accessoriesLateralView.forEach(s -> {
                s.setSourceId(bizRoadsideFacilities.getId());
                s.setGroup("lateralView");
            });
            //保存侧面图
            this.accessoryManager.saveBatch(accessoriesLateralView);
        }

        //3.保存二维平面图
        List<Accessory> accessoriesTwoDimensionalView = bizRoadsideFacilities.getAccessoriesTwoDimensionalView();
        if (null != accessoriesTwoDimensionalView && accessoriesTwoDimensionalView.size() > 0) {
            //设置附件资源ID
            accessoriesTwoDimensionalView.forEach(s -> {
                s.setSourceId(bizRoadsideFacilities.getId());
                s.setGroup("twoDimensionalPlan");
            });
            //保存二维平面图
            this.accessoryManager.saveBatch(accessoriesTwoDimensionalView);
        }
    }

    @Override
    public BizRoadsideFacilities getByFacilitiesId(String id) {
        BizRoadsideFacilities bizRoadsideFacilities = baseMapper.selectById(id);
        //根据资源ID查询关联的所有附件
        List<Accessory> accessories = accessoryManager.getAccessoryBySourceId(id);
        List<Accessory> accessoriesFrontView = new ArrayList<>();
        List<Accessory> accessoriesLateralView = new ArrayList<>();
        List<Accessory> accessoriesTwoDimensionalView = new ArrayList<>();
        if (accessories!=null &&accessories.size()>0) {
            accessories.forEach(s -> {
                String group = s.getGroup();
                if ("frontView".equalsIgnoreCase(group)) accessoriesFrontView.add(s);
                if ("lateralView".equalsIgnoreCase(group)) accessoriesLateralView.add(s);
                if ("twoDimensionalPlan".equalsIgnoreCase(group)) accessoriesTwoDimensionalView.add(s);
            });
        }
        bizRoadsideFacilities.setAccessoriesFrontView(accessoriesFrontView);
        bizRoadsideFacilities.setAccessoriesLateralView(accessoriesLateralView);
        bizRoadsideFacilities.setAccessoriesTwoDimensionalView(accessoriesTwoDimensionalView);
        return bizRoadsideFacilities;
    }
}
