package com.ruoyi.zdsz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.handler.MonthTableNameHandler;
import com.ruoyi.zdsz.domain.ZEngiineeringPhoto;
import com.ruoyi.zdsz.domain.ZEngineeringIndustry;
import com.ruoyi.zdsz.domain.bo.*;
import com.ruoyi.zdsz.domain.vo.ZEngiineeringPhotoVo;
import com.ruoyi.zdsz.domain.vo.ZEngineeringIndustryTypeVo;
import com.ruoyi.zdsz.domain.vo.ZEngineeringIndustryVo;
import com.ruoyi.zdsz.mapper.ZEngineeringIndustryMapper;
import com.ruoyi.zdsz.service.IZEngiineeringPhotoService;
import com.ruoyi.zdsz.service.IZEngineeringIndustryService;
import com.ruoyi.zdsz.service.IZEngineeringNodeService;
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-02
 */
@RequiredArgsConstructor
@Service
public class ZEngineeringIndustryServiceImpl implements IZEngineeringIndustryService {

    @Resource
    private final ZEngineeringIndustryMapper baseMapper;

    @Resource
    private IZEngineeringNodeService izEngineeringNodeService;

    @Resource
    private IZEngineeringNodeService nodeService;

    @Resource
    private IZEngiineeringPhotoService photoService;

    /**
     * 查询工业工程|市政工程
     */
    @Override
    public ZEngineeringIndustryVo queryById(String id) {
        ZEngineeringIndustryVo zEngineeringIndustryVo = baseMapper.selectVoById(id);

        ZEngiineeringPhotoBo zEngiineeringPhotoBo = new ZEngiineeringPhotoBo();
        zEngiineeringPhotoBo.setParentId(zEngineeringIndustryVo.getId());
        zEngiineeringPhotoBo.setCreateTime(zEngineeringIndustryVo.getCreateTime());
        zEngineeringIndustryVo.setPics(photoService.queryList(zEngiineeringPhotoBo));
        ZEngineeringNodeBo zEngineeringNodeBo = new ZEngineeringNodeBo();
        zEngineeringNodeBo.setCivliId(id);
        zEngineeringNodeBo.setCreateTime(zEngineeringIndustryVo.getCreateTime());
        List<ZEngineeringNodeBo> zEngineeringNodeBos = izEngineeringNodeService.queryListDetails(zEngineeringNodeBo);
        zEngineeringIndustryVo.setZEngineeringNodeBoList(zEngineeringNodeBos);
        return zEngineeringIndustryVo;
    }

    /**
     * 查询工业工程|市政工程列表
     */
    @Override
    public TableDataInfo<ZEngineeringIndustryVo> queryPageList(ZEngineeringIndustryBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ZEngineeringIndustry> lqw = buildQueryWrapper(bo);
        Page<ZEngineeringIndustryVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询工业工程|市政工程列表
     */
    @Override
    public List<ZEngineeringIndustryVo> queryList(ZEngineeringIndustryBo bo) {
        LambdaQueryWrapper<ZEngineeringIndustry> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ZEngineeringIndustry> buildQueryWrapper(ZEngineeringIndustryBo bo) {
        LambdaQueryWrapper<ZEngineeringIndustry> lqw = Wrappers.lambdaQuery();
        lqw.orderByDesc(ZEngineeringIndustry::getCreateTime);
        lqw.eq(StringUtils.isNotBlank(bo.getEnginType()), ZEngineeringIndustry::getEnginType, bo.getEnginType());
        lqw.like(StringUtils.isNotBlank(bo.getEnginName()), ZEngineeringIndustry::getEnginName, bo.getEnginName());
        lqw.eq(StringUtils.isNotBlank(bo.getEnginClassification()), ZEngineeringIndustry::getEnginClassification, bo.getEnginClassification());
        lqw.eq(StringUtils.isNotBlank(bo.getConstructUnit()), ZEngineeringIndustry::getConstructUnit, bo.getConstructUnit());
        lqw.eq(StringUtils.isNotBlank(bo.getProjectHead()), ZEngineeringIndustry::getProjectHead, bo.getProjectHead());
        lqw.eq(StringUtils.isNotBlank(bo.getSceneHead()), ZEngineeringIndustry::getSceneHead, bo.getSceneHead());
        lqw.eq(StringUtils.isNotBlank(bo.getDesignUnit()), ZEngineeringIndustry::getDesignUnit, bo.getDesignUnit());
        lqw.eq(StringUtils.isNotBlank(bo.getDesignHead()), ZEngineeringIndustry::getDesignHead, bo.getDesignHead());
        lqw.eq(StringUtils.isNotBlank(bo.getDesignPhone()), ZEngineeringIndustry::getDesignPhone, bo.getDesignPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getSupervisionUnit()), ZEngineeringIndustry::getSupervisionUnit, bo.getSupervisionUnit());
        lqw.eq(StringUtils.isNotBlank(bo.getSupervisionHead()), ZEngineeringIndustry::getSupervisionHead, bo.getSupervisionHead());
        lqw.eq(StringUtils.isNotBlank(bo.getSupervisionPhone()), ZEngineeringIndustry::getSupervisionPhone, bo.getSupervisionPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getType()), ZEngineeringIndustry::getType, bo.getType());
        return lqw;
    }

