package com.ruoyi.zdsz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.zdsz.domain.ZArea;
import com.ruoyi.zdsz.domain.bo.ZAreaBo;
import com.ruoyi.zdsz.domain.bo.ZBuildingBo;
import com.ruoyi.zdsz.domain.bo.ZEngineeringNodeBo;
import com.ruoyi.zdsz.domain.vo.*;
import com.ruoyi.zdsz.mapper.ZAreaMapper;
import com.ruoyi.zdsz.service.IZEngineeringNodeService;
import com.ruoyi.zdsz.service.IZMaterialStatisticsService;
import lombok.RequiredArgsConstructor;
import lombok.Value;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.zdsz.domain.bo.ZEngineeringCivilBo;
import com.ruoyi.zdsz.domain.ZEngineeringCivil;
import com.ruoyi.zdsz.mapper.ZEngineeringCivilMapper;
import com.ruoyi.zdsz.service.IZEngineeringCivilService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

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

/**
 * 民用工程Service业务层处理
 *
 * @author ruoyi
 * @date 2023-12-27
 */
@RequiredArgsConstructor
@Service
public class ZEngineeringCivilServiceImpl implements IZEngineeringCivilService {

    private final ZEngineeringCivilMapper baseMapper;
    @Resource
    private ZAreaMapper zAreaMapper;

    @Autowired
    private IZEngineeringNodeService izEngineeringNodeService;
    @Resource
    private IZMaterialStatisticsService izMaterialStatisticsService;

    /**
     * 查询民用工程
     */
    @Override
    public ZEngineeringCivilVo queryById(String id) {
        ZEngineeringCivilVo zEngineeringCivilVo = baseMapper.selectVoById(id);
        ZEngineeringNodeBo zEngineeringNodeBo = new ZEngineeringNodeBo();
        zEngineeringNodeBo.setCreateTime(zEngineeringCivilVo.getCreateTime());
        zEngineeringNodeBo.setCivliId(zEngineeringCivilVo.getId());
        zEngineeringCivilVo.setzEngineeringNodeBoList(izEngineeringNodeService.queryListDetails(zEngineeringNodeBo));
        return zEngineeringCivilVo;
    }

    /**
     * 查询民用工程
     */
    @Override
    public ZEngineeringCivilVo query(String id, String type) {
        ZEngineeringCivilVo zEngineeringCivilVo = baseMapper.selectVoById(id);
        ZEngineeringNodeBo zEngineeringNodeBo = new ZEngineeringNodeBo();
        zEngineeringNodeBo.setCreateTime(zEngineeringCivilVo.getCreateTime());
        zEngineeringNodeBo.setCivliId(zEngineeringCivilVo.getId());
        zEngineeringNodeBo.setType(type);
        zEngineeringCivilVo.setzEngineeringNodeBo(izEngineeringNodeService.query(zEngineeringNodeBo));
        return zEngineeringCivilVo;
    }

