package com.ruoyi.web.controller.api;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.basic.PageInfo;
import com.ruoyi.common.core.domain.BaseModel;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.WebUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.dto.LocationDTO;
import com.ruoyi.system.importExcel.TLocationImportExcel;
import com.ruoyi.system.model.*;
import com.ruoyi.system.query.LocationListQuery;
import com.ruoyi.system.query.LocationListTaskQuery;
import com.ruoyi.system.service.*;
import com.ruoyi.system.utils.CustomerImportFailedData;
import com.ruoyi.system.vo.system.*;
import com.sun.org.apache.bcel.internal.generic.NEW;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;
/**
*
* 点位管理 前端控制器
*
*
* @author xiaochen
* @since 2025-05-28
*/
@Slf4j
@Api(tags = "点位管理")
@RestController
@RequestMapping("/t-location")
public class TLocationController {
@Resource
private TLocationTypeService locationTypeService;
@Resource
private TLocationService locationService;
@Resource
private TProjectDeptService projectDeptService;
@Resource
private TCleanerService cleanerService;
@Resource
private TTaskCleanService tTaskCleanService;
@Resource
private TTaskDetailService tTaskDetailService;
@Resource
private TDeptService deptService;
@Resource
private ISysUserService sysUserService;
@Resource
private TokenService tokenService;
@ApiOperation(value = "点位管理分页列表")
@PostMapping(value = "/pageList")
public R> pageList(@RequestBody LocationListQuery query) {
return R.ok(locationService.pageList(query));
}
@ApiOperation(value = "点位管理-巡检记录分页列表")
@PostMapping(value = "/pageListTask")
public R> pageListTask(@RequestBody LocationListTaskQuery query) {
List sysUsers = sysUserService.selectAllList();
List locationTypeList = locationTypeService.list();
List deptList = deptService.list();
List projectDeptList = projectDeptService.list();
List locationList = locationService.list();
if (StringUtils.hasLength(query.getDeptName())){
List projectIds = projectDeptService.lambdaQuery().like(TProjectDept::getProjectName, query.getDeptName()).list()
.stream().map(TProjectDept::getId).collect(Collectors.toList());
List deptIds = deptService.lambdaQuery().like(TDept::getDeptName, query.getDeptName()).list()
.stream().map(TDept::getId).collect(Collectors.toList());
projectIds.addAll(deptIds);
if (projectIds.isEmpty()){
return R.ok(new PageInfo<>());
}
if (StringUtils.hasLength(query.getPhonenumber())){
List patrolInspectorIds = sysUsers.stream().filter(sysUser ->
sysUser.getPhonenumber().equals(query.getPhonenumber())
&& projectIds.contains(sysUser.getDeptId())
).map(SysUser::getUserId).collect(Collectors.toList());
if (patrolInspectorIds.isEmpty()){
return R.ok(new PageInfo<>());
}
query.setPatrolInspectorIds(patrolInspectorIds);
}
}else if (StringUtils.hasLength(query.getPhonenumber())){
List patrolInspectorIds = sysUsers.stream().filter(sysUser ->
sysUser.getPhonenumber().equals(query.getPhonenumber())
).map(SysUser::getUserId).collect(Collectors.toList());
query.setPatrolInspectorIds(patrolInspectorIds);
if (patrolInspectorIds.isEmpty()){
return R.ok(new PageInfo<>());
}
}
if (query.getClearStatus()!=null){
List collect = tTaskDetailService.lambdaQuery().eq(TTaskDetail::getClearStatus, query.getClearStatus())
.list().stream().distinct().map(TTaskDetail::getTaskId).collect(Collectors.toList());
query.setTaskIds(collect);
if (collect.isEmpty()){
return R.ok(new PageInfo<>());
}
}
PageInfo pageInfo = new PageInfo<>(query.getPageNum(), query.getPageSize());
List list = tTaskCleanService.lambdaQuery()
.eq(TTask::getLocationId, query.getId())
.between(StringUtils.hasLength(query.getStartTime()), TTask::getImplementTime, query.getStartTime(), query.getEndTime())
.eq(query.getStatus() != null, TTask::getStatus, query.getStatus())
.in(query.getPatrolInspectorIds() != null && query.getPatrolInspectorIds().isEmpty(), TTask::getPatrolInspector, query.getPatrolInspectorIds())
.in(query.getTaskIds() != null && query.getTaskIds().isEmpty(), TTask::getId, query.getTaskIds()).list();
List collect = list.stream().map(TTask::getId).collect(Collectors.toList());
List res = new ArrayList<>();
if (collect.isEmpty()){
return R.ok(pageInfo);
}
List taskDetails = tTaskDetailService.list(Wrappers.lambdaQuery(TTaskDetail.class)
.in(TTaskDetail::getTaskId,collect)
.eq(TTaskDetail::getClearStatus, 2)
.eq(TTaskDetail::getHandleType,1)
.orderByDesc(TTaskDetail::getCreateTime));
taskDetails = new ArrayList<>(taskDetails.stream()
.collect(Collectors.groupingBy(
TTaskDetail::getTaskId,
Collectors.collectingAndThen(
Collectors.toList(),
listAll -> listAll.get(0)
)
))
.values());
for (TTask tTask : list) {
LocationListTaskVO temp = new LocationListTaskVO();
TLocation tLocation = locationList.stream().filter(e -> e.getId().equals(tTask.getLocationId())).findFirst().orElse(null);
if (tLocation!=null){
BeanUtils.copyProperties(tLocation, temp);
sysUsers.stream().filter(sysUser -> Objects.equals(sysUser.getUserId(), Long.valueOf(tTask.getPatrolInspector()))).findFirst().ifPresent(sysUser -> {
temp.setPatrolInspectorName(sysUser.getUserName());
temp.setPhonenumber(sysUser.getPhonenumber());
if (1==sysUser.getDeptType()){
TProjectDept tProjectDept = projectDeptList.stream().filter(e -> e.getId().equals(sysUser.getDeptId())).findFirst().orElse(null);
if (tProjectDept!=null&&!tProjectDept.getParentId().equals("0")){
TProjectDept tProjectDept1 = projectDeptList.stream().filter(e -> e.getId().equals(tProjectDept.getParentId())).findFirst().orElse(null);
if (tProjectDept1!=null){
temp.setDeptName(tProjectDept1.getProjectName()+">"+tProjectDept.getProjectName());
}
}else{
if (tProjectDept!=null){
temp.setDeptName(tProjectDept.getProjectName());
}
}
}else{
TDept tDept = deptList.stream().filter(e -> e.getId().equals(sysUser.getDeptId())).findFirst().orElse(null);
if (tDept!=null){
temp.setDeptName(tDept.getDeptName());
}
}
});
locationTypeList.stream().filter(e -> e.getId().equals(tLocation.getLocationType())).findFirst()
.ifPresent(tLocationType -> temp.setLocationTypeName(tLocationType.getLocationName()));
}
TTaskDetail tTaskDetail = taskDetails.stream().filter(e -> e.getTaskId().equals(tTask.getId())).findFirst().orElse(null);
if (tTaskDetail!=null){
temp.setPicture(tTaskDetail.getPicture());
temp.setClearStatus(tTaskDetail.getClearStatus());
if (query.getClearStatus()!=null){
if (query.getClearStatus().equals(tTaskDetail.getClearStatus())){
res.add(temp);
}
}else{
res.add(temp);
}
}
temp.setTaskType(tTask.getTaskType());
temp.setStatus(tTask.getStatus());
temp.setTaskId(tTask.getId());
temp.setImplementTime(tTask.getImplementTime());
}
res = res.stream().skip((long) (query.getPageNum() - 1) * query.getPageSize()).limit(query.getPageSize()).collect(Collectors.toList());
pageInfo.setTotal(res.size());
pageInfo.setRecords(res);
return R.ok(pageInfo);
}
@ApiOperation(value = "根据片区id查询保洁员列表 不分页")
@GetMapping(value = "/listCleaner")
public R> listCleaner(@RequestParam String id) {
return R.ok(cleanerService.lambdaQuery().eq(TCleaner::getProjectId,id).list());
}
@ApiOperation(value = "根据保洁员id查询点位列表 不分页")
@GetMapping(value = "/listLocation")
public R> listLocation(@RequestParam String id) {
return R.ok(locationService.lambdaQuery().eq(TLocation::getLocationCleaner,id).list());
}
@ApiOperation(value = "查询部门 项目部列表 不分页")
@GetMapping(value = "/listDepts")
public R> listDepts() {
List parent = projectDeptService.lambdaQuery().eq(TProjectDept::getParentId, "0").list();
List child = projectDeptService.lambdaQuery().ne(TProjectDept::getParentId, "0").list();
List depts = deptService.list();
List res = new ArrayList<>();
DeptNoLimitVO deptNoLimitVO1 = new DeptNoLimitVO();
deptNoLimitVO1.setDeptName("项目部");
DeptNoLimitVO deptNoLimitVO2 = new DeptNoLimitVO();
deptNoLimitVO2.setDeptName("公司");
res.add(deptNoLimitVO1);
res.add(deptNoLimitVO2);
for (DeptNoLimitVO re : res) {
if (re.getDeptName().equals("项目部")){
List deptNoLimitVOS = new ArrayList<>();
for (TProjectDept tProjectDept : parent) {
DeptNoLimitParentVO deptNoLimitVO = new DeptNoLimitParentVO();
deptNoLimitVO.setDeptName(tProjectDept.getProjectName());
deptNoLimitVO.setDeptId(tProjectDept.getId());
List collect = child.stream().filter(e -> e.getParentId().equals(tProjectDept.getId())).collect(Collectors.toList());
List deptNoLimitChildVOS = new ArrayList<>();
for (TProjectDept projectDept : collect) {
DeptNoLimitChildVO deptNoLimitChildVO = new DeptNoLimitChildVO();
deptNoLimitChildVO.setDeptName(projectDept.getProjectName());
deptNoLimitChildVO.setDeptId(projectDept.getId());
deptNoLimitChildVOS.add(deptNoLimitChildVO);
}
deptNoLimitVO.setDeptChild(deptNoLimitChildVOS);
deptNoLimitVOS.add(deptNoLimitVO);
}
re.setDeptChild(deptNoLimitVOS);
}else {
List deptNoLimitVOS = new ArrayList<>();
for (TDept tDept : depts) {
DeptNoLimitParentVO deptNoLimitVO = new DeptNoLimitParentVO();
deptNoLimitVO.setDeptName(tDept.getDeptName());
deptNoLimitVO.setDeptId(tDept.getId());
deptNoLimitVOS.add(deptNoLimitVO);
}
re.setDeptChild(deptNoLimitVOS);
}
}
return R.ok(res);
}
@ApiOperation(value = "根据部门/项目部id查询巡检员列表 不分页")
@GetMapping(value = "/listUsers")
public R> listUsers(@RequestParam String id) {
List strings = new ArrayList<>();
strings.add(id);
TProjectDept projectDept = projectDeptService.getById(id);
if (projectDept!=null){
if (projectDept.getParentId().equals("0")){
List collect = projectDeptService.lambdaQuery().eq(TProjectDept::getParentId, projectDept.getId())
.list().stream().map(TProjectDept::getId).collect(Collectors.toList());
strings.addAll(collect);
}
}else{
List collect = deptService.lambdaQuery().eq(TDept::getId, id)
.list().stream().map(TDept::getId).collect(Collectors.toList());
strings.addAll(collect);
}
List res = sysUserService.selectUserByDeptId(strings);
return R.ok(res);
}
@Log(title = "新增点位", businessType = BusinessType.INSERT)
@ApiOperation(value = "新增点位")
@PostMapping(value = "/add")
public R add(@RequestBody LocationDTO dto) {
locationService.save(dto);
return R.ok();
}
@Log(title = "编辑点位", businessType = BusinessType.UPDATE)
@ApiOperation(value = "编辑点位")
@PostMapping(value = "/edit")
public R edit(@RequestBody LocationDTO dto) {
locationService.updateById(dto);
return R.ok();
}
@ApiOperation(value = "详情点位")
@GetMapping(value = "/detail")
public R detail(@RequestParam String id) {
return R.ok(locationService.getById(id));
}
@Log(title = "批量删除点位", businessType = BusinessType.DELETE)
@ApiOperation(value = "批量删除点位")
@DeleteMapping(value = "/delete")
public R edit(@RequestParam String ids) {
String[] split = ids.split(",");
locationService.removeBatchByIds(Arrays.asList(split));
return R.ok();
}
@ApiOperation(value = "点位导入模板下载")
@GetMapping("/import-template")
public void importTemplate() {
List locationImportExcels = new ArrayList<>();
TLocationImportExcel tLocationImportExcel = new TLocationImportExcel();
locationImportExcels.add(tLocationImportExcel);
Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), TLocationImportExcel.class, locationImportExcels);
HttpServletResponse response = WebUtils.response();
ServletOutputStream outputStream = null;
try {
String fileName = URLEncoder.encode("点位导入模板.xls", "utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
response.setHeader("content-Type", "application/vnd.ms-excel");
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
outputStream = response.getOutputStream();
workbook.write(outputStream);
} catch (IOException e) {
e.printStackTrace();
System.out.println("点位导入模板下载失败!");
} finally {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Log(title = "点位导入", businessType = BusinessType.INSERT)
@ApiOperation(value = "点位导入")
@Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRES_NEW)
@PostMapping("/importLocation")
public R importLocation(@RequestPart("file") MultipartFile file) {
ImportParams params = new ImportParams();
// params.setTitleRows(1); // 标题行数
params.setHeadRows(1); //表头行数
InputStream inputStream = null;
// List failedData = new ArrayList<>();
List locationExcelList;
try {
inputStream = file.getInputStream();
locationExcelList = ExcelImportUtil.importExcel(inputStream,
TLocationImportExcel.class, params);
} catch (Exception e) {
e.printStackTrace();
log.error("点位导入失败:{}", e.getMessage());
throw new ServiceException("点位导入失败!");
} finally {
try {
inputStream.close();
} catch (IOException e) {
throw new ServiceException(e.getMessage());
}
}
if (CollectionUtils.isEmpty(locationExcelList)) {
throw new ServiceException("点位数据为空!");
}
// List saveOrUpdateList = new ArrayList<>();
// 查询所有类型点位
List locationTypes = locationTypeService.list();
// 查询所有用户
List users = sysUserService.selectAllList();
// 查询所有部门
List deptList = projectDeptService.list();
// 查询所有保洁员
List cleaners = cleanerService.list();
JSONObject result = new JSONObject();
for (TLocationImportExcel locationExcel : locationExcelList) {
System.err.println(locationExcel);
TLocation location = new TLocation();
location.setLocationCode(locationExcel.getLocationCode());
location.setLocationName(locationExcel.getLocationName());
TLocationType tLocationType = locationTypes.stream().filter(locationType -> locationType.getLocationName().equals(locationExcel.getLocationType())).findFirst().orElse(null);
if (Objects.nonNull(tLocationType)){
location.setLocationType(tLocationType.getId());
}
location.setLocationAddress(locationExcel.getLocationAddress());
String[] addressLonLat = locationExcel.getLocationAddressLonLat().split(",");
location.setLocationLon(addressLonLat[0]);
location.setLocationLat(addressLonLat[1]);
location.setLocationAddressEnd(locationExcel.getLocationAddressEnd());
String[] addressEndLonLat = locationExcel.getLocationAddressEndLonLat().split(",");
location.setLocationLonEnd(addressEndLonLat[0]);
location.setLocationLatEnd(addressEndLonLat[1]);
TProjectDept projectDept = deptList.stream().filter(dept -> dept.getCode().equals(locationExcel.getDeptCode())).findFirst().orElse(null);
if(Objects.nonNull(projectDept)){
location.setProjectId(projectDept.getId());
}else {
result.append("路段名:[", locationExcel.getLocationName()+"]未查询到部门");
continue;
}
SysUser sysUser = users.stream().filter(user -> user.getNickName().equals(locationExcel.getNickName())).findFirst().orElse(null);
if(Objects.nonNull(sysUser)){
location.setLocationLeader(String.valueOf(sysUser.getUserId()));
}else {
result.append("路段名:[", locationExcel.getLocationName()+"]未查询到点位负责人");
continue;
}
TCleaner tCleaner = cleaners.stream().filter(cleaner -> cleaner.getCleanerCode().equals(locationExcel.getCleanerCodeClear())
&& cleaner.getDeptCode().equals(locationExcel.getDeptCodeClear())
&& cleaner.getProjectCode().equals(locationExcel.getProjectCodeClear())
&& cleaner.getCleanerName().equals(locationExcel.getCleanerName())).findFirst().orElse(null);
if(Objects.nonNull(tCleaner)){
location.setLocationCleaner(tCleaner.getId());
}else {
result.append("路段名:[", locationExcel.getLocationName()+"]未查询到保洁员");
continue;
}
locationService.save(location);
}
if(!result.isEmpty()){
return R.ok(result.toString());
}
return R.ok();
}
}