package com.zcxk.charge.web.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zcxk.charge.core.dao.WaterPropertyMapper;
import com.zcxk.charge.core.entity.WaterPropertyEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用水性质服务接口
 *
 * @author yjy
 * @since 2021-5-31
 */
@Service
public class WaterPropertyService extends ServiceImpl<WaterPropertyMapper, WaterPropertyEntity> {

    /**
     * 增加数据
     *
     * @param waterPropertyEntity
     * @return
     * */
    public boolean insert(WaterPropertyEntity waterPropertyEntity) {
        return this.save(waterPropertyEntity);
    }
    /**
     * 删除数据
     *
     * @param id
     * @return
     * */
    public boolean delete(Integer id) {
        return this.removeById(id);
    }
    /**
     * 修改数据
     *
     * @param waterPropertyEntity
     * @return
     * */
    public boolean update(WaterPropertyEntity waterPropertyEntity) {
        return this.updateById(waterPropertyEntity);
    }
    /**
     * 查询数据
     *
     * @param companyOrgId
     * @return
     * */
    public List<WaterPropertyEntity> select(Integer companyOrgId) {
        return this.list(new QueryWrapper<WaterPropertyEntity>().eq("COMPANY_ORG_ID", companyOrgId));
    }
    /**
     * 保存数据
     *
     * @param waterPropertyList
     * @return
     * */
    public boolean save(List<WaterPropertyEntity> waterPropertyList) {
        boolean flag=true;
        try {
            if(waterPropertyList.size()>0){
                //删除多余的数据
                List<WaterPropertyEntity> oldList=this.list(new QueryWrapper<WaterPropertyEntity>()
                        .eq("COMPANY_ORG_ID", waterPropertyList.get(0).getCompanyOrgId()));
                List<Integer> newIdList=waterPropertyList.stream().map(WaterPropertyEntity::getId).collect(Collectors.toList());
                List<Integer> removeIds=new ArrayList<>();
                //原来数据中id 没有 现在的id的 为要删除的数据
                for(WaterPropertyEntity entity : oldList){
                    if(!newIdList.contains(entity.getId())){
                        removeIds.add(entity.getId());
                    }
                }
                if(removeIds.size()>0){
                    flag=this.removeByIds(removeIds);
                }
                //新增和修改数据
                flag=this.saveOrUpdateBatch(waterPropertyList);
            }
        }catch (Exception e){
            flag=false;
        }
        return flag;
    }
}
