package com.ruoyi.zdsz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.annotation.DynamicName;
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.zdsz.domain.bo.ZEngineeringInfoBo;
import com.ruoyi.zdsz.service.IZEnginMaterialQualityService;
import com.ruoyi.zdsz.service.IZEnginSpecificationsService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import com.ruoyi.zdsz.domain.bo.ZEngineeringMaterialBo;
import com.ruoyi.zdsz.domain.vo.ZEngineeringMaterialVo;
import com.ruoyi.zdsz.domain.ZEngineeringMaterial;
import com.ruoyi.zdsz.mapper.ZEngineeringMaterialMapper;
import com.ruoyi.zdsz.service.IZEngineeringMaterialService;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 工程用料Service业务层处理
 *
 * @author ruoyi
 * @date 2023-12-27
 */
@RequiredArgsConstructor
@Service
public class ZEngineeringMaterialServiceImpl implements IZEngineeringMaterialService {

    private final ZEngineeringMaterialMapper baseMapper;

    /**
     * 查询工程用料
     */
    @Override
    public ZEngineeringMaterialVo queryById(String id) {
        return baseMapper.selectVoById(id);
    }

    @Autowired
    private IZEnginMaterialQualityService izEnginMaterialQualityService;
    @Autowired
    private IZEnginSpecificationsService izEnginSpecificationsService;