    /**
     * 新增工业工程|市政工程
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(ZEngineeringIndustryBo bo) {
        ZEngineeringIndustry add = BeanUtil.toBean(bo, ZEngineeringIndustry.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
            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.getUserId()));
                pic.setCreateTime(new Date());
                list.add(pic);
            });
            if (!list.isEmpty()) {
                photoService.insertBatch(list);
            }
        }
        if (!ObjectUtils.isEmpty(bo.getzEngineeringNodeBo())) {
            bo.getzEngineeringNodeBo().setCivliId(add.getId());
            bo.getzEngineeringNodeBo().setCreateTime(new Date());
            izEngineeringNodeService.insert(bo.getzEngineeringNodeBo());
        }
        return flag;
    }

    /**
     * 修改工业工程|市政工程
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(ZEngineeringIndustryBo bo) {
        ZEngineeringIndustry update = BeanUtil.toBean(bo, ZEngineeringIndustry.class);
        validEntityBeforeSave(update);
        boolean flag = baseMapper.updateById(update) > 0;
        if (flag) {
            List<ZEngiineeringPhoto> list = new ArrayList<>();
            // 查询数据库中已存在的文件列表
            ZEngiineeringPhotoBo zEngiineeringPhotoBo = new ZEngiineeringPhotoBo();
            zEngiineeringPhotoBo.setParentId(update.getId());
            zEngiineeringPhotoBo.setCreateTime(bo.getCreateTime());
            List<String> existingPhotos = photoService.queryList(zEngiineeringPhotoBo).stream().map(ZEngiineeringPhotoVo::getPicUrl).collect(Collectors.toList());
            // 插入前端传来的新文件
            if (!ObjectUtils.isEmpty(bo.getFiles())) {
                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.getUserId()));
                        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);
                }
            }
        }
        bo.getzEngineeringNodeBo().setCivliId(bo.getId());
        bo.getzEngineeringNodeBo().setType(bo.getType());
        bo.getzEngineeringNodeBo().setCreateTime(bo.getCreateTime());
        ZEngineeringNodeBo zEngineeringNodeBo = new ZEngineeringNodeBo();
        zEngineeringNodeBo.setCivliId(update.getId());
        zEngineeringNodeBo.setType(bo.getType());
        zEngineeringNodeBo.setCreateTime(baseMapper.selectVoById(bo.getId()).getCreateTime());
        ZEngineeringNodeBo query = izEngineeringNodeService.query(zEngineeringNodeBo);
        if (!ObjectUtils.isEmpty(query)) {
            bo.getzEngineeringNodeBo().setId(query.getId());
        }
        bo.getzEngineeringNodeBo().setCreateTime(zEngineeringNodeBo.getCreateTime());
        izEngineeringNodeService.insert(bo.getzEngineeringNodeBo());
        return flag;
    }

    /**
     * 修改工业工程|市政工程
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateNodeByBo(ZEngineeringIndustryBo bo) {
        ZEngineeringIndustry update = BeanUtil.toBean(bo, ZEngineeringIndustry.class);
        boolean flag = baseMapper.updateById(update) > 0;
        if (flag) {
            if (!ObjectUtils.isEmpty(bo.getFiles())) {
                List<ZEngiineeringPhoto> list = new ArrayList<>();
                // 查询数据库中已存在的文件列表
                ZEngiineeringPhotoBo zEngiineeringPhotoBo = new ZEngiineeringPhotoBo();
                zEngiineeringPhotoBo.setParentId(update.getId());
                List<String> existingPhotos = photoService.queryList(zEngiineeringPhotoBo).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.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);
                }
            }
        }
        if (!ObjectUtils.isEmpty(bo.getzEngineeringNodeBo())){
            List<ZEngineeringInfoBo> engineeringInfoBoList1 = bo.getzEngineeringNodeBo().getzEngineeringInfoBoList();
            if (engineeringInfoBoList1 != null && !engineeringInfoBoList1.isEmpty()) {
                nodeService.updateMuch(bo.getzEngineeringNodeBo());
            }
        }
        //        bo.getzEngineeringNodeBoList().stream().forEach(item->{
        //            item.setCivliId(bo.getId());
        //            item.setCreateTime(bo.getCreateTime());
        //            item.setType(bo.getType());
        //            izEngineeringNodeService.updateMuch(item);
        //        });
        return flag;
    }


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

    /**
     * 批量删除工业工程|市政工程
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {

        ids.forEach(item -> {
            // 查询数据库中已存在的文件列表
            ZEngiineeringPhotoBo zEngiineeringPhotoBo = new ZEngiineeringPhotoBo();
            zEngiineeringPhotoBo.setParentId(item);
            // 将查询出的url放入existingPhotos
            List<String> existingPhotos = photoService.queryList(zEngiineeringPhotoBo).stream().map(ZEngiineeringPhotoVo::getPicUrl).collect(Collectors.toList());
            // 若存在 则进行删除
            if (!existingPhotos.isEmpty()) {
                existingPhotos.forEach(i -> {
                    photoService.deleteWithValidByurls(i);
                });
            }
            // 初始化工程节点对象
            ZEngineeringIndustryVo vo = baseMapper.selectVoById(item);
            ZEngineeringNodeBo zEngineeringNodeBo = new ZEngineeringNodeBo();
            zEngineeringNodeBo.setCreateTime(vo.getCreateTime());
            zEngineeringNodeBo.setCivliId(vo.getId());
            //  查询数据库中已存在的工程节点
            List<ZEngineeringNodeBo> zEngineeringNodeBos = nodeService.queryListDetails(zEngineeringNodeBo);
            // 若存在 则进行删除
            if (!zEngineeringNodeBos.isEmpty()) {
                zEngineeringNodeBos.forEach(ite -> nodeService.delete(ite));
            }
        });
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public ZEngineeringIndustryVo query(String id) {
        ZEngineeringIndustryVo zEngineeringIndustryVo = baseMapper.selectVoById(id);
        ZEngineeringNodeBo zEngineeringNodeBo = new ZEngineeringNodeBo();
        zEngineeringNodeBo.setCreateTime(zEngineeringIndustryVo.getCreateTime());
        zEngineeringNodeBo.setCivliId(zEngineeringIndustryVo.getId());
        zEngineeringIndustryVo.setZEngineeringNodeBo(izEngineeringNodeService.query(zEngineeringNodeBo));
        return zEngineeringIndustryVo;
    }

    @Override
    public List<ZEngineeringIndustryTypeVo> queryNameByType(ZEngineeringIndustryBo bo) {
        LambdaQueryWrapper<ZEngineeringIndustry> zEngineeringIndustryBoLambdaQueryWrapper = buildListByType(bo);
        zEngineeringIndustryBoLambdaQueryWrapper.orderByDesc(ZEngineeringIndustry::getCreateTime);
        List<ZEngineeringIndustry> zEngineeringIndustryVos = baseMapper.selectList(zEngineeringIndustryBoLambdaQueryWrapper);
        List<ZEngineeringIndustryTypeVo> zEngineeringIndustryTypeVos = zEngineeringIndustryVos.stream().map(ZEngineeringIndustryTypeVo::new).collect(Collectors.toList());
        return zEngineeringIndustryTypeVos;
    }

    private LambdaQueryWrapper<ZEngineeringIndustry> buildListByType(ZEngineeringIndustryBo bo) {

        LambdaQueryWrapper<ZEngineeringIndustry> queryWrapper = new LambdaQueryWrapper<ZEngineeringIndustry>();
        queryWrapper.orderByDesc(ZEngineeringIndustry::getCreateTime);
        queryWrapper.eq(StringUtils.isNotBlank(bo.getEnginType()), ZEngineeringIndustry::getEnginType, bo.getEnginType());
        queryWrapper.eq(StringUtils.isNotBlank(bo.getType()), ZEngineeringIndustry::getType, bo.getType());
        if (!"null".equals(bo.getEnginClassification())) {
            queryWrapper.eq(StringUtils.isNotBlank(bo.getEnginClassification()), ZEngineeringIndustry::getEnginClassification, bo.getEnginClassification());
        }

        return queryWrapper;
    }


}
