package com.ruoyi.zdsz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.PageUtils;
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.framework.obs.ObsService;
import com.ruoyi.zdsz.domain.ZEngiineeringPhoto;
import com.ruoyi.zdsz.domain.bo.*;
import com.ruoyi.zdsz.domain.vo.*;
import com.ruoyi.zdsz.mapper.ZEngiineeringPhotoMapper;
import com.ruoyi.zdsz.service.IZEngiineeringPhotoService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.zdsz.domain.ZComprehensive;
import com.ruoyi.zdsz.mapper.ZComprehensiveMapper;
import com.ruoyi.zdsz.service.IZComprehensiveService;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 开栓|安检|维修Service业务层处理
 *
 * @author ruoyi
 * @date 2023-12-27
 */
@RequiredArgsConstructor
@Service
public class ZComprehensiveServiceImpl implements IZComprehensiveService {

    private final ZComprehensiveMapper baseMapper;

    @Resource
    private ZEngiineeringPhotoMapper photoMapper;
    @Resource
    private ObsService obsService;
    @Resource
    private IZEngiineeringPhotoService photoService;

    /**
     * 查询开栓|安检|维修
     */
    @Override
    public ZComprehensiveVo queryById(String id){
        ZComprehensiveVo vo = baseMapper.selectVoById(id);
        ZEngiineeringPhotoBo bo = new ZEngiineeringPhotoBo();
        bo.setParentId(id);
        bo.setCreateTime(vo.getCreateTime());
        vo.setMapList(photoService.queryList(bo));
        return vo;
    }

    /**
     * 查询开栓|安检|维修列表
     */
    @Override
    public TableDataInfo<ZComprehensiveVo> queryPageList(ZComprehensiveBo bo, PageQuery pageQuery) {
//        Page<ZComprehensiveVo> page = new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize());
//        Page<ZComprehensiveVo> list = baseMapper.getPageList(bo,page);
//        return PageUtils.buildDataInfo(list);
        Page<ZComprehensiveVo> page = new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize());
        Integer pageNum = pageQuery.getPageNum();
        if (!ObjectUtils.isEmpty(pageNum)&&pageNum>=1){
            pageNum-=1;
        }
        Page<ZComprehensiveVo> result = baseMapper.queryPageList(bo,page,pageNum, pageQuery.getPageSize());
        page.setTotal((result.getRecords() != null&&!result.getRecords().isEmpty()) ? result.getRecords().get(0).getTotal():0);
        return TableDataInfo.build(result);
    }

    /**
     * 查询开栓|安检|维修列表
     */
    @Override
    public List<ZComprehensiveVo> queryList(ZComprehensiveBo bo) {
//        LambdaQueryWrapper<ZComprehensive> lqw = buildQueryWrapper(bo);
//        return baseMapper.selectVoList(lqw);
        return baseMapper.queryPageListAll(bo);
    }

    private LambdaQueryWrapper<ZComprehensive> buildQueryWrapper(ZComprehensiveBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ZComprehensive> lqw = Wrappers.lambdaQuery();
        lqw.orderByDesc(ZComprehensive::getCreateTime);
        lqw.eq(StringUtils.isNotBlank(bo.getAreaId()), ZComprehensive::getAreaId, bo.getAreaId());
        lqw.eq(StringUtils.isNotBlank(bo.getBuildingId()), ZComprehensive::getBuildingId, bo.getBuildingId());
        lqw.eq(StringUtils.isNotBlank(bo.getUnitId()), ZComprehensive::getUnitId, bo.getUnitId());
        lqw.eq(StringUtils.isNotBlank(bo.getHouseId()), ZComprehensive::getHouseId, bo.getHouseId());
        lqw.eq(StringUtils.isNotBlank(bo.getType()), ZComprehensive::getType, bo.getType());
        lqw.eq(StringUtils.isNotBlank(bo.getIsQualified()), ZComprehensive::getIsQualified, bo.getIsQualified());
        return lqw;
    }

    /**
     * 新增开栓|安检|维修
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(ZComprehensiveBo bo) {
        ZComprehensive add = BeanUtil.toBean(bo, ZComprehensive.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
            List<ZEngiineeringPhoto> list = new ArrayList<>();
            bo.getPicIds().stream().forEach(o->{
                ZEngiineeringPhoto pic = new ZEngiineeringPhoto();
                pic.setParentId(bo.getId());
                pic.setPicUrl(o);
                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()) {
                photoMapper.insertBatch(list);
            }
        }
        return flag;
    }


    /**
     * 修改开栓|安检|维修
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(ZComprehensiveBo bo) {
        ZComprehensive update = BeanUtil.toBean(bo, ZComprehensive.class);
        validEntityBeforeSave(update);

        if (StringUtils.isNotBlank(bo.getId())) {
            List<ZEngiineeringPhoto> list = new ArrayList<>();

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

            // 插入前端传来的新图片
            for (String pic : bo.getPicIds()) {
                if (!existingPhotos.contains(pic)) {
                    ZEngiineeringPhoto newPhoto = new ZEngiineeringPhoto();
                    newPhoto.setParentId(bo.getId());
                    newPhoto.setPicUrl(pic);
                    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.getPicIds().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()) {
                photoMapper.insertBatch(list);
            }
        }

        return baseMapper.updateById(update) > 0;
    }


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

    /**
     * 批量删除开栓|安检|维修
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        ids.forEach(item -> {
            ZComprehensiveVo vo = baseMapper.selectVoById(item);
            ZEngiineeringPhotoBo bo = new ZEngiineeringPhotoBo();
            bo.setCreateTime(vo.getCreateTime());
            bo.setParentId(vo.getId());
            List<ZEngiineeringPhotoVo> queriedList = photoService.queryList(bo);
            if (!queriedList.isEmpty()) {
                obsService.deleteFiles(queriedList.stream().map(ZEngiineeringPhotoVo::getPicUrl).collect(Collectors.toList()));
                photoService.deleteWithValidByIds(queriedList.stream().map(ZEngiineeringPhotoVo::getId).collect(Collectors.toList()),true);
            }
        });
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
