package com.ruoyi.zdsz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.helper.LoginHelper;
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.ZEngiineeringPhoto;
import com.ruoyi.zdsz.domain.ZEngineeringInfrastructure;
import com.ruoyi.zdsz.domain.ZEngineeringPipeJacking;
import com.ruoyi.zdsz.domain.bo.*;
import com.ruoyi.zdsz.domain.vo.*;
import com.ruoyi.zdsz.mapper.ZEngineeringInfrastructureMapper;
import com.ruoyi.zdsz.service.IZEngiineeringPhotoService;
import com.ruoyi.zdsz.service.IZEngineeringInfrastructureService;
import com.ruoyi.zdsz.service.IZEngineeringNodeService;
import com.ruoyi.zdsz.service.IZEngineeringReviewService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
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 2024-01-03
 */
@RequiredArgsConstructor
@Service
public class ZEngineeringInfrastructureServiceImpl implements IZEngineeringInfrastructureService {

    @Resource
    private final ZEngineeringInfrastructureMapper baseMapper;

    @Resource
    private final IZEngineeringNodeService izEngineeringNodeService;
    @Resource
    private IZEngiineeringPhotoService photoService;

    @Resource
    private final IZEngineeringReviewService izEngineeringReviewService;

    /**
     * 查询基建工程
     */
    @Override
    public ZEngineeringInfrastructureVo queryById(String id){
        ZEngineeringInfrastructureVo vo = baseMapper.selectVoById(id);
        ZEngineeringNodeBo zEngineeringNodeBo = new ZEngineeringNodeBo();
        zEngineeringNodeBo.setCreateTime(vo.getCreateTime());
        zEngineeringNodeBo.setCivliId(vo.getId());
        vo.setzEngineeringNodeBoList(izEngineeringNodeService.queryListDetails(zEngineeringNodeBo));
        //文件
        ZEngiineeringPhotoBo bo1 = new ZEngiineeringPhotoBo();
        bo1.setParentId(vo.getId());
        bo1.setCreateTime(vo.getCreateTime());
        vo.setPics(photoService.queryList(bo1));
        return vo;
    }

    /**
     * 查询基建工程历史
     */
    @Override
    public ZEngineeringInfrastructureVo queryByIdType(String id, String type){
        ZEngineeringInfrastructureVo vo = baseMapper.selectVoById(id);
        ZEngineeringNodeBo zEngineeringNodeBo = new ZEngineeringNodeBo();
        zEngineeringNodeBo.setCreateTime(vo.getCreateTime());
        zEngineeringNodeBo.setCivliId(vo.getId());
        zEngineeringNodeBo.setType(type);
        ZEngineeringNodeBo node = izEngineeringNodeService.query(zEngineeringNodeBo);
        vo.setzEngineeringNodeBo(node);
        return vo;
    }

    /**
     * 查询基建工程下拉
     */
    @Override
    public List<ZEngineeringInfrastructureSelectVo> select(ZEngineeringInfrastructureBo bo) {
        LambdaQueryWrapper<ZEngineeringInfrastructure> lqw = buildQueryWrapper(bo);
        List<ZEngineeringInfrastructureVo> result = baseMapper.selectVoList(lqw);
        List<ZEngineeringInfrastructureSelectVo> list = new ArrayList<>();
        for (ZEngineeringInfrastructureVo vo: result) {
            ZEngineeringInfrastructureSelectVo select = BeanUtil.toBean(vo, ZEngineeringInfrastructureSelectVo.class);
            list.add(select);
        }
        return list;
    }

    /**
     * 查询基建工程列表
     */
    @Override
    public TableDataInfo<ZEngineeringInfrastructureVo> queryPageList(ZEngineeringInfrastructureBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ZEngineeringInfrastructure> lqw = buildQueryWrapper(bo);
        Page<ZEngineeringInfrastructureVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        Map<String, Object> ReviewList = izEngineeringNodeService.ReViewInfrastructureList(result.getRecords());
        result.getRecords().forEach(item -> {
            item.setNodeReViewStateList(ReviewList.get(item.getId()));
        });
        return TableDataInfo.build(result);
    }

