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

import com.artfess.base.context.BaseContext;
import com.artfess.base.query.*;
import com.artfess.base.util.DateUtils;
import com.artfess.uc.api.impl.util.ContextUtil;
import com.artfess.uc.dao.OrgDao;
import com.artfess.uc.manager.OrgManager;
import com.artfess.uc.model.Org;
import com.artfess.yhxt.basedata.dao.SideSlopeInformationDao;
import com.artfess.yhxt.basedata.manager.AccessoryManager;
import com.artfess.yhxt.basedata.manager.RoadManager;
import com.artfess.yhxt.basedata.manager.SideSlopeInformationManager;
import com.artfess.yhxt.basedata.model.Accessory;
import com.artfess.yhxt.basedata.model.Road;
import com.artfess.yhxt.basedata.model.SideSlopeInformation;
import com.artfess.base.manager.impl.BaseManagerImpl;
import com.artfess.uc.api.model.IUser;
import com.artfess.yhxt.basedata.model.TunnelInformation;
import com.artfess.yhxt.basedata.vo.SideSlopCheckVo;
import com.artfess.yhxt.basedata.vo.SideSlopeRegularVo;
import com.artfess.yhxt.check.regular.dao.SideSlopeOftenCheckDao;
import com.artfess.yhxt.check.regular.dao.SideSlopeRegularCheckDao;
import com.artfess.yhxt.check.regular.model.SideSlopeOftenCheck;
import com.artfess.yhxt.check.regular.model.SideSlopeRegularCheck;
import com.artfess.yhxt.check.regular.model.TunnelRegularCheck;
import com.artfess.yhxt.statistics.dao.WorkbenchDao;
import com.artfess.yhxt.statistics.vo.Org4sideSlopelVO;
import com.artfess.yhxt.statistics.vo.Org4tunnelVO;
import com.artfess.yhxt.util.PermissionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.commons.lang3.ObjectUtils;
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.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 边坡信息表 服务实现类
 *
 * @author 向贞好
 * @company 阿特菲斯信息技术有限公司
 * @since 2021-07-28
 */
@Service
public class SideSlopeInformationManagerImpl extends BaseManagerImpl<SideSlopeInformationDao, SideSlopeInformation> implements SideSlopeInformationManager {

    @Resource
    private SideSlopeOftenCheckDao slopeOftenCheckDao;
    @Resource
    private SideSlopeRegularCheckDao sideSlopeRegularCheckDao;
    @Resource
    private BaseContext baseContext;
    @Resource
    private AccessoryManager accessoryManager;
    @Resource
    PermissionUtils permissionUtils;
    @Resource
    OrgManager orgManager;
    @Resource
    WorkbenchDao workbenchDao;

    @Resource
    private OrgDao orgDao;

    @Resource
    private RoadManager roadManager;

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