    @Override
    public ZEngineeringCivilVo queryByEntityBo(ZEngineeringCivilBo zEngineeringCivilBo) {
        LambdaQueryWrapper<ZEngineeringCivil> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(zEngineeringCivilBo.getAreaId()), ZEngineeringCivil::getAreaId, zEngineeringCivilBo.getAreaId());
        lqw.eq(ZEngineeringCivil::getBuildingId, zEngineeringCivilBo.getBuildingId());
        lqw.eq(ZEngineeringCivil::getUnitId, zEngineeringCivilBo.getUnitId());
        lqw.eq(ZEngineeringCivil::getHouseId, zEngineeringCivilBo.getHouseId());
        lqw.eq(StringUtils.isNotBlank(zEngineeringCivilBo.getEnginCycle()), ZEngineeringCivil::getEnginCycle, zEngineeringCivilBo.getEnginCycle());
        lqw.eq(StringUtils.isNotBlank(zEngineeringCivilBo.getEnginType()), ZEngineeringCivil::getEnginType, zEngineeringCivilBo.getEnginType());
        lqw.eq(StringUtils.isNotBlank(zEngineeringCivilBo.getEnginClassification()), ZEngineeringCivil::getEnginClassification, zEngineeringCivilBo.getEnginClassification());
        return baseMapper.selectVoOne(lqw);
    }

    /**
     * 查询民用工程列表
     */
    @Override
    public TableDataInfo<ZEngineeringCivilVo> queryPageList(ZEngineeringCivilBo bo, PageQuery pageQuery) {
        Page<ZBuildingBo> page = new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize());
        Page<ZEngineeringCivilVo> result = baseMapper.queryPageList(bo, page);
        return TableDataInfo.build(result);
    }

    /**
     * 查询民用工程列表
     */
    @Override
    public List<ZEngineeringCivilVo> queryList(ZEngineeringCivilBo bo) {
        LambdaQueryWrapper<ZEngineeringCivil> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ZEngineeringCivil> buildQueryWrapper(ZEngineeringCivilBo bo) {
        LambdaQueryWrapper<ZEngineeringCivil> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getDistrict()), ZEngineeringCivil::getDistrict, bo.getDistrict());
        lqw.eq(StringUtils.isNotBlank(bo.getAreaId()), ZEngineeringCivil::getAreaId, bo.getAreaId());
        lqw.eq(ZEngineeringCivil::getBuildingId, bo.getBuildingId());
        lqw.eq(ZEngineeringCivil::getUnitId, bo.getUnitId());
        lqw.eq(ZEngineeringCivil::getHouseId, bo.getHouseId());
        lqw.eq(StringUtils.isNotBlank(bo.getEnginType()), ZEngineeringCivil::getEnginType, bo.getEnginType());
        lqw.eq(StringUtils.isNotBlank(bo.getEnginClassification()), ZEngineeringCivil::getEnginClassification, bo.getEnginClassification());
        lqw.eq(StringUtils.isNotBlank(bo.getEnginCycle()), ZEngineeringCivil::getEnginCycle, bo.getEnginCycle());
        lqw.eq(StringUtils.isNotBlank(bo.getCompletionStatus()), ZEngineeringCivil::getCompletionStatus, bo.getCompletionStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getImgUrl()), ZEngineeringCivil::getImgUrl, bo.getImgUrl());
        return lqw;
    }

    @Autowired
    private ZEngineeringNodeServiceImpl zEngineeringNodeService;

    /**
     * 新增民用工程
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(ZEngineeringCivilBo bo) {
        ZEngineeringCivil add = BeanUtil.toBean(bo, ZEngineeringCivil.class);
        validEntityBeforeSave(add);
        LambdaQueryWrapper<ZEngineeringCivil> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getAreaId()), ZEngineeringCivil::getAreaId, bo.getAreaId());
        lqw.eq(ZEngineeringCivil::getBuildingId, bo.getBuildingId());
        lqw.eq(ZEngineeringCivil::getUnitId, bo.getUnitId());
        lqw.eq(ZEngineeringCivil::getHouseId, bo.getHouseId());
        lqw.eq(StringUtils.isNotBlank(bo.getEnginCycle()), ZEngineeringCivil::getEnginCycle, bo.getEnginCycle());
        lqw.eq(StringUtils.isNotBlank(bo.getEnginClassification()), ZEngineeringCivil::getEnginClassification, bo.getEnginClassification());
        ZEngineeringCivilVo zEngineeringCivilVo = baseMapper.selectVoOne(lqw);
        if ("indoor_engin".equals(bo.getEnginClassification())) {
            izMaterialStatisticsService.insert(bo);
        }
        if (ObjectUtils.isEmpty(zEngineeringCivilVo)) {
            boolean flag = baseMapper.insert(add) > 0;
            if (flag) {
                bo.setId(add.getId());
                if (ObjectUtils.isEmpty(bo.getzEngineeringNodeBo())) {
                    for (ZEngineeringNodeBo zEngineeringNodeBo : bo.getzEngineeringNodeBoList()) {
                        zEngineeringNodeBo.setCivliId(add.getId());
                        zEngineeringNodeBo.setCreateTime(add.getCreateTime());
                        zEngineeringNodeService.insert(zEngineeringNodeBo);
                    }

                } else {
                    ZEngineeringNodeBo zEngineeringNodeBo = bo.getzEngineeringNodeBo();
                    zEngineeringNodeBo.setCivliId(add.getId());
                    zEngineeringNodeBo.setCreateTime(add.getCreateTime());
                    zEngineeringNodeService.insert(zEngineeringNodeBo);
                }
            }
            return flag;
        } else {
            if (ObjectUtils.isEmpty(bo.getzEngineeringNodeBo())) {
                for (ZEngineeringNodeBo zEngineeringNodeBo : bo.getzEngineeringNodeBoList()) {
                    zEngineeringNodeBo.setCivliId(add.getId());
                    zEngineeringNodeBo.setCreateTime(add.getCreateTime());
                    zEngineeringNodeService.insert(zEngineeringNodeBo);
                }

            } else {
                ZEngineeringNodeBo zEngineeringNodeBo = bo.getzEngineeringNodeBo();
                zEngineeringNodeBo.setCivliId(zEngineeringCivilVo.getId());
                zEngineeringNodeBo.setType(zEngineeringNodeBo.getType());
                zEngineeringNodeBo.setCreateTime(zEngineeringCivilVo.getCreateTime());
                ZEngineeringNodeBo query = zEngineeringNodeService.query(zEngineeringNodeBo);
                if (!ObjectUtils.isEmpty(query)) {
                    zEngineeringNodeBo.setId(query.getId());
                }
                zEngineeringNodeService.insert(zEngineeringNodeBo);
            }
            return true;
        }
    }

    /**
     * 修改民用工程
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(ZEngineeringCivilBo bo) {
        ZEngineeringCivil update = BeanUtil.toBean(bo, ZEngineeringCivil.class);
        validEntityBeforeSave(update);
        boolean flag = baseMapper.updateById(update) > 0;
        if (flag) {
            ZEngineeringCivilVo zEngineeringCivilVo = baseMapper.selectVoById(update.getId());
            ZEngineeringNodeBo zEngineeringNodeBo = bo.getzEngineeringNodeBo();
            zEngineeringNodeBo.setCivliId(zEngineeringCivilVo.getId());
            zEngineeringNodeBo.setCreateTime(zEngineeringCivilVo.getCreateTime());
            zEngineeringNodeService.update(zEngineeringNodeBo);
        }
        return flag;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ZEngineeringCivil entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除民用工程
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
            ids.forEach(item -> {
                ZEngineeringCivilVo zEngineeringCivilVo = baseMapper.selectVoById(item);
                ZEngineeringNodeBo zEngineeringNodeBo = new ZEngineeringNodeBo();
                zEngineeringNodeBo.setCreateTime(zEngineeringCivilVo.getCreateTime());
                zEngineeringNodeBo.setCivliId(zEngineeringCivilVo.getId());
                List<ZEngineeringNodeBo> zEngineeringNodeBos = izEngineeringNodeService.queryListDetails(zEngineeringNodeBo);
                zEngineeringNodeBos.forEach(ite -> zEngineeringNodeService.delete(ite));
            });
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public int getCivilByAreaId(Collection<String> ids) {
        LambdaQueryWrapper<ZEngineeringCivil> lqw = Wrappers.lambdaQuery();
        lqw.in(!ids.isEmpty(), ZEngineeringCivil::getAreaId, ids);
        return baseMapper.selectVoList(lqw).size();
    }

    @Override
    public int getCivilByhouseId(Collection<String> ids) {
        LambdaQueryWrapper<ZEngineeringCivil> lqw = Wrappers.lambdaQuery();
        lqw.in(!ids.isEmpty(), ZEngineeringCivil::getHouseId, ids);
        return baseMapper.selectVoList(lqw).size();
    }

    @Override
    public List getObtainRoomcCompletionInformationList(ZEngineeringCivilBo bo) {
      List<roomStatusVo> roomStatusList=  baseMapper.getObtainRoomcCompletionInformationList(bo);
      Map<String ,List<roomStatusVo>> map=new HashMap<>();
        map=  roomStatusList.stream().collect(Collectors.groupingBy(item->item.getUnitName()));
        List areaList=new ArrayList();
        map.forEach((key,value)->{
            BulidingStatusVo bulidingStatusVo=new BulidingStatusVo();
            bulidingStatusVo.setUnitName(key);
            bulidingStatusVo.setUnitId(value.get(0).getUnitId());
            //bulidingStatusVo.setRoomStatusVoList(value);
            Map<String ,List<roomStatusVo>> roomMap= value.stream().collect(Collectors.groupingBy(item-> String.valueOf(item.getRoomName().length()>3?item.getRoomName().charAt(1):item.getRoomName().charAt(0))));;
            List willDone = value.stream().filter(item->item.getRoomStatus().equals("未完工")).collect(Collectors.toList());
            List notstart =value.stream().filter(item->item.getRoomStatus().equals("未开工")).collect(Collectors.toList());
            List done =value.stream().filter(item->item.getRoomStatus().equals("完工")).collect(Collectors.toList());
            List<List<roomStatusVo>> roomStatusVoList=new ArrayList<>();
            roomMap.forEach((key1,value1)->{
                roomStatusVoList.add(value1);
            });
            bulidingStatusVo.setRoomStatusVoList(roomStatusVoList);
            bulidingStatusVo.setDone(String.valueOf(done.size()));
            bulidingStatusVo.setWillDone(String.valueOf(willDone.size()));
            bulidingStatusVo.setNotstart(String.valueOf(notstart.size()));
            areaList.add(bulidingStatusVo);
        });
        return areaList ;
    }

    @Override
    public TableDataInfo<areaStatusVo> getAreaCompletionInformationList(ZEngineeringCivilBo bo,PageQuery po) {
        LambdaQueryWrapper<ZArea> lqw =Wrappers.lambdaQuery();
        Page<ZBuildingBo> page = new Page<>(po.getPageNum(), po.getPageSize());
        Page<ZAreaVo> result = zAreaMapper.selectVoPage(po.build(),lqw);
         List<ZAreaVo> IdList= result.getRecords();
          List Id=new ArrayList();
        IdList.stream().forEach(item->{
            Id.add(item.getId());
        });
       List<areaWillDoneVo> hourseList=baseMapper.getAreaCompletionInformationList(Id,bo.getEnginCycle());
      Map<String,List<areaWillDoneVo>> stringListMap=  hourseList.stream().collect(Collectors.groupingBy(item->item.getAreaId()));
      List<areaStatusVo> areaList=new ArrayList<>();
        stringListMap.forEach((key,value)->{
            areaStatusVo  areaStatusVo=new areaStatusVo();
            List willDone = value.stream().filter(item->item.getRoomStatus().equals("未完工")).collect(Collectors.toList());
            List notstart =value.stream().filter(item->item.getRoomStatus().equals("未开工")).collect(Collectors.toList());
            List done =value.stream().filter(item->item.getRoomStatus().equals("完工")).collect(Collectors.toList());
            areaStatusVo.setAreaId(key);
            areaStatusVo.setAreaName(value.get(0).getName());
            areaStatusVo.setWillDone(String.valueOf(willDone.size()));
            areaStatusVo.setNotstart(String.valueOf(notstart.size()));
            areaStatusVo.setDone(String.valueOf(done.size()));
            areaList.add(areaStatusVo);
        });
        Page<areaStatusVo> page2=new Page<>();
        BeanUtils.copyProperties(result,page2);
        page2.setRecords(areaList);
        return TableDataInfo.build(page2);
    }

    @Override
    public areaStatusVo getsumStatus(ZEngineeringCivilBo bo) {
        areaStatusVo areaStatusVo=  baseMapper.getsumStatus(bo.getEnginCycle());
        areaStatusVo.setNotstart(String.valueOf(Integer.parseInt(areaStatusVo.getNotstart())-Integer.parseInt(areaStatusVo.getWillDone())-Integer.parseInt(areaStatusVo.getDone())));
        return areaStatusVo;
    }
}