    /**
     * 查询基建工程列表
     */
    @Override
    public List<ZEngineeringInfrastructureVo> queryList(ZEngineeringInfrastructureBo bo) {
        LambdaQueryWrapper<ZEngineeringInfrastructure> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ZEngineeringInfrastructure> buildQueryWrapper(ZEngineeringInfrastructureBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ZEngineeringInfrastructure> lqw = Wrappers.lambdaQuery();
        lqw.orderByDesc(ZEngineeringInfrastructure::getCreateTime);
        lqw.like(StringUtils.isNotBlank(bo.getEnginName()), ZEngineeringInfrastructure::getEnginName, bo.getEnginName());
        lqw.eq(StringUtils.isNotBlank(bo.getEnginAddre()), ZEngineeringInfrastructure::getEnginAddre, bo.getEnginAddre());
        lqw.eq(StringUtils.isNotBlank(bo.getConstructUnit()), ZEngineeringInfrastructure::getConstructUnit, bo.getConstructUnit());
        lqw.eq(bo.getStartTime() != null, ZEngineeringInfrastructure::getStartTime, bo.getStartTime());
        lqw.eq(StringUtils.isNotBlank(bo.getPlannedDuration()), ZEngineeringInfrastructure::getPlannedDuration, bo.getPlannedDuration());
        lqw.eq(bo.getCompletedTime() != null, ZEngineeringInfrastructure::getCompletedTime, bo.getCompletedTime());
        lqw.eq(StringUtils.isNotBlank(bo.getEnginContent()), ZEngineeringInfrastructure::getEnginContent, bo.getEnginContent());
        return lqw;
    }

    /**
     * 新增基建工程
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(ZEngineeringInfrastructureBo bo) {
        ZEngineeringInfrastructure add = BeanUtil.toBean(bo, ZEngineeringInfrastructure.class);
        validEntityBeforeSave(add);
        ZEngineeringInfrastructureVo jackingVo = null;
        if (StringUtils.isNotBlank(bo.getId())){
            LambdaQueryWrapper<ZEngineeringInfrastructure> lqw = Wrappers.lambdaQuery();
            lqw.eq(StringUtils.isNotBlank(bo.getId()), ZEngineeringInfrastructure::getId, bo.getId());
             jackingVo = baseMapper.selectVoOne(lqw);
        }
        //如果不存在工程
        if (ObjectUtil.isEmpty(jackingVo)) {
            boolean flag = baseMapper.insert(add) > 0;
            List<ZEngineeringNodeBo> nodeBoList = bo.getzEngineeringNodeBoList();
            if(nodeBoList != null && !nodeBoList.isEmpty()){
                for (ZEngineeringNodeBo nodeBo:nodeBoList) {
                    bo.setId(add.getId());
                    ZEngineeringNodeBo zEngineeringNodeBo = nodeBo;
                    zEngineeringNodeBo.setCivliId(add.getId());
                    zEngineeringNodeBo.setType(nodeBo.getType());
                    zEngineeringNodeBo.setCreateTime(add.getCreateTime());
                    ZEngineeringNodeBo query = izEngineeringNodeService.query(zEngineeringNodeBo);
                    if (!ObjectUtils.isEmpty(query)) {
                        zEngineeringNodeBo.setId(query.getId());
                    }
                    izEngineeringNodeService.insert(zEngineeringNodeBo);
                }
            }
        }
        //存在工程 多info
        else {
            List<ZEngineeringNodeBo> nodeBoList = bo.getzEngineeringNodeBoList();
            if(nodeBoList != null && !nodeBoList.isEmpty()){
                for (ZEngineeringNodeBo nodeBo:nodeBoList) {
                    bo.setId(add.getId());
                    ZEngineeringNodeBo zEngineeringNodeBo = nodeBo;
                    zEngineeringNodeBo.setCivliId(add.getId());
                    zEngineeringNodeBo.setType(nodeBo.getType());
                    zEngineeringNodeBo.setCreateTime(add.getCreateTime());
                    ZEngineeringNodeBo query = izEngineeringNodeService.query(zEngineeringNodeBo);
                    if (!ObjectUtils.isEmpty(query)) {
                        zEngineeringNodeBo.setId(query.getId());
                    }
                    izEngineeringNodeService.insert(zEngineeringNodeBo);
                }
            }
        }
        //文件集合
        if (!bo.getFiles().isEmpty()){
            List<ZEngiineeringPhoto> list = new ArrayList<>();
            bo.getFiles().forEach(o->{
                ZEngiineeringPhoto pic = new ZEngiineeringPhoto();
                pic.setParentId(bo.getId());
                pic.setPicUrl(o.getUrl());
                pic.setFileName(o.getName());
                pic.setCreateBy(String.valueOf(LoginHelper.getUsername()));
                pic.setCreateTime(new Date());
                pic.setUpdateBy(String.valueOf(LoginHelper.getUsername()));
                pic.setUpdateTime(new Date());
                list.add(pic);
            });
            if (!list.isEmpty()) {
                photoService.insertBatch(list);
            }
        }
        return true;
    }

    /**
     * 新增基建工程App
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBoApp(ZEngineeringInfrastructureBo bo) {
        ZEngineeringInfrastructure add = BeanUtil.toBean(bo, ZEngineeringInfrastructure.class);
        validEntityBeforeSave(add);
        LambdaQueryWrapper<ZEngineeringInfrastructure> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getId()), ZEngineeringInfrastructure::getId, bo.getId());
        ZEngineeringInfrastructureVo infrastructureVo = baseMapper.selectVoOne(lqw);
        boolean flag = false;
        ZEngineeringNodeBo zEngineeringNodeBo = bo.getzEngineeringNodeBo();
        zEngineeringNodeBo.setCivliId(infrastructureVo.getId());
        zEngineeringNodeBo.setType(zEngineeringNodeBo.getType());
        zEngineeringNodeBo.setCreateTime(infrastructureVo.getCreateTime());
        ZEngineeringNodeBo query = izEngineeringNodeService.query(zEngineeringNodeBo);
        if (!ObjectUtils.isEmpty(query)) {
            zEngineeringNodeBo.setId(query.getId());
        }
        izEngineeringNodeService.insert(bo.getzEngineeringNodeBo());
        flag = true;

        return flag;
    }
    private void doPhotos(ZEngineeringInfrastructure update, ZEngineeringInfrastructureBo bo) {
        List<ZEngiineeringPhoto> list = new ArrayList<>();

        // 查询数据库中已存在的文件列表
        ZEngiineeringPhotoBo bo1 = new ZEngiineeringPhotoBo();
        bo1.setParentId(update.getId());
        bo1.setCreateTime(update.getCreateTime());
        List<String> existingPhotos = photoService.queryList(bo1).stream()
            .map(ZEngiineeringPhotoVo::getPicUrl)
            .collect(Collectors.toList());

        // 插入前端传来的新文件
        for (ZFileBo pic : bo.getFiles()) {
            if (!existingPhotos.contains(pic.getUrl())) {
                ZEngiineeringPhoto newPhoto = new ZEngiineeringPhoto();
                newPhoto.setParentId(bo.getId());
                newPhoto.setPicUrl(pic.getUrl());
                newPhoto.setFileName(pic.getName());
                newPhoto.setCreateBy(String.valueOf(LoginHelper.getUsername()));
                newPhoto.setUpdateBy(String.valueOf(LoginHelper.getUsername()));
                newPhoto.setCreateTime(bo.getCreateTime());
                newPhoto.setUpdateTime(new Date());
                list.add(newPhoto);
            }
        }

        // 删除数据库中多余的文件
        List<String> photosToDelete = existingPhotos.stream()
            .filter(pic -> !bo.getFiles().stream().map(ZFileBo::getUrl).collect(Collectors.toList()).contains(pic))
            .collect(Collectors.toList());
        if (!photosToDelete.isEmpty()) {
            photosToDelete.forEach(item->{
                ZEngiineeringPhoto zEngiineeringPhoto=new ZEngiineeringPhoto();
                zEngiineeringPhoto.setPicUrl(item);
                zEngiineeringPhoto.setCreateTime(bo.getCreateTime());
                photoService.deleteWithValid(zEngiineeringPhoto);
            });
        }

        // 批量插入新图片
        if (!list.isEmpty()) {
            photoService.insertBatch(list);
        }
    }
    /**
     * 新增基建工程审核
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean review(ZEngineeringReviewBo bo) {
        ZEngineeringReviewBo zEngineeringReviewBo = new ZEngineeringReviewBo();
        zEngineeringReviewBo.setEngInfoId(bo.getEngInfoId());
        List<ZEngineeringReviewVo> voList = izEngineeringReviewService.queryList(zEngineeringReviewBo);
        if(voList.size() == 0){
            return izEngineeringReviewService.insert(bo);
        }else {
            bo.setId(voList.get(0).getId());
            return izEngineeringReviewService.updateByBo(bo);
        }
    }

    /**
     * 修改基建工程
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(ZEngineeringInfrastructureBo bo) {
        ZEngineeringInfrastructure update = BeanUtil.toBean(bo, ZEngineeringInfrastructure.class);
        validEntityBeforeSave(update);
        int i = baseMapper.updateById(update);
        if (i>0){
            ZEngineeringInfrastructureVo jackingVo = baseMapper.selectVoById(update.getId());
            ZEngineeringNodeBo zEngineeringNodeBo = bo.getzEngineeringNodeBo();
            if (!ObjectUtils.isEmpty(zEngineeringNodeBo)){
                //多info
                if (zEngineeringNodeBo.getzEngineeringInfoBoList()!=null&&!zEngineeringNodeBo.getzEngineeringInfoBoList().isEmpty()){
                    List<ZEngineeringInfoBo> engineeringInfoBoList = zEngineeringNodeBo.getzEngineeringInfoBoList();
                    if (engineeringInfoBoList != null && !engineeringInfoBoList.isEmpty()) {
                        izEngineeringNodeService.updateMuch(zEngineeringNodeBo);
                    }
                }
                //单info
                if (!ObjectUtil.isEmpty(zEngineeringNodeBo.getzEngineeringInfoBo())) {
                    zEngineeringNodeBo.setCivliId(jackingVo.getId());
                    zEngineeringNodeBo.setCreateTime(jackingVo.getCreateTime());
                    izEngineeringNodeService.update(zEngineeringNodeBo);
                }
            }
            if (bo.getFiles()!=null&&!bo.getFiles().isEmpty()) {
                this.doPhotos(update,bo);
            }
        }
        return i>0;
    }

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

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