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.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.zdsz.domain.ZEngiineeringPhoto;
import com.ruoyi.zdsz.domain.ZEngineeringGasOpening;
import com.ruoyi.zdsz.domain.bo.*;
import com.ruoyi.zdsz.domain.vo.ZEngiineeringPhotoVo;
import com.ruoyi.zdsz.domain.vo.ZEngineeringGasOpeningVo;
import com.ruoyi.zdsz.domain.vo.ZEngineeringIndustryTypeVo;
import com.ruoyi.zdsz.mapper.ZEngineeringGasOpeningMapper;
import com.ruoyi.zdsz.service.IZEngiineeringPhotoService;
import com.ruoyi.zdsz.service.IZEngineeringGasOpeningService;
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.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 开栓施工Service业务层处理
 *
 * @author ruoyi
 * @date 2024-01-02
 */
@RequiredArgsConstructor
@Service
public class ZEngineeringGasOpeningServiceImpl implements IZEngineeringGasOpeningService {

    @Resource
    private final ZEngineeringGasOpeningMapper baseMapper;

    @Resource
    private IZEngineeringNodeService izEngineeringNodeService;

    @Resource
    private IZEngineeringNodeService nodeService;

    @Resource
    private IZEngiineeringPhotoService photoService;

    /**
     * 查询开栓施工
     */
    @Override
    public ZEngineeringGasOpeningVo queryById(String id) {
        ZEngineeringGasOpeningVo zEngineeringGasOpeningVo = baseMapper.queryVoById(id);
        ZEngiineeringPhotoBo photoBo = new ZEngiineeringPhotoBo();
        photoBo.setCreateTime(zEngineeringGasOpeningVo.getCreateTime());
        photoBo.setParentId(zEngineeringGasOpeningVo.getId());
        List<ZEngiineeringPhotoVo> photoVoList = photoService.queryList(photoBo);
        zEngineeringGasOpeningVo.setGasCylinderPic(photoVoList.stream().collect(Collectors.groupingBy(ZEngiineeringPhotoVo::getType)).get("gasCylinderPic")==null?new ArrayList<>():photoVoList.stream().collect(Collectors.groupingBy(ZEngiineeringPhotoVo::getType)).get("gasCylinderPic").stream().map(s -> s.getPicUrl()).collect(Collectors.toList()));
        zEngineeringGasOpeningVo.setPressureTestPic(photoVoList.stream().collect(Collectors.groupingBy(ZEngiineeringPhotoVo::getType)).get("pressureTestPic")==null?new ArrayList<>():photoVoList.stream().collect(Collectors.groupingBy(ZEngiineeringPhotoVo::getType)).get("pressureTestPic").stream().map(s -> s.getPicUrl()).collect(Collectors.toList()));
        zEngineeringGasOpeningVo.setGasMeterPic(photoVoList.stream().collect(Collectors.groupingBy(ZEngiineeringPhotoVo::getType)).get("gasMeterPic")==null?new ArrayList<>():photoVoList.stream().collect(Collectors.groupingBy(ZEngiineeringPhotoVo::getType)).get("gasMeterPic").stream().map(s -> s.getPicUrl()).collect(Collectors.toList()));
        zEngineeringGasOpeningVo.setRearPipePic(photoVoList.stream().collect(Collectors.groupingBy(ZEngiineeringPhotoVo::getType)).get("rearPipePic")==null?new ArrayList<>():photoVoList.stream().collect(Collectors.groupingBy(ZEngiineeringPhotoVo::getType)).get("rearPipePic").stream().map(s -> s.getPicUrl()).collect(Collectors.toList()));
        zEngineeringGasOpeningVo.setGasChangePic(photoVoList.stream().collect(Collectors.groupingBy(ZEngiineeringPhotoVo::getType)).get("gasChangePic")==null?new ArrayList<>():photoVoList.stream().collect(Collectors.groupingBy(ZEngiineeringPhotoVo::getType)).get("gasChangePic").stream().map(s -> s.getPicUrl()).collect(Collectors.toList()));
        zEngineeringGasOpeningVo.setSoftPipePic(photoVoList.stream().collect(Collectors.groupingBy(ZEngiineeringPhotoVo::getType)).get("softPipePic")==null?new ArrayList<>():photoVoList.stream().collect(Collectors.groupingBy(ZEngiineeringPhotoVo::getType)).get("softPipePic").stream().map(s -> s.getPicUrl()).collect(Collectors.toList()));
        zEngineeringGasOpeningVo.setWindproofCirclePic(photoVoList.stream().collect(Collectors.groupingBy(ZEngiineeringPhotoVo::getType)).get("windproofCirclePic")==null?new ArrayList<>():photoVoList.stream().collect(Collectors.groupingBy(ZEngiineeringPhotoVo::getType)).get("windproofCirclePic").stream().map(s -> s.getPicUrl()).collect(Collectors.toList()));
        zEngineeringGasOpeningVo.setGasEnvironmentPic(photoVoList.stream().collect(Collectors.groupingBy(ZEngiineeringPhotoVo::getType)).get("gasEnvironmentPic")==null?new ArrayList<>():photoVoList.stream().collect(Collectors.groupingBy(ZEngiineeringPhotoVo::getType)).get("gasEnvironmentPic").stream().map(s -> s.getPicUrl()).collect(Collectors.toList()));
        zEngineeringGasOpeningVo.setReceiptFormPic(photoVoList.stream().collect(Collectors.groupingBy(ZEngiineeringPhotoVo::getType)).get("receiptFormPic")==null?new ArrayList<>():photoVoList.stream().collect(Collectors.groupingBy(ZEngiineeringPhotoVo::getType)).get("receiptFormPic").stream().map(s -> s.getPicUrl()).collect(Collectors.toList()));
        return zEngineeringGasOpeningVo;
    }

