package com.hfwedo.spot.market.modules.sysconfig.service.impl;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.hfwedo.commons.ParseUtils;
import com.hfwedo.commons.pojo.OptionResult;
import com.hfwedo.commons.pojo.SearchParameter;
import com.hfwedo.spot.market.global.Const;
import com.hfwedo.spot.market.global.converter.PageConverter;
import com.hfwedo.spot.market.modules.sysconfig.service.SysClassifyGenAdjustService;
import com.hfwedo.spot.market.repository.spot.dao.SysClassifyDao;
import com.hfwedo.spot.market.repository.spot.dao.SysClassifyGenAdjustDao;
import com.hfwedo.spot.market.repository.spot.po.AsSpotPowerPlant;
import com.hfwedo.spot.market.repository.spot.po.BmSpotGenerator;
import com.hfwedo.spot.market.repository.spot.po.SysClassify;
import com.hfwedo.spot.market.repository.spot.po.SysClassifyGenAdjust;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@Service
@Transactional
public class SysClassifyGenAdjustServiceImpl implements SysClassifyGenAdjustService {
@Autowired
private SysClassifyGenAdjustDao sysClassifyGenAdjustDao;
@Autowired
private SysClassifyDao sysClassifyDao;
@Override
public OptionResult<?> query(SearchParameter sp) {
if (sp.hasFilters()) {
final String sysClassifyId = sp.stringFilterEscapeVal("sysClassifyId");
final String classifyCode = sp.stringFilterVal("classifyCode");
Specification<SysClassifyGenAdjust> specification = null;
if (sp.hasFilters()) {
specification = new Specification<SysClassifyGenAdjust>() {
public Predicate toPredicate(Root<SysClassifyGenAdjust> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
Predicate predicate = builder.conjunction();
if (!Strings.isNullOrEmpty(sysClassifyId)) {
predicate = builder.and(predicate, builder.equal(root.get("classify").get("id"), sysClassifyId));
}
if (!Strings.isNullOrEmpty(classifyCode)) {
predicate = builder.and(predicate, builder.equal(root.get("classify").get("code"), classifyCode));
}
return predicate;
}
};
}
PageRequest pr = PageConverter.buildPage(sp);
if (pr != null) {
return OptionResult.wrap(sysClassifyGenAdjustDao.findAll(specification, pr));
} else {
return OptionResult.wrap(sysClassifyGenAdjustDao.findAll(specification, PageConverter.buildSort(sp)));
}
} else {
return OptionResult.wrap(sysClassifyGenAdjustDao.findAll());
}
}
@Override
public OptionResult<?> query(String code, LocalDateTime begTime, LocalDateTime endTime) {
return OptionResult.wrap(sysClassifyGenAdjustDao.queryBmGenerator(code, begTime, endTime));
}
@Override
public OptionResult<?> queryTotal() {
SysClassify parent = sysClassifyDao.findByCode(Const.CONFIG_CLASSIFY_GEN_ADJUST);
if (parent != null) {
List<Map<String, Object>> genCounts = sysClassifyGenAdjustDao.sumByClassifyId();
List<Map<String, Object>> results = Lists.newArrayList();
List<SysClassify> genClassifies = sysClassifyDao.queryByParentId(parent.getId());
for (SysClassify genClassify : genClassifies) {
Map<String, Object> genCount = genCounts.stream().filter(x -> x.get("classifyId") != null && x.get("classifyId").equals(genClassify.getId())).findFirst().orElse(null);
Map<String, Object> result = Maps.newHashMap();
result.put("classify", genClassify);
result.put("count", genCount == null ? 0 : ParseUtils.parseInteger(genCount.get("count"), 1, 0));
results.add(result);
}
return OptionResult.wrap(results);
} else {
return OptionResult.fail("未发现编码为CONFIG_CLASSIFY_GEN_ADJUST的分类");
}
}
@Override
public OptionResult<?> delete(String[] ids) {
if (ids != null) {
for (String id : ids) {
sysClassifyGenAdjustDao.deleteById(id);
}
}
return OptionResult.done();
}
@Override
public OptionResult<?> save(String classifyId, String[] genIds) {
SysClassify classify = sysClassifyDao.findOne(classifyId);
for (String id : genIds) {
SysClassifyGenAdjust one = new SysClassifyGenAdjust();
one.setBmSpotGenerator(new BmSpotGenerator().setId(id));
one.setClassify(classify);
sysClassifyGenAdjustDao.save(one);
}
return OptionResult.done("保存完成");
}
@Override
public OptionResult<?> query(String[] codes, LocalDateTime begTime, LocalDateTime endTime) {
return OptionResult.wrap(sysClassifyGenAdjustDao.queryBmGenerator(Lists.newArrayList(codes), begTime, endTime));
}
@Override
public OptionResult<?> reorderSort(String id, boolean up) {
SysClassifyGenAdjust me = sysClassifyGenAdjustDao.findOne(id);
if (me != null) {
SysClassifyGenAdjust friend = null;
if (up) {
// 上移则查询排序号小于当前排序号的并且最大的对应的记录
friend = sysClassifyGenAdjustDao.findFirstBySortLessThanAndClassifyCodeOrderBySortDesc(me.getSort(),me.getClassify().getCode());
} else {
// 下移则查询排序号大于当前排序号的并且最小的对应的记录
friend = sysClassifyGenAdjustDao.findFirstBySortGreaterThanAndClassifyCodeOrderBySortAsc(me.getSort(),me.getClassify().getCode());
}
if (friend != null) {
// 交换排序号,保存
Integer sort = me.getSort();
me.setSort(friend.getSort());
friend.setSort(sort);
sysClassifyGenAdjustDao.save(friend);
sysClassifyGenAdjustDao.save(me);
return OptionResult.done();
}
}
return OptionResult.fail();
}
@Override
public OptionResult<?> reorderDragSort(String currRowId, String sortRowId) {
SysClassifyGenAdjust current = sysClassifyGenAdjustDao.findOne(currRowId);
SysClassifyGenAdjust sort = sysClassifyGenAdjustDao.findOne(sortRowId);
List<SysClassifyGenAdjust> all = sysClassifyGenAdjustDao.findByClassifyCode(current.getClassify().getCode());
for (int i = 0; i < all.size(); i++) {
all.get(i).setSort(i + 1);
}
sysClassifyGenAdjustDao.saveAll(all);
if (current != null && sort != null) {
if (current.getSort() < sort.getSort()) {
Integer oldCurrentSort = current.getSort();
current.setSort(sort.getSort());
for (SysClassifyGenAdjust sysClassifyGenAdjust : all) {
if (sysClassifyGenAdjust.getSort() > oldCurrentSort && sysClassifyGenAdjust.getSort() <= sort.getSort() && !Objects.equals(sysClassifyGenAdjust.getId(), currRowId)) {
sysClassifyGenAdjust.setSort(sysClassifyGenAdjust.getSort() - 1);
}
}
sysClassifyGenAdjustDao.saveAll(all);
} else {
Integer oldCurrentSort = current.getSort();
current.setSort(sort.getSort());
for (SysClassifyGenAdjust sysClassifyGenAdjust : all) {
if (sysClassifyGenAdjust.getSort() >= sort.getSort() && sysClassifyGenAdjust.getSort() < oldCurrentSort && !Objects.equals(sysClassifyGenAdjust.getId(), currRowId)) {
sysClassifyGenAdjust.setSort(sysClassifyGenAdjust.getSort() + 1);
}
}
sysClassifyGenAdjustDao.saveAll(all);
}
return OptionResult.done();
}
return OptionResult.fail();
}
}<template>
<div>
<el-dialog :title="title"
:visible.sync="visible"
:close-on-click-modal="false"
:before-close="handleClose"
width="1300px"
append-to-body
style="min-height: 600px" @open="handleOpen">
<div style="height:60vh">
<el-form :inline="true" class="sys-tool-bar">
<el-form-item>
<el-button type="primary" icon="el-icon-circle-plus" @click="handleAddClick">添加</el-button>
<el-button type="danger" icon="el-icon-delete" @click="handleDeleteClicks">删除</el-button>
</el-form-item>
</el-form>
<el-table ref="multipleTable" v-loading="loading" :stripe="true" :data="tableData" style="width: 100%" highlight-current-row border :height="550">
<el-table-column prop="sort" width="50" halign="center" align="center"/>
<el-table-column type="selection" width="50" align="center"/>
<el-table-column prop="bmSpotGenerator.bmSpotPowerPlant.name" label="电厂" width="150" halign="center" header-align="center" align="center"/>
<el-table-column prop="bmSpotGenerator.fullName" label="机组名称" halign="center" header-align="center" align="center"/>
<el-table-column prop="bmSpotGenerator.inTime" align="center" width="100" label="启用时间" :formatter="dateFormatter"/>
<el-table-column prop="bmSpotGenerator.outTime" align="center" width="100" label="停用时间" :formatter="dateFormatter"/>
<el-table-column prop="bmSpotGenerator.powerType" label="发电类型" width="200" halign="center" header-align="center" align="center" :formatter="powerTypeFormatter"/>
<el-table-column prop="bmSpotGenerator.voltage" label="电压等级" width="120" halign="center" header-align="center" align="center" :formatter="voltageFormatter"/>
<el-table-column label="操作" align="center" class-name="sys-grid-opts" width="300">
<template slot-scope="scope">
<el-link icon="el-icon-thumb" type="warning">拖动排序</el-link>
<el-link icon="el-icon-top" type="info" @click="reorder(scope.row,true)">上移</el-link>
<el-link icon="el-icon-bottom" type="info" @click="reorder(scope.row)">下移</el-link>
</template>
</el-table-column>
</el-table>
</div>
</el-dialog>
<sys-classify-gen-adjust-choose v-model="genAdjustChooseDialog.visible" v-bind="genAdjustChooseDialog" @saveSuccess="handleSaveSuccess"/>
</div>
</template>
<script>
import vModelDialog from '@/mixins/vModelDialog';
import SysClassifyGenAdjustChoose from './SysClassifyGenAdjustChoose';
import moment from 'moment';
import Sortable from 'sortablejs';
export default {
components: { SysClassifyGenAdjustChoose },
mixins: [vModelDialog],
props: ['title', 'oid'],
data() {
return {
tableData: [],
loading: false,
genAdjustChooseDialog: {
visible: false,
title: '',
oid: '',
existIds: ''
}
};
},
methods: {
handleAddClick() {
const generatorIds = this.tableData.filter(item => item.bmSpotGenerator != null).map(item => item.bmSpotGenerator.id);
this.genAdjustChooseDialog.visible = true;
this.genAdjustChooseDialog.title = '机组选择';
this.genAdjustChooseDialog.oid = this.oid;
this.genAdjustChooseDialog.existIds = generatorIds.join();
},
handleDeleteClicks() {
const ids = this.$refs.multipleTable.selection.map(item => item.id);
if (!ids.length) {
this.$alert('请选择要删除的数据', '提示');
return;
}
this.$confirm('确定要删除' + ids.length + '条数据吗?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
this.$http.post('/config/sysClassifyGenAdjust/delete', this.$qs.stringify({
ids: ids.join()
})).then((r) => {
if (r.successful) {
this.handleOpen();
}
});
}).catch(() => {
this.$message({
type: 'info',
message: '已取消删除'
});
});
},
dateFormatter(row, column, cellValue) {
if (!cellValue) {
return '';
}
return moment(cellValue).format('YYYY-MM-DD');
},
powerTypeFormatter(row, column, cellValue) {
return this.$store.getters.getEnumTextByValue('powerTypes', cellValue);
},
voltageFormatter(row, column, cellValue) {
return this.$store.getters.getEnumTextByValue('voltageTypes', cellValue);
},
handleSaveSuccess() {
this.handleOpen();
},
async handleOpen() {
if (this.oid) {
this.loading = true;
try {
const { successful, data } = await this.$http.post('/config/sysClassifyGenAdjust', {
filters: {
sysClassifyId: this.oid
},
sort: 'sort,bmSpotGenerator.powerType,bmSpotGenerator.bmSpotPowerPlant,bmSpotGenerator.fullName',
order: 'asc'
});
if (successful) {
this.tableData = data || [];
this.$nextTick(() => {
this.rowDrop();
});
}
this.loading = false;
} catch (e) {
this.loading = false;
console.error('数据加载失败:', e);
}
}
},
reorder(row, up) {
if (!row?.id) {
this.$message.warning('无效的行数据');
return;
}
this.$http.post('/config/sysClassifyGenAdjust/reorderSort', this.$qs.stringify({
id: row.id,
up: !!up
})).then((r) => {
if (r.successful) {
this.handleOpen();
} else {
this.$message.error('排序失败');
}
}).catch(e => {
console.error('上移下移接口错误:', e);
});
},
rowDrop() {
const table = this.$refs.multipleTable;
if (!table) {
console.warn('未找到表格实例');
return;
}
const tbody = table.$el.querySelector('.el-table__body tbody');
if (!tbody) {
console.warn('表格未渲染tbody元素');
return;
}
const _this = this;
Sortable.create(tbody, {
draggable: '.el-table__row',
animation: 150,
onEnd({ newIndex, oldIndex }) {
if (newIndex === oldIndex) return;
const currRow = _this.tableData[oldIndex];
_this._updateMoveData(newIndex, oldIndex, currRow);
}
});
},
async _updateMoveData(newIndex, oldIndex, currRow) {
if (!currRow?.id) {
this.$message.warning('当前行ID不存在');
return;
}
let sortRowId = null;
if (newIndex > oldIndex) {
if (newIndex < this.tableData.length) {
sortRowId = this.tableData[newIndex]?.id;
}
} else if (newIndex < oldIndex) {
if (newIndex >= 0) {
sortRowId = this.tableData[newIndex]?.id;
}
}
if (!sortRowId) {
this.$message.warning('目标行ID不存在');
return;
}
try {
const res = await this.$http.post(
'/config/sysClassifyGenAdjust/reorderDragSort',
this.$qs.stringify({
currRowId: currRow.id,
sortRowId: sortRowId
})
);
if (res.successful) {
this.handleOpen();
} else {
this.$message.error('拖拽排序失败');
}
} catch (e) {
console.error('拖拽排序接口错误:', e);
this.$message.error('拖拽排序请求失败');
}
},
handleClose() {
this.innerVisible = false;
this.$emit('saveSuccess');
}
}
};
</script>
<style scoped>
.el-table__row {
cursor: move;
}
.el-table__row.sortable-ghost {
opacity: 0.6;
background-color: #f0f2f5;
}
</style>
现在的拖拽功能有问题,请帮我修改一下这一个模块的代码