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.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.redis.RedisUtils;
import com.ruoyi.framework.handler.MonthTableNameHandler;
import com.ruoyi.zdsz.domain.ZEngiineeringPhoto;
import com.ruoyi.zdsz.domain.ZEngineeringGY;
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.ZEngineeringGYVo;
import com.ruoyi.zdsz.domain.vo.ZEngineeringIndustryTypeVo;
import com.ruoyi.zdsz.domain.vo.ZEngineeringIndustryVo;
import com.ruoyi.zdsz.mapper.ZEngineeringCivilMapper;
import com.ruoyi.zdsz.mapper.ZEngineeringGYMapper;
import com.ruoyi.zdsz.mapper.ZEngineeringIndustryMapper;
import com.ruoyi.zdsz.service.IZEngiineeringPhotoService;
import com.ruoyi.zdsz.service.IZEngineeringGYService;
import com.ruoyi.zdsz.service.IZEngineeringIndustryService;
import com.ruoyi.zdsz.service.IZEngineeringNodeService;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 工业工程Service业务层处理
 *
 * @author ruoyi
 * @date 2024-01-02
 */
@RequiredArgsConstructor
@Service
public class ZEngineeringGYServiceImpl implements IZEngineeringGYService {

    @Resource
    private final ZEngineeringGYMapper baseMapper;

    @Resource
    private IZEngineeringNodeService izEngineeringNodeService;

    @Resource
    private IZEngineeringNodeService nodeService;

    @Resource
    private IZEngiineeringPhotoService photoService;