    /**
     * 查询开栓施工列表
     */
    @Override
    public TableDataInfo<ZEngineeringGasOpeningVo> queryPageList(ZEngineeringGasOpeningBo bo, PageQuery pageQuery) {
        Page<ZBuildingBo> page = new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize());
        Page<ZEngineeringGasOpeningVo> result = baseMapper.queryPageList(bo, page, (pageQuery.getPageNum() - 1) * pageQuery.getPageSize(), pageQuery.getPageSize());
        return TableDataInfo.build(result);
    }

    /**
     * 查询开栓施工列表
     */
    @Override
    public List<ZEngineeringGasOpeningVo> queryList(ZEngineeringGasOpeningBo bo) {
        LambdaQueryWrapper<ZEngineeringGasOpening> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ZEngineeringGasOpening> buildQueryWrapper(ZEngineeringGasOpeningBo bo) {
        LambdaQueryWrapper<ZEngineeringGasOpening> lqw = Wrappers.lambdaQuery();
        lqw.orderByDesc(ZEngineeringGasOpening::getCreateTime);
        lqw.eq(StringUtils.isNotBlank(bo.getDistrict()), ZEngineeringGasOpening::getDistrict, bo.getDistrict());
        lqw.eq(StringUtils.isNotBlank(bo.getAreaId()), ZEngineeringGasOpening::getAreaId, bo.getAreaId());
        lqw.eq(StringUtils.isNotBlank(bo.getBuildingId()), ZEngineeringGasOpening::getBuildingId, bo.getBuildingId());
        lqw.eq(StringUtils.isNotBlank(bo.getUnitId()), ZEngineeringGasOpening::getUnitId, bo.getUnitId());
        lqw.eq(StringUtils.isNotBlank(bo.getHouseId()), ZEngineeringGasOpening::getHouseId, bo.getHouseId());
        return lqw;
    }

    private void batchInsertPic(List<String> picList, String parentId, String type){
        List<ZEngiineeringPhoto> list = new ArrayList<>();
//        bo.getFiles().forEach(o -> {
        picList.forEach(o -> {
            ZEngiineeringPhoto pic = new ZEngiineeringPhoto();
            pic.setParentId(parentId);
            pic.setType(type);
            pic.setPicUrl(o);
//            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);
        }
    }

    /**
     * 新增开栓施工
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(ZEngineeringGasOpeningBo bo) {
        LambdaQueryWrapper<ZEngineeringGasOpening> lqw = buildQueryWrapper(bo);
        List<ZEngineeringGasOpeningVo> list = baseMapper.selectVoList(lqw);
        if(list.size() > 0){
            throw new ServiceException("当前房间已开栓，不能重复提交！");
        }
        ZEngineeringGasOpening add = BeanUtil.toBean(bo, ZEngineeringGasOpening.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);
            }*/
//            gasCylinderPic: [], // 燃气立杠图片
//            pressureTestPic: [], // 气密测试图片
//            gasMeterPic: [], // 燃气表图片
//            rearPipePic: [], // 表后管图片
//            gasChangePic: [], // 灶前阀门图片
//            softPipePic: [], // 软管图片
//            windproofCirclePic: [], // 灶具阀门图片
//            gasEnvironmentPic: [], // 用气环境图片
//            receiptFormPic: [], // 回执单图片
            batchInsertPic(bo.getGasCylinderPic(), bo.getId(), "gasCylinderPic");
            batchInsertPic(bo.getPressureTestPic(), bo.getId(), "pressureTestPic");
            batchInsertPic(bo.getGasMeterPic(), bo.getId(), "gasMeterPic");
            batchInsertPic(bo.getRearPipePic(), bo.getId(), "rearPipePic");
            batchInsertPic(bo.getGasChangePic(), bo.getId(), "gasChangePic");
            batchInsertPic(bo.getSoftPipePic(), bo.getId(), "softPipePic");
            batchInsertPic(bo.getWindproofCirclePic(), bo.getId(), "windproofCirclePic");
            batchInsertPic(bo.getGasEnvironmentPic(), bo.getId(), "gasEnvironmentPic");
            batchInsertPic(bo.getReceiptFormPic(), bo.getId(), "receiptFormPic");
        }
//        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(ZEngineeringGasOpeningBo bo) {
        ZEngineeringGasOpening update = BeanUtil.toBean(bo, ZEngineeringGasOpening.class);
        validEntityBeforeSave(update);
        boolean flag = baseMapper.updateById(update) > 0;
        ZEngineeringInfoBo photoBo = new ZEngineeringInfoBo();
        photoBo.setCreateTime(bo.getCreateTime());
        photoBo.setId(bo.getId());
        photoService.delete(photoBo);
        batchInsertPic(bo.getGasCylinderPic(), bo.getId(), "gasCylinderPic");
        batchInsertPic(bo.getPressureTestPic(), bo.getId(), "pressureTestPic");
        batchInsertPic(bo.getGasMeterPic(), bo.getId(), "gasMeterPic");
        batchInsertPic(bo.getRearPipePic(), bo.getId(), "rearPipePic");
        batchInsertPic(bo.getGasChangePic(), bo.getId(), "gasChangePic");
        batchInsertPic(bo.getSoftPipePic(), bo.getId(), "softPipePic");
        batchInsertPic(bo.getWindproofCirclePic(), bo.getId(), "windproofCirclePic");
        batchInsertPic(bo.getGasEnvironmentPic(), bo.getId(), "gasEnvironmentPic");
        batchInsertPic(bo.getReceiptFormPic(), bo.getId(), "receiptFormPic");
        return flag;
    }

        /**
         * 本故事根据管道厚度功能模块改编
         */
    private void batchUpdatePic(List<String> picList, String parentId, String type, Date createTime){
//            if (!ObjectUtils.isEmpty(bo.getzEngineeringNodeBo().getzEngineeringInfoBo().getIronPipelineThickness())) {
//        if (!ObjectUtils.isEmpty(bo.getzEngineeringNodeBo().getzEngineeringInfoBoList().get(0).getIronPipelineThickness())) {
        if (!ObjectUtils.isEmpty(picList)){
            List<ZEngiineeringPhoto> list = new ArrayList<>();
            // 查询数据库中已存在的文件列表
            ZEngiineeringPhotoBo zEngiineeringPhotoBo = new ZEngiineeringPhotoBo();
//            zEngiineeringPhotoBo.setCreateTime(bo.getzEngineeringNodeBo().getzEngineeringInfoBoList().get(0).getCreateTime());//
            zEngiineeringPhotoBo.setCreateTime(createTime);//
//                zEngiineeringPhotoBo.setParentId(update.getId());
//            zEngiineeringPhotoBo.setParentId(bo.getzEngineeringNodeBo().getzEngineeringInfoBoList().get(0).getId());
            zEngiineeringPhotoBo.setParentId(parentId);
            List<String> existingPhotos = photoService.queryList(zEngiineeringPhotoBo).stream().map(ZEngiineeringPhotoVo::getPicUrl).collect(Collectors.toList());
            // 插入前端传来的新文件
//                for (ZFileBo pic : bo.getzEngineeringNodeBo().getzEngineeringInfoBo().getIronPipelineThickness()) {
//            for (String pic : bo.getzEngineeringNodeBo().getzEngineeringInfoBo().getIronPipelineThickness()) {
            for (String pic : picList) {
                if (!existingPhotos.contains(pic)) {
                    ZEngiineeringPhoto newPhoto = new ZEngiineeringPhoto();
//                        newPhoto.setParentId(bo.getId());
//                    newPhoto.setParentId(bo.getzEngineeringNodeBo().getzEngineeringInfoBoList().get(0).getId());
                    newPhoto.setParentId(parentId);
                    newPhoto.setPicUrl(pic);
//                    newPhoto.setFileName(pic);
                    newPhoto.setType(type);
                    newPhoto.setCreateBy(String.valueOf(LoginHelper.getUsername()));
                    newPhoto.setCreateTime(createTime);
                    newPhoto.setUpdateTime(new Date());
                    list.add(newPhoto);
                }
            }
            // 删除数据库中多余的文件
//            List<String> photosToDelete = existingPhotos.stream().filter(pic -> !bo.getzEngineeringNodeBo().getzEngineeringInfoBo().getIronPipelineThickness().contains(pic)).collect(Collectors.toList());
            List<String> photosToDelete = existingPhotos.stream().filter(pic -> !picList.contains(pic)).collect(Collectors.toList());
            if (!photosToDelete.isEmpty()) {
                photosToDelete.forEach(item -> {
                    ZEngiineeringPhoto zEngiineeringPhoto = new ZEngiineeringPhoto();
//                    zEngiineeringPhoto.setType("ironPipelineThickness");
                    zEngiineeringPhoto.setType(type);
                    zEngiineeringPhoto.setPicUrl(item);
//                    zEngiineeringPhoto.setCreateTime(bo.getCreateTime());
                    zEngiineeringPhoto.setCreateTime(createTime);
                    photoService.deleteWithValid(zEngiineeringPhoto);
                });
            }
            // 批量插入新图片
            if (!list.isEmpty()) {
                photoService.insertBatch(list);
            }
        }else {
            // 查询数据库中已存在的文件列表
            ZEngiineeringPhotoBo zEngiineeringPhotoBo = new ZEngiineeringPhotoBo();
            zEngiineeringPhotoBo.setCreateTime(createTime);//
            zEngiineeringPhotoBo.setParentId(parentId);
            List<String> existingPhotos = photoService.queryList(zEngiineeringPhotoBo).stream().map(ZEngiineeringPhotoVo::getPicUrl).collect(Collectors.toList());
            // 删除数据库中多余的文件
            List<String> photosToDelete = existingPhotos.stream().filter(pic -> !picList.contains(pic)).collect(Collectors.toList());
            if (!photosToDelete.isEmpty()) {
                photosToDelete.forEach(item -> {
                    ZEngiineeringPhoto zEngiineeringPhoto = new ZEngiineeringPhoto();
                    zEngiineeringPhoto.setCreateTime(createTime);
                    zEngiineeringPhoto.setPicUrl(item);
                    zEngiineeringPhoto.setType(type);
                    photoService.deleteWithValid(zEngiineeringPhoto);
                });
            }
        }
    }

    /**
     * 修改开栓施工
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateNodeByBo(ZEngineeringGasOpeningBo bo) {
        ZEngineeringGasOpening update = BeanUtil.toBean(bo, ZEngineeringGasOpening.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(ZEngineeringGasOpening entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除开栓施工
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {

        ids.forEach(item -> {
            ZEngineeringGasOpeningVo vo = baseMapper.selectVoById(item);
            // 查询数据库中已存在的文件列表
            ZEngiineeringPhotoBo zEngiineeringPhotoBo = new ZEngiineeringPhotoBo();
            zEngiineeringPhotoBo.setParentId(item);
            zEngiineeringPhotoBo.setCreateTime(vo.getCreateTime());
            // 将查询出的url放入existingPhotos
            List<String> existingPhotos = photoService.queryList(zEngiineeringPhotoBo).stream().map(ZEngiineeringPhotoVo::getPicUrl).collect(Collectors.toList());
            // 若存在 则进行删除
            if (!existingPhotos.isEmpty()) {
                existingPhotos.forEach(i -> {
                    photoService.deleteWithValidByurls(i);
                });
            }
        });
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public ZEngineeringGasOpeningVo query(String id, String type) {
        ZEngineeringGasOpeningVo zEngineeringGasOpeningVo = baseMapper.selectVoById(id);
        ZEngineeringNodeBo zEngineeringNodeBo = new ZEngineeringNodeBo();
        zEngineeringNodeBo.setCreateTime(zEngineeringGasOpeningVo.getCreateTime());
        zEngineeringNodeBo.setCivliId(zEngineeringGasOpeningVo.getId());
        System.out.println("type===" + type);
        zEngineeringNodeBo.setType(type);
//        zEngineeringNodeBo.setType("trench_construction");
        zEngineeringGasOpeningVo.setZEngineeringNodeBo(izEngineeringNodeService.query(zEngineeringNodeBo));
        return zEngineeringGasOpeningVo;
    }

}
