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.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.RoadManager;
import com.artfess.yhxt.basedata.model.*;
import com.artfess.yhxt.basedata.dao.BizCulvertInformationDao;
import com.artfess.yhxt.basedata.manager.BizCulvertInformationManager;
import com.artfess.base.manager.impl.BaseManagerImpl;
import com.artfess.yhxt.basedata.vo.CulvertCheckVo;
import com.artfess.yhxt.basedata.vo.CulvertRegularVo;
import com.artfess.yhxt.budget.model.YearBudget;
import com.artfess.yhxt.budget.model.YearBudgetDetailed;
import com.artfess.yhxt.check.regular.dao.CulvertOftenCheckDao;
import com.artfess.yhxt.check.regular.dao.CulvertRegularCheckDao;
import com.artfess.yhxt.check.regular.model.CulvertOftenCheck;
import com.artfess.yhxt.check.regular.model.CulvertRegularCheck;
import com.artfess.yhxt.contract.model.Contract;
import com.artfess.yhxt.statistics.dao.WorkbenchDao;
import com.artfess.yhxt.statistics.vo.Org4ContractVO;
import com.artfess.yhxt.statistics.vo.Org4bridgeInfoVO;
import com.artfess.yhxt.statistics.vo.Org4culvertVO;
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.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("BizCulvertInformationManager")
public class BizCulvertInformationManagerImpl extends BaseManagerImpl<BizCulvertInformationDao, BizCulvertInformation> implements BizCulvertInformationManager {

    @Resource
    BizCulvertInformationDao bizCulvertInformationDao;
    @Resource
    OrgManager orgManager;
    @Resource
    WorkbenchDao workbenchDao;

    @Resource
    CulvertOftenCheckDao culvertOftenCheckDao;
    @Resource
    CulvertRegularCheckDao culvertRegularCheckDao;
    @Resource
    AccessoryManager accessoryManager;

    @Resource
    BaseContext baseContext;
    @Resource
    PermissionUtils permissionUtils;

    @Resource
    private OrgDao orgDao;

    @Resource
    private RoadManager roadManager;


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


        return this.setCount(lists);
    }


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

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

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

        //盖板
        List<BizCulvertInformation> board =
                culverts.stream().filter(information -> Objects.equals(information.getType(),"1")).collect(Collectors.toList());

        //管涵
        List<BizCulvertInformation> pipe =
                culverts.stream().filter(information -> Objects.equals(information.getType(),"2")).collect(Collectors.toList());

        //箱涵
        List<BizCulvertInformation> box =
                culverts.stream().filter(information -> Objects.equals(information.getType(),"3")).collect(Collectors.toList());

        //拱涵
        List<BizCulvertInformation> arch =
                culverts.stream().filter(information -> Objects.equals(information.getType(),"4")).collect(Collectors.toList());

        //倒虹吸
        List<BizCulvertInformation> inverted =
                culverts.stream().filter(information -> Objects.equals(information.getType(),"5")).collect(Collectors.toList());

        //板涵
        List<BizCulvertInformation> plank =
                culverts.stream().filter(information -> Objects.equals(information.getType(),"6")).collect(Collectors.toList());

        orgVO.setArch(arch.size());
        orgVO.setBoard(board.size());
        orgVO.setBox(box.size());
        orgVO.setInverted(inverted.size());
        orgVO.setPlank(plank.size());
        orgVO.setPipe(pipe.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<Org4culvertVO> getChild(List<Org4culvertVO> allList, String pCode) {
        List<Org4culvertVO> returnList = new ArrayList<>();
        for (Org4culvertVO entity : allList){
            if (pCode.equals(entity.getParentId())) {
                entity.setChirldren(getChild(allList, entity.getId()));
                returnList.add(entity);
            }
        }
        return returnList;
    }

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

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

    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<CulvertCheckVo> queryBizCulvert(QueryFilter<BizCulvertInformation> queryFilter) throws Exception {
        queryFilter.addFilter("is_dele_", "0", QueryOP.EQUAL);

        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<CulvertCheckVo> result = baseMapper.queryBizCulvert(convert2IPage(queryFilter.getPageBean()), map, convert2Wrapper(queryFilter, currentModelClass()));
        List<CulvertCheckVo> records = result.getRecords();

        LocalDate today = LocalDate.now();
        for (CulvertCheckVo record : records) {
            //涵洞id
            String id = record.getId();
            QueryWrapper<CulvertOftenCheck> culvertOftenCheckQueryWrapper = new QueryWrapper<>();
            culvertOftenCheckQueryWrapper.eq(record.getCheckDate()!=null,"CHECK_DATE_",record.getCheckDate());
            culvertOftenCheckQueryWrapper.eq("CULVERT_ID_",id);
            List<CulvertOftenCheck> culvertOftenChecks = culvertOftenCheckDao.selectList(culvertOftenCheckQueryWrapper);
            if (culvertOftenChecks!=null &&culvertOftenChecks.size()>0){
                record.setEvaluateValue(culvertOftenChecks.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<CulvertCheckVo>(result);
    }

    @Override
    public PageList<CulvertRegularVo> queryCulvertRegular(QueryFilter<BizCulvertInformation> 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<CulvertRegularVo> result = baseMapper.queryCulvertRegularCheckVo(convert2IPage(queryFilter.getPageBean()),map, convert2Wrapper(queryFilter, currentModelClass()));
        List<CulvertRegularVo> records = result.getRecords();
        LocalDate today = LocalDate.now();

        for (CulvertRegularVo record : records) {
            //涵洞ID
            String id = record.getId();
            QueryWrapper<CulvertRegularCheck> culvertRegularCheckQueryWrapper = new QueryWrapper<>();
            culvertRegularCheckQueryWrapper.eq(record.getCheckDate()!=null,"CHECK_DATE_",record.getCheckDate());
            culvertRegularCheckQueryWrapper.eq("CULVERT_ID_",id);
            List<CulvertRegularCheck> culvertRegularChecks = culvertRegularCheckDao.selectList(culvertRegularCheckQueryWrapper);
            if (culvertRegularChecks!=null && culvertRegularChecks.size()>0){
                record.setEvaluateValue(culvertRegularChecks.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<>(result);
    }

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

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

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

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

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

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

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