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.annotation.DynamicName;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.obs.ObsService;
import com.ruoyi.zdsz.domain.ZEngiineeringPhoto;
import com.ruoyi.zdsz.domain.bo.ZEngiineeringPhotoBo;
import com.ruoyi.zdsz.domain.bo.ZEngineeringInfoBo;
import com.ruoyi.zdsz.domain.vo.ZEngiineeringPhotoVo;
import com.ruoyi.zdsz.mapper.ZEngiineeringPhotoMapper;
import com.ruoyi.zdsz.service.IZEngiineeringPhotoService;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
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 ZEngiineeringPhotoServiceImpl implements IZEngiineeringPhotoService {

    private final ZEngiineeringPhotoMapper baseMapper;
    @Resource
   private ObsService obsService;

    /**
     * 查询照片
     */
    @Override
    public ZEngiineeringPhotoVo queryById(String id){
        return baseMapper.selectVoById(id);
    }

    @Override
    @DynamicName(spel = "#bo.createTime")
//    @Async("threadPoolTaskExecutor")
    public List<String> queryList(ZEngineeringInfoBo bo) {
        List<String> list =new ArrayList<>();
        LambdaQueryWrapper<ZEngiineeringPhoto> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getId()), ZEngiineeringPhoto::getParentId, bo.getId()).orderByDesc(ZEngiineeringPhoto::getCreateTime);
        List<ZEngiineeringPhoto> zEngiineeringPhotoList= baseMapper.selectList(lqw);
        zEngiineeringPhotoList.stream().forEach( item->{
            list.add(item.getPicUrl());
        });
        return list;
    }

    /**
     * 查询照片列表
     */
    @Override
    public TableDataInfo<ZEngiineeringPhotoVo> queryPageList(ZEngiineeringPhotoBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ZEngiineeringPhoto> lqw = buildQueryWrapper(bo);
        Page<ZEngiineeringPhotoVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询照片列表
     */
    @Override
    public List<ZEngiineeringPhotoVo> queryList(ZEngiineeringPhotoBo bo) {
        LambdaQueryWrapper<ZEngiineeringPhoto> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ZEngiineeringPhoto> buildQueryWrapper(ZEngiineeringPhotoBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ZEngiineeringPhoto> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getParentId()), ZEngiineeringPhoto::getParentId, bo.getParentId());
        lqw.eq(StringUtils.isNotBlank(bo.getPicUrl()), ZEngiineeringPhoto::getPicUrl, bo.getPicUrl());
        return lqw;
    }

    /**
     * 新增照片
     */
    @Override
    public Boolean insertByBo(ZEngiineeringPhotoBo bo) {
        ZEngiineeringPhoto add = BeanUtil.toBean(bo, ZEngiineeringPhoto.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 批量插入
     * @param bo
     * @return
     */
    @Override
    @Transactional(rollbackFor=Exception.class)
    @DynamicName(spel = "#bo[0].createTime")
//    @Async("threadPoolTaskExecutor")
    public Boolean insertBatch(List<ZEngiineeringPhoto> bo) {
        boolean flag = baseMapper.insertBatch(bo);
        return flag;
    }

    /**
     * 修改照片
     */
    @Override
    public Boolean updateByBo(ZEngiineeringPhotoBo bo) {
        ZEngiineeringPhoto update = BeanUtil.toBean(bo, ZEngiineeringPhoto.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    @Override
    @DynamicName(spel = "#bo[0].createTime")
    @Transactional(rollbackFor = Exception.class)
//    @Async("threadPoolTaskExecutor")
    public Boolean updateBatch(List<ZEngiineeringPhoto> bo) {
        ZEngiineeringPhoto zEngiineeringPhoto = bo.get(0);
        LambdaQueryWrapper<ZEngiineeringPhoto> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(zEngiineeringPhoto.getParentId()), ZEngiineeringPhoto::getParentId, zEngiineeringPhoto.getParentId());
        List<ZEngiineeringPhoto> zEngiineeringPhotoList=  baseMapper.selectList(lqw);
        List<String> list=new ArrayList<>();
        zEngiineeringPhotoList.stream().forEach(item->{
            list.add(item.getPicUrl());
        });
        List<String> bolist=new ArrayList<>();
        bo.stream().forEach(item->{
            bolist.add(item.getPicUrl());
        });
        List dlList= list.stream().filter(i->!bolist.contains(i)).collect(Collectors.toList());
        List<String> inList= bolist.stream().filter(i->!list.contains(i)).collect(Collectors.toList());
        obsService.deleteFiles(dlList);
        List dlIdList=new ArrayList();
        dlList.stream().forEach(item->{
            zEngiineeringPhotoList.stream().forEach(Photoitem->{
                if (Photoitem.getPicUrl()==item)
                {
                    dlIdList.add(Photoitem);
                }
            });

        });
        if (dlIdList.size()!=0)
        {
            baseMapper.deleteBatchIds(dlIdList);

        }else if (inList.size()!=0)
        {
            List <ZEngiineeringPhoto> photoList=new ArrayList();
            inList.stream().forEach(item->{
                    ZEngiineeringPhoto zEngiineeringPhoto1=new ZEngiineeringPhoto();
                    zEngiineeringPhoto1.setParentId(zEngiineeringPhoto.getParentId());
                     zEngiineeringPhoto1.setPicUrl(item);
                zEngiineeringPhoto1.setCreateTime(zEngiineeringPhoto.getCreateTime());
                    photoList.add(zEngiineeringPhoto1);
            });
            insertBatch(photoList);
        }
        return null;


    }

    @Override
    @DynamicName(spel = "#bo.createTime")
    @Transactional(rollbackFor = Exception.class)
//    @Async("threadPoolTaskExecutor")
    public Boolean delete(ZEngineeringInfoBo bo) {
        LambdaQueryWrapper<ZEngiineeringPhoto> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getId()), ZEngiineeringPhoto::getParentId, bo.getId());
        List<ZEngiineeringPhoto> zEngiineeringPhoto= baseMapper.selectList(lqw);
        List IdList=new ArrayList();
        List UrlList=new ArrayList();
        zEngiineeringPhoto.stream().forEach(item->{
            IdList.add(item.getId());
            UrlList.add(item.getPicUrl());

        });
        int flag=0;
        if(IdList.size()>0)
        {
            obsService.deleteFiles(UrlList);
            flag=  baseMapper.deleteBatchIds(IdList);
        }
       ;
        return flag>0;
    }

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

    /**
     * 批量删除照片
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 删除照片
     */
    @Override
    public Boolean deleteWithValidByurls(String url) {
        try {
            obsService.deleteFiles(Collections.singletonList(url));
        } catch (Exception e) {

        }
        return baseMapper.deleteByUrls(url) > 0;
    }

}