    /**
     * 查询工业工程
     */
    @Override
    public ZEngineeringGYVo queryById(String id) {
        ZEngineeringGYVo 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<ZEngineeringGYVo> queryPageList(ZEngineeringIndustryGYBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ZEngineeringGY> lqw = buildQueryWrapper(bo);
        Page<ZEngineeringGYVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        Map<String, Object> ReviewList;
        ReviewList = nodeService.ReViewGYList(result.getRecords());
        result.getRecords().forEach(item -> {
            item.setNodeReViewStateList(ReviewList.get(item.getId()));
        });
        return TableDataInfo.build(result);
    }

    /**
     * 查询工业工程列表
     */
    @Override
    public List<ZEngineeringGYVo> queryList(ZEngineeringIndustryGYBo bo) {
        LambdaQueryWrapper<ZEngineeringGY> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

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

    /**
     * 新增工业工程
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(ZEngineeringIndustryGYBo bo) {
        ZEngineeringGY add = BeanUtil.toBean(bo, ZEngineeringGY.class);
        validEntityBeforeSave(add);
        if (StringUtils.isEmpty(bo.getId())){
            LambdaQueryWrapper<ZEngineeringGY> lqw = buildQueryWrapper(bo);
            lqw.eq(ZEngineeringGY::getEnginName,bo.getEnginName()).eq(ZEngineeringGY::getEnginClassification,bo.getEnginClassification());
            Long selected = baseMapper.selectCount(lqw);
            if (selected>0){
                throw new IllegalArgumentException("同一工程类型,不能建相同工程名称数据!");
            }
            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;
        }
        else if (StringUtils.isNotBlank(bo.getId())){
            ZEngineeringGYVo voById = baseMapper.selectVoById(bo.getId());
            List<ZEngineeringNodeBo> zEngineeringNodeBoList = bo.getzEngineeringNodeBoList();
            ZEngineeringNodeBo entity = bo.getzEngineeringNodeBo();
            //pc
            if (!ObjectUtils.isEmpty(zEngineeringNodeBoList)) {
                for (ZEngineeringNodeBo zEngineeringNodeBo : zEngineeringNodeBoList) {
                    zEngineeringNodeBo.setCivliId(voById.getId());
                    zEngineeringNodeBo.setCreateTime(voById.getCreateTime());
                    ZEngineeringNodeBo query = izEngineeringNodeService.query(zEngineeringNodeBo);
                    if (!ObjectUtils.isEmpty(query)) {
                        zEngineeringNodeBo.setId(query.getId());
                    }
                    izEngineeringNodeService.insert(zEngineeringNodeBo);
                }
            }
            //uniapp
            if (!ObjectUtils.isEmpty(entity)) {
                entity.setCivliId(voById.getId());
                entity.setCreateTime(voById.getCreateTime());
                ZEngineeringNodeBo query = izEngineeringNodeService.query(entity);
                if (!ObjectUtils.isEmpty(query)) {
                    entity.setId(query.getId());
                }
                izEngineeringNodeService.insert(entity);
            }
            return true;
        }
        return false;
    }

    /**
     * 修改工业工程
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(ZEngineeringIndustryGYBo bo) {
        ZEngineeringGY update = BeanUtil.toBean(bo, ZEngineeringGY.class);
        validEntityBeforeSave(update);
        //工程表
        boolean flag = baseMapper.updateById(update) > 0;
        ZEngineeringGYVo voById = baseMapper.selectVoById(bo.getId());
        bo.setCreateTime(voById.getCreateTime());
        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);
                }
            }
        }
        //节点表与info表
        if (!ObjectUtils.isEmpty(bo.getzEngineeringNodeBo())) {
            bo.getzEngineeringNodeBo().setCreateTime(voById.getCreateTime());
            izEngineeringNodeService.update(bo.getzEngineeringNodeBo());
        }
        return flag;
    }


    /**
     * 修改工业工程
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateNodeByBo(ZEngineeringIndustryGYBo bo) {
        ZEngineeringGY update = BeanUtil.toBean(bo, ZEngineeringGY.class);
        boolean flag = baseMapper.updateById(update) > 0;
        ZEngineeringGYVo voById = baseMapper.selectVoById(bo.getId());
        bo.setCreateTime(voById.getCreateTime());
        if (flag) {
            if (!ObjectUtils.isEmpty(bo.getFiles())) {
                List<ZEngiineeringPhoto> list = new ArrayList<>();
                // 查询数据库中已存在的文件列表
                ZEngiineeringPhotoBo zEngiineeringPhotoBo = new ZEngiineeringPhotoBo();
                zEngiineeringPhotoBo.setCreateTime(bo.getCreateTime());
                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);
                }
            }
        }
        return flag;
    }


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

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

        ids.forEach(item -> {
            ZEngineeringGYVo 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);
                });
            }
            // 初始化工程节点对象

            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 ZEngineeringGYVo query(String id, String type) {
        ZEngineeringGYVo zEngineeringIndustryVo = baseMapper.selectVoById(id);
        ZEngineeringNodeBo zEngineeringNodeBo = new ZEngineeringNodeBo();
        zEngineeringNodeBo.setCreateTime(zEngineeringIndustryVo.getCreateTime());
        zEngineeringNodeBo.setCivliId(zEngineeringIndustryVo.getId());
        zEngineeringNodeBo.setType(type);
        zEngineeringIndustryVo.setZEngineeringNodeBo(izEngineeringNodeService.query(zEngineeringNodeBo));
        return zEngineeringIndustryVo;
    }

    @Override
    public ZEngineeringGYVo query(String id) {
        ZEngineeringGYVo 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<?> queryByType(ZEngineeringIndustryGYBo bo) {
        LambdaQueryWrapper<ZEngineeringGY> zEngineeringIndustryBoLambdaQueryWrapper = buildListByType(bo);
        List<ZEngineeringGY> zEngineeringIndustryVos = baseMapper.selectList(zEngineeringIndustryBoLambdaQueryWrapper);
        List<Map<String, Object>> result = zEngineeringIndustryVos.stream()
            .map(vo -> {
                Map<String, Object> map = new HashMap<>();
                map.put("id", vo.getId());
                map.put("name", vo.getEnginName());
                return map;
            })
            .collect(Collectors.toList());
        return result;
    }

    private LambdaQueryWrapper<ZEngineeringGY> buildListByType(ZEngineeringIndustryGYBo bo) {
        LambdaQueryWrapper<ZEngineeringGY> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(ZEngineeringGY::getCreateTime);
        queryWrapper.eq(StringUtils.isNotBlank(bo.getEnginType()), ZEngineeringGY::getEnginType, bo.getEnginType());
        queryWrapper.eq(StringUtils.isNotBlank(bo.getEnginClassification()), ZEngineeringGY::getEnginClassification, bo.getEnginClassification());
        return queryWrapper;
    }


}
