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.TunnelInformationDao;
import com.artfess.yhxt.basedata.manager.AccessoryManager;
import com.artfess.yhxt.basedata.manager.RoadManager;
import com.artfess.yhxt.basedata.manager.TunnelInformationManager;
import com.artfess.yhxt.basedata.model.Accessory;
import com.artfess.yhxt.basedata.model.BridgeInformation;
import com.artfess.yhxt.basedata.model.Road;
import com.artfess.yhxt.basedata.model.TunnelInformation;
import com.artfess.base.manager.impl.BaseManagerImpl;
import com.artfess.uc.api.model.IUser;
import com.artfess.yhxt.basedata.vo.TunnelCheckVo;
import com.artfess.yhxt.basedata.vo.TunnelRegularVo;
import com.artfess.yhxt.check.regular.dao.TunnelOftenCheckDao;
import com.artfess.yhxt.check.regular.dao.TunnelRegularCheckDao;
import com.artfess.yhxt.check.regular.model.TunnelOftenCheck;
import com.artfess.yhxt.check.regular.model.TunnelRegularCheck;
import com.artfess.yhxt.statistics.dao.WorkbenchDao;
import com.artfess.yhxt.statistics.vo.Org4BridgeVO;
import com.artfess.yhxt.statistics.vo.Org4bridgeInfoVO;
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.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;

/**
 * 隧道信息表 服务实现类
 *
 * @company 阿特菲斯信息技术有限公司
 * @author xzh
 * @since 2021-07-28
 */
@Service
public class TunnelInformationManagerImpl extends BaseManagerImpl<TunnelInformationDao, TunnelInformation> implements TunnelInformationManager {

    @Resource
    private TunnelOftenCheckDao tunnelOftenCheckDao;
    @Resource
    private TunnelRegularCheckDao tunnelRegularCheckDao;
    @Resource
    private BaseContext baseContext;
    @Resource
    private AccessoryManager accessoryManager;
    @Resource
    PermissionUtils permissionUtils;

    @Resource
    private OrgDao orgDao;
    @Resource
    private OrgManager orgManager;
    @Resource
    private WorkbenchDao workbenchDao;

    @Resource
    private RoadManager roadManager;



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


        return this.setCount(lists);
    }

    public List<Org4tunnelVO> setCount(List<Org4tunnelVO> list){

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

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

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


        List<TunnelInformation> biggestList =
                tunnels.stream().filter(tunnelInformation -> Objects.equals(tunnelInformation.getType(),"1")).collect(Collectors.toList());

        List<TunnelInformation> biggerList =
                tunnels.stream().filter(tunnelInformation -> Objects.equals(tunnelInformation.getType(),"2")).collect(Collectors.toList());

        List<TunnelInformation> bigList =
                tunnels.stream().filter(tunnelInformation -> Objects.equals(tunnelInformation.getType(),"3")).collect(Collectors.toList());

        List<TunnelInformation> smallList =
                tunnels.stream().filter(tunnelInformation -> Objects.equals(tunnelInformation.getType(),"4")).collect(Collectors.toList());

        String biggest = String.format("%.2f",biggestList.stream().mapToDouble(TunnelInformation::getLength).sum())+"/"+biggestList.size();

        String bigger = String.format("%.2f",biggerList.stream().mapToDouble(TunnelInformation::getLength).sum())+"/"+biggerList.size();

        String big = String.format("%.2f",bigList.stream().mapToDouble(TunnelInformation::getLength).sum())+"/"+bigList.size();

        String small = String.format("%.2f",smallList.stream().mapToDouble(TunnelInformation::getLength).sum())+"/"+smallList.size();

        String all = String.format("%.2f",tunnels.stream().mapToDouble(TunnelInformation::getLength).sum())+"/"+tunnels.size();

        orgVO.setBig(big);
        orgVO.setBigger(bigger);
        orgVO.setBiggest(biggest);
        orgVO.setSmall(small);
        orgVO.setAll(all);

        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<Org4tunnelVO> getChild(List<Org4tunnelVO> allList, String pCode) {
        List<Org4tunnelVO> returnList = new ArrayList<>();
        for (Org4tunnelVO 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<TunnelCheckVo> queryTunnel(QueryFilter<TunnelInformation> 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<TunnelCheckVo> result = baseMapper.queryTunnel(convert2IPage(queryFilter.getPageBean()),map, convert2Wrapper(queryFilter, currentModelClass()));

        List<TunnelCheckVo> records = result.getRecords();
        LocalDate today = LocalDate.now();
        for (TunnelCheckVo record : records) {
            QueryWrapper<TunnelOftenCheck> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(record.getCheckDate()!=null,"CHECK_DATE_",record.getCheckDate());
            queryWrapper.eq("TUNNEL_ID_",record.getId());
            List<TunnelOftenCheck> tunnelRegularChecks = tunnelOftenCheckDao.selectList(queryWrapper);
            if (tunnelRegularChecks!=null && tunnelRegularChecks.size()>0){
                record.setEvaluateValue(tunnelRegularChecks.get(0).getEvaluateValue());
            }
            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<TunnelCheckVo>(result);
    }

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

    @Override
    public void checkNumber(TunnelInformation tunnelInformation) {
        QueryWrapper<TunnelInformation> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(tunnelInformation.getId())) {
            queryWrapper.notIn("id_", tunnelInformation.getId());
        }
        queryWrapper.eq("NUMBER_", tunnelInformation.getNumber());
        queryWrapper.eq("IS_DELE_", "0");
        List<TunnelInformation> 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<TunnelInformation> queryTunnelInformation(QueryFilter<TunnelInformation> 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<TunnelInformation> result = baseMapper.queryTunnelInformation(convert2IPage(queryFilter.getPageBean()), map,convert2Wrapper(queryFilter, currentModelClass()));
        return new PageList<>(result);
    }

    @Override
    public PageList<TunnelRegularVo> queryTunnelRegular(QueryFilter<TunnelInformation> 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<TunnelRegularVo> result = baseMapper.queryTunnelRegularCheckVo(convert2IPage(queryFilter.getPageBean()),map, convert2Wrapper(queryFilter, currentModelClass()));
        List<TunnelRegularVo> records = result.getRecords();

        LocalDate today = LocalDate.now();
        for (TunnelRegularVo record : records) {
            QueryWrapper<TunnelRegularCheck> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(record.getCheckDate()!=null,"CHECK_DATE_",record.getCheckDate());
            queryWrapper.eq("TUNNEL_ID_",record.getId());
            List<TunnelRegularCheck> tunnelRegularChecks = tunnelRegularCheckDao.selectList(queryWrapper);
            if (tunnelRegularChecks!=null && tunnelRegularChecks.size()>0){
                record.setSkillScoreValue(tunnelRegularChecks.get(0).getSkillScoreValue());
            }

            //设置临期标志
            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 saveTunnel(TunnelInformation tunnelInformation) {
        //正面图:frontView  侧面图:lateralView 二维平面图:twoDimensionalPlan
        this.save(tunnelInformation);
        //1.保存正面图
        List<Accessory> accessoriesFrontView = tunnelInformation.getAccessoriesFrontView();
        if (null != accessoriesFrontView && accessoriesFrontView.size() > 0) {
            //设置附件资源ID
            accessoriesFrontView.forEach(s -> {
                s.setSourceId(tunnelInformation.getId());
                s.setGroup("frontView");
            });
            //保存正面图
            this.accessoryManager.saveBatch(accessoriesFrontView);
        }

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

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

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

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

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