package com.ruoyi.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.EsModel;
import com.ruoyi.common.utils.MapUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.domain.*;
import com.ruoyi.domain.ZfEconomy;
import com.ruoyi.mapper.ZfEconomyMapper;
import com.ruoyi.service.*;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
import static com.ruoyi.constant.MenuAuthority.*;
/**
*
* 家庭收支台账 服务实现类
*
*
* @author ojq
* @since 2023-03-12
*/
@Service
@Slf4j
public class ZfEconomyServiceImpl extends ServiceImpl implements ZfEconomyService {
@Resource
ZfEconomyService zfEconomyService;
@Resource
ZInfoUserService zInfoUserService;
@Resource
ZAuthorityService zAuthorityService;
@Resource
ZfEconomyMapper zfEconomyMapper;
@Resource
EsService esService;
@Resource
RestHighLevelClient restHighLevelClient;
@Resource
ZfEconomyShaService zfEconomyShaService;
@Resource
ZfEconomyDownlService zfEconomyDownlService;
private LambdaQueryWrapper buildCondition(ZfEconomy zfEconomy,List familyIdList) {
LambdaQueryWrapper lqw = new LambdaQueryWrapper<>();
lqw.orderByDesc(ZfEconomy::getCreateTime);
lqw.in(ZfEconomy::getFamilyId,familyIdList);
lqw.like(StringUtils.isNotEmpty(zfEconomy.getType()),ZfEconomy::getType,zfEconomy.getType());
lqw.like(StringUtils.isNotEmpty(zfEconomy.getKind()),ZfEconomy::getKind,zfEconomy.getKind());
lqw.like(StringUtils.isNotEmpty(zfEconomy.getPrice()),ZfEconomy::getPrice,zfEconomy.getPrice());
lqw.like(StringUtils.isNotEmpty(zfEconomy.getUseFor()),ZfEconomy::getUseFor,zfEconomy.getUseFor());
lqw.like(StringUtils.isNotEmpty(zfEconomy.getUsePeople()),ZfEconomy::getUsePeople,zfEconomy.getUsePeople());
lqw.like(StringUtils.isNotEmpty(zfEconomy.getBalance()),ZfEconomy::getBalance,zfEconomy.getBalance());
lqw.like(StringUtils.isNotEmpty(zfEconomy.getRemark()),ZfEconomy::getRemark,zfEconomy.getRemark());
lqw.eq(zfEconomy.getHappenTime() != null, ZfEconomy::getHappenTime, zfEconomy.getHappenTime());
lqw.between(zfEconomy.getHappenStartTime() != null && zfEconomy.getHappenEndTime() != null, ZfEconomy::getHappenTime, zfEconomy.getHappenStartTime(), zfEconomy.getHappenEndTime());
return lqw;
}
private LambdaQueryWrapper uniqueCondition(ZfEconomy zfEconomy) {
LambdaQueryWrapper lqw = new LambdaQueryWrapper<>();
lqw.eq(StringUtils.isNotEmpty(zfEconomy.getType()),ZfEconomy::getType,zfEconomy.getType());
lqw.eq(StringUtils.isNotEmpty(zfEconomy.getKind()),ZfEconomy::getKind,zfEconomy.getKind());
lqw.eq(StringUtils.isNotEmpty(zfEconomy.getPrice()),ZfEconomy::getPrice,zfEconomy.getPrice());
lqw.eq(StringUtils.isNotEmpty(zfEconomy.getUseFor()),ZfEconomy::getUseFor,zfEconomy.getUseFor());
lqw.eq(StringUtils.isNotEmpty(zfEconomy.getUsePeople()),ZfEconomy::getUsePeople,zfEconomy.getUsePeople());
lqw.eq(StringUtils.isNotEmpty(zfEconomy.getBalance()),ZfEconomy::getBalance,zfEconomy.getBalance());
lqw.eq(StringUtils.isNotEmpty(zfEconomy.getRemark()),ZfEconomy::getRemark,zfEconomy.getRemark());
lqw.eq(zfEconomy.getFamilyId()!=null,ZfEconomy::getFamilyId,zfEconomy.getFamilyId());
lqw.eq(zfEconomy.getHappenTime() != null, ZfEconomy::getHappenTime, zfEconomy.getHappenTime());
return lqw;
}
@Override
public List change(){
ZfEconomy zfEconomy = new ZfEconomy();
return list(buildCondition(zfEconomy,null));
}
// private LambdaQueryWrapper buildCondition(ZfEconomy zfEconomy, String familyIds, String secondFamilyAuthority) {
// //模糊查询的条件
// LambdaQueryWrapper lqw = buildCondition(zfEconomy);
//
// //定义一个布尔标记,标记第一家庭号是否有逗号
// boolean flag = false;
//
// StringBuilder secondFamilyIdsBuffer = new StringBuilder();
//
// //处理传入的secondFamilyAuthority 3{2007 2018 2015},4{2007 2019}
//
// if (StringUtils.isNotEmpty(secondFamilyAuthority)) {
//
// if (secondFamilyAuthority.contains(",")) {
// //逗号隔开得到如下串:3{2007 2018 2015}
// String[] authorityList = secondFamilyAuthority.split(",");
// for (String authorityAndId : authorityList) {
// setSecondFamilyAuthority(secondFamilyIdsBuffer, authorityAndId);
// }
//
// //把后面的逗号去掉
// if (secondFamilyIdsBuffer.length() > 1) {
// secondFamilyIdsBuffer.deleteCharAt(secondFamilyIdsBuffer.length() - 1);
// }
//
// }else{
// setSecondFamilyAuthority(secondFamilyIdsBuffer, secondFamilyAuthority);
// //把后面的逗号去掉
// if (secondFamilyIdsBuffer.length() > 1) {
// secondFamilyIdsBuffer.deleteCharAt(secondFamilyIdsBuffer.length() - 1);
// }
// }
// }
// //将StringBuffer转成String
// String secondFamilyIds = secondFamilyIdsBuffer.toString();
//
// //第一家庭号的条件
// if (familyIds.contains(",")) {
// flag = true;
// }
//
// //第二家庭号的条件
// if (StringUtils.isNotEmpty(secondFamilyIds)) {
// if (secondFamilyIds.contains(",")) {
// String[] secondFamilyIdList = secondFamilyIds.split(",");
// if (flag) {
// //如果第一家庭号和第二家庭号都有逗号
// String[] familyList = familyIds.split(",");
// String[] totalFamilyIdList = ArraysUtil.appendToArray(familyList, secondFamilyIdList);
// lqw.in(ZfEconomy::getFamilyId, totalFamilyIdList);
// } else {
// //如果第一家庭号没有逗号但是第二家庭号有逗号
// String[] totalFamilyIdList = ArraysUtil.appendToArray(secondFamilyIdList, familyIds);
// lqw.in(ZfEconomy::getFamilyId, totalFamilyIdList);
// }
//
// } else {
// if (flag) {
// //如果第一家庭号有逗号但第二家庭号没有逗号
// String[] familyList = familyIds.split(",");
// String[] totalFamilyIdList = ArraysUtil.appendToArray(familyList, secondFamilyIds);
// lqw.in(ZfEconomy::getFamilyId, totalFamilyIdList);
// } else {
// //如果第一家庭号和第二家庭号都没有逗号
// String[] totalFamilyIdList = ArraysUtil.appendToArray(familyIds, secondFamilyIds);
// lqw.in(ZfEconomy::getFamilyId, totalFamilyIdList);
// }
// }
// } else {
// //如果没有第二家庭号
// if (flag) {
// String[] familyList = familyIds.split(",");
// lqw.in(ZfEconomy::getFamilyId, familyList);
// } else {
// lqw.eq(ZfEconomy::getFamilyId, familyIds);
// }
//
// }
//
// lqw.orderByDesc(ZfEconomy::getCreateTime);
// return lqw;
// }
//
// private void setSecondFamilyAuthority(StringBuilder secondFamilyIdsBuffer, String authorityAndId) {
// //得到权限串
// String authorities = authorityAndId.substring(2, authorityAndId.length() - 1);
//
// if (authorities.contains(" ")) {
// //空格隔开得到菜单id,看是否有对应的权限
// String[] authorityIdList = authorities.split(" ");
// for (String s : authorityIdList) {
// if (s.equals(ECONOMY_LIST)) {
// secondFamilyIdsBuffer.append(authorityAndId.charAt(0)).append(",");
// break;
// }
// }
// } else {
// if (authorities.equals(ECONOMY_LIST)) {
// secondFamilyIdsBuffer.append(authorityAndId.charAt(0)).append(",");
// }
// }
// }
//
// private ZInfoUser getMySelf() {
// SysUser user = SecurityUtils.getLoginUser().getUser();
// Long userId = user.getUserId();
// LambdaQueryWrapper zInfoUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
// zInfoUserLambdaQueryWrapper.eq(ZInfoUser::getUserId, userId);
// return zInfoUserService.getOne(zInfoUserLambdaQueryWrapper);
// }
//
// private String listFamilyIds() {
// ZInfoUser mySelf = getMySelf();
// return mySelf.getFamilyId();
// }
//
// private String listSecondFamilyIds() {
// ZInfoUser mySelf = getMySelf();
// return mySelf.getSecondFamilyId();
// }
@Override
public List selectByCondition(ZfEconomy zfEconomy) {
// String familyIds = listFamilyIds();
// String secondFamilyIds = listSecondFamilyIds();
// LambdaQueryWrapper lambdaQueryWrapper = buildCondition(zfEconomy, familyIds, secondFamilyIds);
// List beanRecords = list(lambdaQueryWrapper);
// log.info("从数据库中查到的为:{}", beanRecords);
// return markOwnData(familyIds, beanRecords);
//要查自己家庭的
ZInfoUser myself = zInfoUserService.getMyself();
Long familyId = myself.getFamilyId();
//查看父母的数据:
Long fatherFaId = 0L;
if(myself.getFatherId()!=null)
fatherFaId = zInfoUserService.getInfoById(myself.getFatherId()).getFamilyId();
Long motherFaId = 0L;
if(myself.getMomId()!=null)
motherFaId = zInfoUserService.getInfoById(myself.getMomId()).getFamilyId();
//也要查别人授权的
List authority = zAuthorityService.getAuthority();
List idList = authority.stream().filter(auth -> auth.getAuthority().toString().equals(ECONOMY_LIST)).map(ZAuthority::getFid).collect(Collectors.toList());
//加上自己家庭的id
idList.add(familyId);
//加上父母家族id
idList.add(fatherFaId);
idList.add(motherFaId);
List fms = zInfoUserService.findByUaidToFaid(myself.getUaid()).stream().map(ZInfoUser::getFamilyId).collect(Collectors.toList());
if(!fms.isEmpty())
{
idList.addAll(fms);
}
LambdaQueryWrapper lambdaQueryWrapper = buildCondition(zfEconomy, idList);
List beanRecords = list(lambdaQueryWrapper);
log.info("从数据库中查到的为:{}", beanRecords);
return markOwnData(familyId,fatherFaId, motherFaId, beanRecords);
}
@Override
public List selectByIds(Long[] ids) {
List list = new ArrayList<>();
if(ids.length!=0)
list = listByIds(Arrays.asList(ids));
else
list = list();
return list;
}
// private List markOwnData(String familyIds, List beanRecords) {
// return beanRecords.stream().peek(record -> {
// String recordFamilyId = record.getFamilyId();
// if (familyIds.contains(",")) {
// String[] familyIdList = familyIds.split(",");
// for (String familyId : familyIdList) {
// if (familyId.equals(recordFamilyId)) {
// record.setOwnData(1);
// }
// }
// } else {
// if (familyIds.equals(recordFamilyId)) {
// record.setOwnData(1);
// }
// }
// }).collect(Collectors.toList());
// }
@Override
public AjaxResult selectDataList(ZfEconomy zfEconomy, Integer pageNum, Integer pageSize) {
// String familyIds = listFamilyIds();
// String secondFamilyAuthority = listSecondFamilyIds();
// LambdaQueryWrapper lqw = buildCondition(zfEconomy, familyIds, secondFamilyAuthority);
//
// Page zfEconomyPage = new Page<>(pageNum, pageSize);
// Page pageResult = page(zfEconomyPage, lqw);
//
// List beanRecords = pageResult.getRecords();//得到查询出来的数据
//
// List dtoResult = markOwnData(familyIds, beanRecords);
//
// HashMap data = MapUtils.getResult(pageResult, dtoResult);
// return AjaxResult.success(data);
//要查自己家庭的
ZInfoUser myself = zInfoUserService.getMyself();
if(myself==null)
{
// System.out.println("ssssss");
return AjaxResult.success("您没加入到对应的家庭,请联系管理员");
}
Long familyId = myself.getFamilyId();
//查看父母的数据:
Long fatherFaId = 0L;
if(myself.getFatherId()!=null)
fatherFaId = zInfoUserService.getInfoById(myself.getFatherId()).getFamilyId();
Long motherFaId = 0L;
if(myself.getMomId()!=null)
motherFaId = zInfoUserService.getInfoById(myself.getMomId()).getFamilyId();
//也要查别人授权的
List authority = zAuthorityService.getAuthority();
List idList = authority.stream().filter(auth -> auth.getAuthority().toString().equals(ECONOMY_LIST)).map(ZAuthority::getFid).collect(Collectors.toList());
//加上自己家庭的id
idList.add(familyId);
//加上父母家族id
idList.add(fatherFaId);
idList.add(motherFaId);
List fms = zInfoUserService.findByUaidToFaid(myself.getUaid()).stream().map(ZInfoUser::getFamilyId).collect(Collectors.toList());
if(!fms.isEmpty())
{
idList.addAll(fms);
}
// String familyIds = listFamilyIds();
// String secondFamilyAuthority = listSecondFamilyIds();
LambdaQueryWrapper lqw = buildCondition(zfEconomy, idList);
Page zfEconomyPage = new Page<>(pageNum, pageSize);
Page pageResult = page(zfEconomyPage, lqw);
List beanRecords = pageResult.getRecords();//得到查询出来的数据
List dtoResult = markOwnData(familyId, fatherFaId, motherFaId,beanRecords);
HashMap data = MapUtils.getResult(pageResult, dtoResult);
return AjaxResult.success(data);
}
public List markOwnData(Long familyId,Long fatherFamilyId, Long motherFamilyId,List beanRecords){
return beanRecords.stream().peek(
bean -> {
if (Objects.equals(bean.getFamilyId(), familyId) ||(fatherFamilyId!=0L && fatherFamilyId.equals(familyId))||(motherFamilyId!=0L && motherFamilyId.equals(familyId))) {
bean.setOwnData(1);
} else {
bean.setOwnData(0);
}
}
).sorted((a,b)-> b.getOwnData()-a.getOwnData()).collect(Collectors.toList());
}
// @Override
// public AjaxResult addData2(ZfEconomy zfEconomy){
// ZInfoUser mySelf = getMySelf();
// String myFamilyId = mySelf.getFamilyId();
//
// if (StringUtils.isNotEmpty(zfEconomy.getFamilyId())){
// throw new RuntimeException("导入数据时您不能指定家庭号");
// }
//
// if(StringUtils.isEmpty(myFamilyId)){
// throw new RuntimeException("您还未加入任何家庭");
// }
//
// if (myFamilyId.contains(",")){
// String[] myFamilyIds = myFamilyId.split(",");
// //默认添加第一个家庭的数据
// zfEconomy.setFamilyId(myFamilyIds[0]);
// }else {
// zfEconomy.setFamilyId(myFamilyId);
// }
//
// //判断是否有重复数据
// LambdaQueryWrapper lqw = uniqueCondition(zfEconomy);
// List list = list(lqw);
// if(list.size()>0){
// throw new RuntimeException("请勿新增重复数据");
// }
//
// if (save(zfEconomy)) {
// return AjaxResult.success();
// }else {
// return AjaxResult.error();
// }
// }
@Override
@Transactional
public AjaxResult importExcel(MultipartFile file) {
ExcelUtil util = new ExcelUtil<>(ZfEconomy.class);
List dataList = null;
try {
dataList = util.importExcel(file.getInputStream());
} catch (Exception e) {
throw new RuntimeException(e);
}
log.info("准备要导入的数据列表为:{}", dataList);
for (ZfEconomy zfEconomy : dataList) {
zfEconomyService.addData(zfEconomy);
}
return AjaxResult.success("导入数据成功");
}
@Override
public AjaxResult addData(ZfEconomy zfEconomy) {
ZInfoUser myself = zInfoUserService.getMyself();
Long familyId = myself.getFamilyId();
if(familyId == null){
throw new RuntimeException("您还未加入任何家庭");
}
List authority = zAuthorityService.getAuthority();
List familyIdList = authority.stream().filter(auth -> auth.getAuthority().toString().equals(ECONOMY_LIST_ADD)).map(ZAuthority::getFid).collect(Collectors.toList());
familyIdList.add(familyId);
if (zfEconomy.getFamilyId()!=null && !familyIdList.contains(zfEconomy.getFamilyId())) {
throw new RuntimeException("你没有权限操作此家庭的数据");
}
if(zfEconomy.getFamilyId() == null){
//默认添加自己家庭的数据
zfEconomy.setFamilyId(familyId);
}
//判断是否有重复数据
LambdaQueryWrapper lqw = uniqueCondition(zfEconomy);
List list = list(lqw);
if(list.size()>0){
throw new RuntimeException("请勿新增重复数据");
}
if (save(zfEconomy)) {
EsModel esModel = new EsModel();
Integer inte = zfEconomy.getId().intValue();
String uuid = UUID.randomUUID().toString().replace("-","");
esModel.setId(uuid);
esModel.setCtId(Long.valueOf(inte));
esModel.setCtTableName("家庭收支台账");
esModel.setBy1(zfEconomy.getUseFor());
esModel.setBy2(zfEconomy.getUsePeople());
esModel.setBy5("/family/zfEconomy");
esModel.setRemark(zfEconomy.getRemark());
esModel.setFid(familyId);
//这里存储查询详情的路径
esService.insertTable(esModel);
return AjaxResult.success();
} else {
return AjaxResult.error();
}
}
@Resource
ZfLogService zfLogService;
@Override
public AjaxResult updateData(ZfEconomy zfEconomy) {
ZInfoUser myself = zInfoUserService.getMyself();
Long familyId = myself.getFamilyId();
//先根据id查询出数据的familyId,看看有没有权限操作
Long dataFamilyId = getById(zfEconomy.getId()).getFamilyId();
List authority = zAuthorityService.getAuthority();
List familyIdList = authority.stream().filter(auth -> auth.getAuthority().toString().equals(ECONOMY_LIST_UPDATE)).map(ZAuthority::getFid).collect(Collectors.toList());
familyIdList.add(familyId);
if (dataFamilyId!=null && !familyIdList.contains(dataFamilyId)) {
throw new RuntimeException("你没有权限操作此家庭的数据");
}
//操作后加入日志
ZfLog zfLog = new ZfLog();
zfLog.setUpdateTime(LocalDateTime.now());
zfLog.setModule("家庭收支台账");
zfLog.setUpdater(zInfoUserService.getMyself().getNickName());
zfLogService.save(zfLog);
if(updateById(zfEconomy)){
//到数据库中查询对应的数据
ZfEconomy dataById = getById(zfEconomy.getId());
//先到es中查询到对应那条数据在es的id
EsModel esResult = esService.findByCtId(dataById.getId().intValue(), "家庭收支台账");
if (esResult == null){
return AjaxResult.success();
}
//操作es修改数据
EsModel newModel = new EsModel();
if(zfEconomy.getUseFor()!=null){
newModel.setBy1(zfEconomy.getUseFor());
}else {
newModel.setBy1(dataById.getUseFor());
}
if(zfEconomy.getUsePeople()!=null){
newModel.setBy2(zfEconomy.getUsePeople());
}else {
newModel.setBy2(dataById.getUsePeople());
}
if(zfEconomy.getRemark()!=null){
newModel.setRemark(zfEconomy.getRemark());
}else {
newModel.setRemark(dataById.getRemark());
}
UpdateRequest updateRequest = new UpdateRequest("allsearchdata", esResult.getId());
updateRequest.doc(
"by1",newModel.getBy1(),
"by2",newModel.getBy2(),
"remark",newModel.getRemark()
);
try {
restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
} catch (IOException e) {
throw new RuntimeException(e);
}
return AjaxResult.success();
}else {
return AjaxResult.error();
}
}
@Override
public AjaxResult deleteData(Long[] ids) {
List dataList = zfEconomyService.listByIds(Arrays.asList(ids));
ZInfoUser myself = zInfoUserService.getMyself();
Long familyId = myself.getFamilyId();
List authority = zAuthorityService.getAuthority();
List familyIdList = authority.stream().filter(auth -> auth.getAuthority().toString().equals(ECONOMY_LIST_REMOVE)).map(ZAuthority::getFid).collect(Collectors.toList());
familyIdList.add(familyId);
for (ZfEconomy data : dataList) {
if (!familyIdList.contains(data.getFamilyId())){
throw new RuntimeException("你没有权限操作此家庭的数据");
}
}
List zfEconomys = listByIds(Arrays.asList(ids));
if (! (zfEconomyDownlService.deleteData(ids) && zfEconomyShaService.deleteByContentId(ids) ) ){
return AjaxResult.error();
}
if (zfEconomyService.removeByIds(Arrays.asList(ids))) {
//删除es中的数据
zfEconomys.stream().forEach(zfEconomy -> {
EsModel esModel = esService.findByCtId(zfEconomy.getId().intValue(), "家庭收支台账");
if (esModel != null){
DeleteRequest deleteRequest = new DeleteRequest("allsearchdata", esModel.getId());
try {
restHighLevelClient.delete(deleteRequest,RequestOptions.DEFAULT);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
});
return AjaxResult.success();
}else {
return AjaxResult.error();
}
}
@Override
public AjaxResult listType() {
List result = zfEconomyMapper.listType();
return AjaxResult.success(result);
}
}