        return this.setCount(lists);
    }


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

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

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

        BigDecimal height = new BigDecimal(sides.stream().filter(e->null != e.getHeight()).mapToDouble(SideSlopeInformation::getHeight).sum());


        orgVO.setCount(sides.size());
        if (sides.size()>0&&!height.equals(BigDecimal.ZERO)){
            orgVO.setHeight(height.divide(new BigDecimal(sides.size()),2,BigDecimal.ROUND_UP));
        }else {
            orgVO.setHeight(BigDecimal.ZERO);
        }
        orgVO.setLength(new BigDecimal(String.format("%.2f",sides.stream().filter(e->null != e.getLength()).mapToDouble(SideSlopeInformation::getLength).sum())));
        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<Org4sideSlopelVO> getChild(List<Org4sideSlopelVO> allList, String pCode) {
        List<Org4sideSlopelVO> returnList = new ArrayList<>();
        for (Org4sideSlopelVO entity : allList){
            if (pCode.equals(entity.getParentId())) {
                entity.setChirldren(getChild(allList, entity.getId()));
                returnList.add(entity);
            }
        }
        return returnList;
    }

    private List<String> getOrgIds (String currentOrgId){
        List<Org> orgList = orgManager.getByParentId(currentOrgId);
        List<String> collect = orgList.stream().map(Org::getId).collect(Collectors.toList());
        collect.add(currentOrgId);
        return collect;
    }
    @Override
    public PageList<SideSlopCheckVo> querySideSlope(QueryFilter<SideSlopeInformation> queryFilter) throws Exception {
        queryFilter.addFilter("is_dele_", "0", QueryOP.EQUAL);
        PageBean pageBean = queryFilter.getPageBean();
        HashMap<String, Object> map = new HashMap<>();
        Map<String, Object> params = queryFilter.getParams();
        if (params != null) {
            map.putAll(params);
        }
        String baseContextCurrentOrgId = baseContext.getCurrentOrgId();
        if (StringUtils.isNotEmpty(baseContextCurrentOrgId) ){
            permissionUtils.addPermission(queryFilter);
        }

        List<FieldSort> sorter = queryFilter.getSorter();
        for (FieldSort fieldSort : sorter) {
            if(fieldSort.getProperty().equals("checkDate")){
                fieldSort.setProperty("CHECK_DATE_");
            }
        }

        IPage<SideSlopCheckVo> result = baseMapper.querySideSlope(convert2IPage(queryFilter.getPageBean()), map, convert2Wrapper(queryFilter, currentModelClass()));
        List<SideSlopCheckVo> records = result.getRecords();
        LocalDate today = LocalDate.now();
        for (SideSlopCheckVo record : records) {
            QueryWrapper<SideSlopeOftenCheck> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(record.getCheckDate()!=null,"CHECK_DATE_",record.getCheckDate());
            queryWrapper.eq("SIDE_SLOPE_ID_",record.getId());
            List<SideSlopeOftenCheck> sideSlopeOftenChecks = slopeOftenCheckDao.selectList(queryWrapper);
            if (sideSlopeOftenChecks!=null && sideSlopeOftenChecks.size()>0){
                SideSlopeOftenCheck sideSlopeOftenCheck = sideSlopeOftenChecks.get(0);
                record.setEvaluateValue(sideSlopeOftenCheck.getEvaluateValue());
                record.setRummager(sideSlopeOftenCheck.getRummager());
                record.setNoteTaker(sideSlopeOftenCheck.getNoteTaker());
            }
            //设置临期标志
            Date checkDate = record.getCheckDate();
            if(null == checkDate){
                record.setTemporary(0);

            }else {
                Instant instant = checkDate.toInstant();
                ZoneId zoneId = ZoneId.systemDefault();
                LocalDate oldDate = instant.atZone(zoneId).toLocalDate();
                //设置距离上次检查过去多少天
                long dateLength=today.until(oldDate, ChronoUnit.DAYS);
                record.setAlreadyCheckDays((int)Math.abs(dateLength) );

                Date checkNewDay = record.getCheckNewDay();
                Instant instantNew = checkNewDay.toInstant();
                LocalDate newDate = instantNew.atZone(zoneId).toLocalDate();

                long dateDivide=today.until(newDate, ChronoUnit.DAYS);
                if(dateDivide< 0){
                    dateDivide =0;
                }
                record.setCheckDays((int)dateDivide);
            }
        }

        return new PageList<SideSlopCheckVo>(result);
    }

    @Override
    public SideSlopeInformation getSideSlopeById(String id) {
        SideSlopeInformation sideSlopeInformation = 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);
            });
        }
        sideSlopeInformation.setAccessoriesFrontView(accessoriesFrontView);
        sideSlopeInformation.setAccessoriesLateralView(accessoriesLateralView);
        sideSlopeInformation.setAccessoriesTwoDimensionalView(accessoriesTwoDimensionalView);
        return sideSlopeInformation;
    }

    @Override
    public void checkNumber(SideSlopeInformation sideSlopeInformation) {
        QueryWrapper<SideSlopeInformation> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(sideSlopeInformation.getId())) {
            queryWrapper.notIn("id_", sideSlopeInformation.getId());
        }
        queryWrapper.eq("NUMBER_", sideSlopeInformation.getNumber());
        queryWrapper.eq("IS_DELE_", "0");
        List<SideSlopeInformation> list = baseMapper.selectList(queryWrapper);
        if (list.size() > 0) {
            throw new RuntimeException("该边坡编码已经存在");
        }
    }

    @Override
    public Integer getSn() {
        HashMap<String, Object> map = new HashMap<>();
        IUser user = ContextUtil.getCurrentUser();
        if (ObjectUtils.isNotEmpty(user)) {
            map.put("tenant_id_", user.getTenantId());
        }
        return this.getNextSequence(map);
    }

    @Override
    public PageList<SideSlopeInformation> querySideSlopeInformation(QueryFilter<SideSlopeInformation> queryFilter) {
        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<SideSlopeInformation> result = baseMapper.querySideSlopeInformation(convert2IPage(queryFilter.getPageBean()),map, convert2Wrapper(queryFilter, currentModelClass()));
        return new PageList<>(result);
    }

    @Override
    public PageList<SideSlopeRegularVo> queryRegularSideSlope(QueryFilter<SideSlopeInformation> queryFilter) throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        Map<String, Object> params = queryFilter.getParams();
        if (params != null) {
            map.putAll(params);
        }
        if (StringUtils.isNotEmpty(baseContext.getCurrentOrgId()) ){
            permissionUtils.addPermission(queryFilter);
        }
        List<FieldSort> sorter = queryFilter.getSorter();
        for (FieldSort fieldSort : sorter) {
            if(fieldSort.getProperty().equals("checkDate")){
                fieldSort.setProperty("CHECK_DATE_");
            }
        }
        IPage<SideSlopeRegularVo> result = baseMapper.querySideSlopeRegularCheckVo(convert2IPage(queryFilter.getPageBean()),map, convert2Wrapper(queryFilter, currentModelClass()));
        List<SideSlopeRegularVo> records = result.getRecords();

        LocalDate today = LocalDate.now();
        for (SideSlopeRegularVo record : records) {
            QueryWrapper<SideSlopeRegularCheck> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(record.getCheckDate()!=null,"CHECK_DATE_",record.getCheckDate());
            queryWrapper.eq("SIDE_SLOPE_ID_",record.getId());
            List<SideSlopeRegularCheck> sideSlopeRegularChecks = sideSlopeRegularCheckDao.selectList(queryWrapper);
            if (sideSlopeRegularChecks!=null && sideSlopeRegularChecks.size()>0){
                record.setOverallRatingValue(sideSlopeRegularChecks.get(0).getOverallRatingValue());
            }
            //设置临期标志
            Date checkDate = record.getCheckDate();
            if(null == checkDate){
                record.setTemporary(0);

            }else {
                Instant instant = checkDate.toInstant();
                ZoneId zoneId = ZoneId.systemDefault();
                LocalDate oldDate = instant.atZone(zoneId).toLocalDate();
                //设置距离上次检查过去多少天
                long dateLength=today.until(oldDate, ChronoUnit.DAYS);
                record.setAlreadyCheckDays((int)Math.abs(dateLength) );

                Date checkNewDay = record.getCheckNewDay();
                Instant instantNew = checkNewDay.toInstant();
                LocalDate newDate = instantNew.atZone(zoneId).toLocalDate();

                long dateDivide=today.until(newDate, ChronoUnit.DAYS);
                if(dateDivide< 0){
                    dateDivide =0;
                }
                record.setCheckDays((int)dateDivide);
            }
        }
        return new PageList<>(result);
    }

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

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

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

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

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

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