    @Override
    @DynamicName(spel = "#bo.createTime")
    //    @Async("threadPoolTaskExecutor")
    public List<ZEngineeringMaterialBo> query(ZEngineeringInfoBo bo) {
        LambdaQueryWrapper<ZEngineeringMaterial> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getId()), ZEngineeringMaterial::getDetailsId, bo.getId()).orderByAsc(ZEngineeringMaterial::getUpdateTime);
        List<ZEngineeringMaterial> zEngineeringMaterialVo = baseMapper.selectList(lqw);
        List<ZEngineeringMaterialBo> zEngineeringMaterialBoList = new ArrayList<>();
        zEngineeringMaterialVo.stream().forEach(item -> {
            ZEngineeringMaterialBo zEngineeringMaterialBo = BeanUtil.toBean(item, ZEngineeringMaterialBo.class);
            if (StringUtils.isNotEmpty(zEngineeringMaterialBo.getMaterialQuality()))
                zEngineeringMaterialBo.setMaterialQualityName(
                    izEnginMaterialQualityService.queryById(zEngineeringMaterialBo.getMaterialQuality())!=null
                        ?
                        izEnginMaterialQualityService.queryById(zEngineeringMaterialBo.getMaterialQuality()).getName()
                        :
                        zEngineeringMaterialBo.getMaterialQuality());
            if (StringUtils.isNotEmpty(zEngineeringMaterialBo.getSpecifications()))
                zEngineeringMaterialBo.setSpecificationsName(
                    izEnginSpecificationsService.queryById(zEngineeringMaterialBo.getSpecifications())!=null
                        ?
                        izEnginSpecificationsService.queryById(zEngineeringMaterialBo.getSpecifications()).getName()
                        :
                        zEngineeringMaterialBo.getSpecifications()
                );
            zEngineeringMaterialBoList.add(zEngineeringMaterialBo);
        });

        return zEngineeringMaterialBoList;
    }

    /**
     * 查询工程用料列表
     */
    @Override
    public TableDataInfo<ZEngineeringMaterialVo> queryPageList(ZEngineeringMaterialBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ZEngineeringMaterial> lqw = buildQueryWrapper(bo);
        Page<ZEngineeringMaterialVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询工程用料列表
     */
    @Override
    public List<ZEngineeringMaterialVo> queryList(ZEngineeringMaterialBo bo) {
        LambdaQueryWrapper<ZEngineeringMaterial> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ZEngineeringMaterial> buildQueryWrapper(ZEngineeringMaterialBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ZEngineeringMaterial> lqw = Wrappers.lambdaQuery();
        lqw.orderByDesc(ZEngineeringMaterial::getCreateTime);
        lqw.eq(StringUtils.isNotBlank(bo.getDetailsId()), ZEngineeringMaterial::getDetailsId, bo.getDetailsId());
        lqw.eq(StringUtils.isNotBlank(bo.getCorrosionLevel()), ZEngineeringMaterial::getCorrosionLevel, bo.getCorrosionLevel());
        lqw.eq(StringUtils.isNotBlank(bo.getBrand()), ZEngineeringMaterial::getBrand, bo.getBrand());
        lqw.eq(StringUtils.isNotBlank(bo.getMaterialQuality()), ZEngineeringMaterial::getMaterialQuality, bo.getMaterialQuality());
        lqw.eq(StringUtils.isNotBlank(bo.getSpecifications()), ZEngineeringMaterial::getSpecifications, bo.getSpecifications());
        lqw.eq(bo.getNumber() != null, ZEngineeringMaterial::getNumber, bo.getNumber());
        return lqw;
    }

    /**
     * 新增工程用料
     */
    @Override
    public Boolean insertByBo(ZEngineeringMaterialBo bo) {
        ZEngineeringMaterial add = BeanUtil.toBean(bo, ZEngineeringMaterial.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    @Override
    @DynamicName(spel = "#bo.createTime")
    @Transactional(rollbackFor = Exception.class)
    //@Async("threadPoolTaskExecutor")
    public ZEngineeringMaterial insert(ZEngineeringMaterialBo bo) {
        ZEngineeringMaterial add = new ZEngineeringMaterial();
        BeanUtils.copyProperties(bo, add);
        validEntityBeforeSave(add);
        add.setUpdateTime(new Date());
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return add;
    }

    /**
     * 修改工程用料
     */
    @Override
    public Boolean updateByBo(ZEngineeringMaterialBo bo) {
        ZEngineeringMaterial update = BeanUtil.toBean(bo, ZEngineeringMaterial.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    @Override
    @DynamicName(spel = "#bo.createTime")
    @Transactional(rollbackFor = Exception.class)
    public Boolean update(ZEngineeringMaterialBo bo) {
        ZEngineeringMaterial update = BeanUtil.toBean(bo, ZEngineeringMaterial.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    @Override
    @DynamicName(spel = "#Infobo.createTime")
    @Transactional(rollbackFor = Exception.class)
    @Async("threadPoolTaskExecutor")
    public Boolean updateList(ZEngineeringInfoBo Infobo) {
        List<ZEngineeringMaterialBo> bo = Infobo.getzEngineeringMaterialBo();
        LambdaQueryWrapper<ZEngineeringMaterial> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(Infobo.getId()), ZEngineeringMaterial::getDetailsId, Infobo.getId());
        List boList = new ArrayList();
        List selectList = new ArrayList();
        List<ZEngineeringMaterial> zEngineeringMaterialVoList = baseMapper.selectList(lqw);
        zEngineeringMaterialVoList.stream().forEach(item -> {
            selectList.add(item.getId());
        });
        bo.stream().forEach(item -> {
            boList.add(item.getId());
            ZEngineeringMaterial update = BeanUtil.toBean(item, ZEngineeringMaterial.class);
            validEntityBeforeSave(update);
            boolean flag = baseMapper.updateById(update) > 0;
        });
        ZEngineeringMaterial update = BeanUtil.toBean(bo, ZEngineeringMaterial.class);
        validEntityBeforeSave(update);
        boolean flag = baseMapper.updateById(update) > 0;
        List inlist = (List) boList.stream().filter(i -> !selectList.contains(i)).collect(Collectors.toList());
        List dllist = (List) selectList.stream().filter(i -> !boList.contains(i)).collect(Collectors.toList());
        if (dllist.size() != 0) {
            baseMapper.deleteBatchIds(dllist);
        }
        if (inlist.size() != 0) {
            List<ZEngineeringMaterial> zEngineeringMaterialList = new ArrayList<>();
            bo.stream().forEach(item -> {
                inlist.stream().forEach(i -> {
                    if (item.getId() == i) {
                        ZEngineeringMaterial update2 = BeanUtil.toBean(item, ZEngineeringMaterial.class);
                        update2.setDetailsId(Infobo.getId());
                        update2.setUpdateTime(new Date());
                        zEngineeringMaterialList.add(update2);
                    }
                });
            });

            baseMapper.insertBatch(zEngineeringMaterialList);
        }
        return flag;
    }

    @Override
    @DynamicName(spel = "#bo.createTime")
    @Transactional(rollbackFor = Exception.class)
    @Async("threadPoolTaskExecutor")
    public Boolean delete(ZEngineeringInfoBo bo) {
        LambdaQueryWrapper<ZEngineeringMaterial> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getId()), ZEngineeringMaterial::getDetailsId, bo.getId());
        List<ZEngineeringMaterial> zEngineeringMaterial = baseMapper.selectList(lqw);
        zEngineeringMaterial.stream().forEach(item -> {
            baseMapper.deleteById(item.getId());
        });
        return null;
    }

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

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