code
stringlengths 1
1.05M
| repo_name
stringlengths 6
83
| path
stringlengths 3
242
| language
stringclasses 222
values | license
stringclasses 20
values | size
int64 1
1.05M
|
|---|---|---|---|---|---|
package org.example.main.entity;
public class Record {
private long recordId;
private long houseId;
private long tenantId;
private java.sql.Timestamp recordTime;
public long getRecordId() {
return recordId;
}
public void setRecordId(long recordId) {
this.recordId = recordId;
}
public long getHouseId() {
return houseId;
}
public void setHouseId(long houseId) {
this.houseId = houseId;
}
public long getTenantId() {
return tenantId;
}
public void setTenantId(long tenantId) {
this.tenantId = tenantId;
}
public java.sql.Timestamp getRecordTime() {
return recordTime;
}
public void setRecordTime(java.sql.Timestamp recordTime) {
this.recordTime = recordTime;
}
}
|
2301_79970562/student_union_backend
|
src/main/java/org/example/main/entity/Record.java
|
Java
|
unknown
| 750
|
package org.example.main.entity;
import io.swagger.v3.oas.annotations.media.Schema;
import java.util.Date;
@Schema(name = "RentalApplication",description = "租赁申请实体")
public class RentalApplication {
@Schema(name = "applicationId",description = "申请id")
private long applicationId;
@Schema(name = "houseId",description = "房源id")
private long houseId;
@Schema(name = "tenantId",description = "租客id")
private long tenantId;
@Schema(name = "applicationTime",description = "申请时间")
private Date applicationTime;
@Schema(name = "status",description = "申请状态")
private String status;
@Schema(name = "type",description = "申请类型")
private String type;
public long getApplicationId() { return applicationId; }
public void setApplicationId(long applicationId) { this.applicationId = applicationId; }
public long getHouseId() { return houseId; }
public void setHouseId(long houseId) { this.houseId = houseId; }
public long getTenantId() { return tenantId; }
public void setTenantId(long tenantId) { this.tenantId = tenantId; }
public Date getApplicationTime() { return applicationTime; }
public void setApplicationTime(Date applicationTime) { this.applicationTime = applicationTime; }
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
|
2301_79970562/student_union_backend
|
src/main/java/org/example/main/entity/RentalApplication.java
|
Java
|
unknown
| 1,498
|
package org.example.main.entity;
import io.swagger.v3.oas.annotations.media.Schema;
@Schema(name = "Tenant",description = "租客实体")
public class Tenant {
@Schema(name = "tenantId",description = "租客id")
private long tenantId;
@Schema(name = "username",description = "用户名")
private String username;
@Schema(name = "password",description = "密码")
private String password;
@Schema(name = "phone",description = "手机号")
private String phone;
@Schema(name = "email",description = "邮箱地址")
private String email;
public long getTenantId() {
return tenantId;
}
public void setTenantId(long tenantId) {
this.tenantId = tenantId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
|
2301_79970562/student_union_backend
|
src/main/java/org/example/main/entity/Tenant.java
|
Java
|
unknown
| 1,220
|
package org.example.main.service;
import org.example.main.entity.Admin;
import java.util.List;
import java.util.Map;
public interface AdminService {
int add(Admin admin);
int deleteById(long adminId);
int updateById(Admin admin); // 不修改 admin_id
Admin findById(long adminId);
Admin findByUsername(String username);
List<Admin> findAll();
public Map<String, Object> getAdminPage(int currentPage, int size);
}
|
2301_79970562/student_union_backend
|
src/main/java/org/example/main/service/AdminService.java
|
Java
|
unknown
| 445
|
package org.example.main.service;
import org.example.main.entity.Comment;
import org.example.main.entity.Tenant;
import java.util.List;
public interface CommentService {
int add(Comment comment);
int deleteById(long commentId);
int update(Comment comment);
List<Comment> findByHouseId(long houseId);
List<Comment> findByTenantId(long tenantId);
Comment findByHouseIdAndTenantId(long houseId, long tenantId);
List<Comment> findAll();
}
|
2301_79970562/student_union_backend
|
src/main/java/org/example/main/service/CommentService.java
|
Java
|
unknown
| 467
|
package org.example.main.service;
import org.example.main.entity.Favorite;
import java.util.List;
public interface FavoriteService {
int add(Favorite favorite);
int removeById(long favoriteId);
int removeByTenantAndHouse(long tenantId, long houseId);
List<Favorite> findAll();
List<Favorite> getByTenantId(long tenantId);
List<Favorite> getByHouseId(long houseId);
Favorite getByTenantAndHouse(long tenantId, long houseId);
}
|
2301_79970562/student_union_backend
|
src/main/java/org/example/main/service/FavoriteService.java
|
Java
|
unknown
| 457
|
package org.example.main.service;
import org.example.main.entity.House;
import java.util.List;
public interface HouseService {
int add(House house);
int update(House house);
int deleteById(long houseId);
House findById(long houseId);
List<House> findAll();
List<House> findByLandlordId(long landlordId);
List<House> findByStatus(String status);
List<House> findByTitle(String title);
List<House> findByArea(String area);
int updateStatus(long houseId, String status);
}
|
2301_79970562/student_union_backend
|
src/main/java/org/example/main/service/HouseService.java
|
Java
|
unknown
| 512
|
package org.example.main.service;
import org.example.main.entity.Landlord;
import java.util.List;
public interface LandlordService {
int add(Landlord landlord);
int deleteById(long landlordId);
int updateById(Landlord landlord); // 不修改 landlordId
Landlord findById(long landlordId);
Landlord findByUsername(String username);
List<Landlord> findAll();
}
|
2301_79970562/student_union_backend
|
src/main/java/org/example/main/service/LandlordService.java
|
Java
|
unknown
| 391
|
package org.example.main.service;
import org.example.main.entity.Record;
import java.util.List;
public interface RecordService {
int add(Record record);
int deleteById(long recordId);
List<Record> findAll();
List<Record> findByHouseId(long houseId);
List<Record> findByTenantId(long tenantId);
}
|
2301_79970562/student_union_backend
|
src/main/java/org/example/main/service/RecordService.java
|
Java
|
unknown
| 319
|
package org.example.main.service;
import org.example.main.entity.RentalApplication;
import java.util.List;
public interface RentalApplicationService {
int apply(RentalApplication application);
int updateStatus(long applicationId, String status);
int delete(long applicationId);
RentalApplication findById(long applicationId);
List<RentalApplication> findByTenantId(long tenantId);
List<RentalApplication> findByHouseId(long houseId);
RentalApplication findByTenantIdAndHouseIdAndType(long tenantId, long houseId, String type);
List<RentalApplication> findAll();
}
|
2301_79970562/student_union_backend
|
src/main/java/org/example/main/service/RentalApplicationService.java
|
Java
|
unknown
| 598
|
package org.example.main.service;
import org.example.main.entity.Tenant;
import java.util.List;
public interface TenantService {
int add(Tenant tenant);
int deleteById(long tenantId);
int updateById(Tenant tenant);
Tenant findById(long tenantId);
Tenant findByUsername(String username);
List<Tenant> findAll();
}
|
2301_79970562/student_union_backend
|
src/main/java/org/example/main/service/TenantService.java
|
Java
|
unknown
| 340
|
package org.example.main.service.impl;
import org.apache.log4j.Logger;
import org.example.main.entity.Admin;
import org.example.main.dao.AdminMapper;
import org.example.main.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class AdminServiceImpl implements AdminService {
private static final Logger logger = Logger.getLogger(AdminServiceImpl.class);
@Autowired
private AdminMapper adminMapper;
@Override
public int add(Admin admin) {
logger.info("Adding new admin with username: " + admin.getUsername());
int result = adminMapper.insert(admin);
logger.info("Admin added with ID: " + admin.getAdminId() + ", result: " + result);
return result;
}
@Override
public int deleteById(long adminId) {
logger.info("Deleting admin by ID: " + adminId);
int result = adminMapper.deleteById(adminId);
logger.info("Admin deletion result: " + result);
return result;
}
@Override
public int updateById(Admin admin) {
logger.info("Updating admin with ID: " + admin.getAdminId());
int result = adminMapper.updateById(admin);
logger.info("Admin update result: " + result);
return result;
}
@Override
public Admin findById(long adminId) {
logger.info("Finding admin by ID: " + adminId);
Admin admin = adminMapper.findById(adminId);
logger.debug("Found admin: " + admin);
return admin;
}
@Override
public Admin findByUsername(String username) {
logger.info("Finding admin by username: " + username);
Admin admin = adminMapper.findByUsername(username);
logger.debug("Found admin: " + admin);
return admin;
}
@Override
public List<Admin> findAll() {
logger.info("Retrieving all admins");
List<Admin> admins = adminMapper.findAll();
logger.debug("Found " + admins.size() + " admins");
return admins;
}
@Override
public Map<String, Object> getAdminPage(int currentPage, int size) {
logger.info("Getting admin page - currentPage: " + currentPage + ", size: " + size);
//计算分页起始行的索引
int start = (currentPage - 1) * size;
//创建Map对象,用于储存储存分页的结果
Map<String, Object> resultMap = new HashMap<>();
resultMap.put("total",adminMapper.findAll().size());
resultMap.put("record",adminMapper.getUserByPage(start,size));
logger.debug("Page result - total: " + resultMap.get("total"));
return resultMap;
}
}
|
2301_79970562/student_union_backend
|
src/main/java/org/example/main/service/impl/AdminServiceImpl.java
|
Java
|
unknown
| 2,761
|
package org.example.main.service.impl;
import org.apache.log4j.Logger;
import org.example.main.dao.CommentMapper;
import org.example.main.entity.Comment;
import org.example.main.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class CommentServiceImpl implements CommentService {
private static final Logger logger = Logger.getLogger(CommentServiceImpl.class);
@Autowired
private CommentMapper commentMapper;
@Override
public int add(Comment comment){
logger.info("Adding new comment for house ID: " + comment.getHouseId() + " by tenant ID: " + comment.getTenantId());
int result = commentMapper.insert(comment);
logger.info("Comment added with ID: " + comment.getCommentId() + ", result: " + result);
return result;
}
@Override
public int deleteById(long commentId){
logger.info("Deleting comment by ID: " + commentId);
int result = commentMapper.deleteById(commentId);
logger.info("Comment deletion result: " + result);
return result;
}
@Override
public int update(Comment comment){
logger.info("Updating comment with ID: " + comment.getCommentId());
int result = commentMapper.update(comment);
logger.info("Comment update result: " + result);
return result;
}
@Override
public List<Comment> findByHouseId(long houseId){
logger.info("Finding comments by house ID: " + houseId);
List<Comment> comments = commentMapper.findByHouseId(houseId);
logger.debug("Found " + comments.size() + " comments for house ID: " + houseId);
return comments;
}
@Override
public List<Comment> findByTenantId(long tenantId){
logger.info("Finding comments by tenant ID: " + tenantId);
List<Comment> comments = commentMapper.findByTenantId(tenantId);
logger.debug("Found " + comments.size() + " comments for tenant ID: " + tenantId);
return comments;
}
@Override
public Comment findByHouseIdAndTenantId(long houseId, long tenantId){
logger.info("Finding comment by house ID: " + houseId + " and tenant ID: " + tenantId);
Comment comment = commentMapper.findByHouseIdAndTenantId(houseId, tenantId);
logger.debug("Found comment: " + comment);
return comment;
}
@Override
public List<Comment> findAll(){
logger.info("Retrieving all comments");
List<Comment> comments = commentMapper.findAll();
logger.debug("Found " + comments.size() + " comments");
return comments;
}
}
|
2301_79970562/student_union_backend
|
src/main/java/org/example/main/service/impl/CommentServiceImpl.java
|
Java
|
unknown
| 2,702
|
package org.example.main.service.impl;
import org.apache.log4j.Logger;
import org.example.main.dao.FavoriteMapper;
import org.example.main.entity.Favorite;
import org.example.main.service.FavoriteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class FavoriteServiceImpl implements FavoriteService {
private static final Logger logger = Logger.getLogger(FavoriteServiceImpl.class);
@Autowired
private FavoriteMapper favoriteMapper;
@Override
public int add(Favorite favorite) {
logger.info("Adding favorite for tenant ID: " + favorite.getTenantId() + " and house ID: " + favorite.getHouseId());
int result = favoriteMapper.insert(favorite);
logger.info("Favorite added with ID: " + favorite.getFavoriteId() + ", result: " + result);
return result;
}
@Override
public int removeById(long favoriteId) {
logger.info("Removing favorite by ID: " + favoriteId);
int result = favoriteMapper.deleteById(favoriteId);
logger.info("Favorite removal result: " + result);
return result;
}
@Override
public int removeByTenantAndHouse(long tenantId, long houseId) {
logger.info("Removing favorite by tenant ID: " + tenantId + " and house ID: " + houseId);
int result = favoriteMapper.deleteByTenantAndHouse(tenantId, houseId);
logger.info("Favorite removal result: " + result);
return result;
}
@Override
public List<Favorite> getByTenantId(long tenantId) {
logger.info("Getting favorites by tenant ID: " + tenantId);
List<Favorite> favorites = favoriteMapper.findByTenantId(tenantId);
logger.debug("Found " + favorites.size() + " favorites for tenant ID: " + tenantId);
return favorites;
}
@Override
public List<Favorite> getByHouseId(long houseId){
logger.info("Getting favorites by house ID: " + houseId);
List<Favorite> favorites = favoriteMapper.findByHouseId(houseId);
logger.debug("Found " + favorites.size() + " favorites for house ID: " + houseId);
return favorites;
}
@Override
public Favorite getByTenantAndHouse(long tenantId, long houseId) {
logger.info("Getting favorite by tenant ID: " + tenantId + " and house ID: " + houseId);
Favorite favorite = favoriteMapper.findByTenantAndHouse(tenantId, houseId);
logger.debug("Found favorite: " + favorite);
return favorite;
}
@Override
public List<Favorite> findAll(){
logger.info("Retrieving all favorites");
List<Favorite> favorites = favoriteMapper.findAll();
logger.debug("Found " + favorites.size() + " favorites");
return favorites;
}
}
|
2301_79970562/student_union_backend
|
src/main/java/org/example/main/service/impl/FavoriteServiceImpl.java
|
Java
|
unknown
| 2,827
|
package org.example.main.service.impl;
import org.apache.log4j.Logger;
import org.example.main.dao.HouseMapper;
import org.example.main.entity.House;
import org.example.main.service.HouseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class HouseServiceImpl implements HouseService {
private static final Logger logger = Logger.getLogger(HouseServiceImpl.class);
@Autowired
private HouseMapper houseMapper;
@Override
public int add(House house) {
logger.info("Adding new house with title: " + house.getTitle());
int result = houseMapper.insert(house);
logger.info("House added with ID: " + house.getHouseId() + ", result: " + result);
return result;
}
@Override
public int update(House house) {
logger.info("Updating house with ID: " + house.getHouseId());
int result = houseMapper.update(house);
logger.info("House update result: " + result);
return result;
}
@Override
public int deleteById(long houseId) {
logger.info("Deleting house by ID: " + houseId);
int result = houseMapper.deleteById(houseId);
logger.info("House deletion result: " + result);
return result;
}
@Override
public House findById(long houseId) {
logger.info("Finding house by ID: " + houseId);
House house = houseMapper.findById(houseId);
logger.debug("Found house: " + house);
return house;
}
@Override
public List<House> findAll() {
logger.info("Retrieving all houses");
List<House> houses = houseMapper.findAll();
logger.debug("Found " + houses.size() + " houses");
return houses;
}
@Override
public List<House> findByLandlordId(long landlordId) {
logger.info("Finding houses by landlord ID: " + landlordId);
List<House> houses = houseMapper.findByLandlordId(landlordId);
logger.debug("Found " + houses.size() + " houses for landlord ID: " + landlordId);
return houses;
}
@Override
public List<House> findByStatus(String status) {
logger.info("Finding houses by status: " + status);
List<House> houses = houseMapper.findByStatus(status);
logger.debug("Found " + houses.size() + " houses with status: " + status);
return houses;
}
@Override
public List<House> findByTitle(String title) {
logger.info("Finding houses by title: " + title);
List<House> houses = houseMapper.findByTitle(title);
logger.debug("Found " + houses.size() + " houses with title: " + title);
return houses;
}
@Override
public List<House> findByArea(String area) {
logger.info("Finding houses by area: " + area);
List<House> houses = houseMapper.findByArea(area);
logger.debug("Found " + houses.size() + " houses in area: " + area);
return houses;
}
@Override
public int updateStatus(long houseId, String status) {
logger.info("Updating status for house ID: " + houseId + " to status: " + status);
int result = houseMapper.updateStatus(houseId, status);
logger.info("Status update result: " + result);
return result;
}
}
|
2301_79970562/student_union_backend
|
src/main/java/org/example/main/service/impl/HouseServiceImpl.java
|
Java
|
unknown
| 3,343
|
package org.example.main.service.impl;
import org.apache.log4j.Logger;
import org.example.main.dao.LandlordMapper;
import org.example.main.entity.Landlord;
import org.example.main.service.LandlordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class LandlordServiceImpl implements LandlordService {
private static final Logger logger = Logger.getLogger(LandlordServiceImpl.class);
@Autowired
private LandlordMapper landlordMapper;
@Override
public int add(Landlord landlord) {
logger.info("Adding new landlord with username: " + landlord.getUsername());
int result = landlordMapper.insert(landlord);
logger.info("Landlord added with ID: " + landlord.getLandlordId() + ", result: " + result);
return result;
}
@Override
public int deleteById(long landlordId) {
logger.info("Deleting landlord by ID: " + landlordId);
int result = landlordMapper.deleteById(landlordId);
logger.info("Landlord deletion result: " + result);
return result;
}
@Override
public int updateById(Landlord landlord) {
logger.info("Updating landlord with ID: " + landlord.getLandlordId());
int result = landlordMapper.updateById(landlord);
logger.info("Landlord update result: " + result);
return result;
}
@Override
public Landlord findById(long landlordId) {
logger.info("Finding landlord by ID: " + landlordId);
Landlord landlord = landlordMapper.findById(landlordId);
logger.debug("Found landlord: " + landlord);
return landlord;
}
@Override
public Landlord findByUsername(String username) {
logger.info("Finding landlord by username: " + username);
Landlord landlord = landlordMapper.findByUsername(username);
logger.debug("Found landlord: " + landlord);
return landlord;
}
@Override
public List<Landlord> findAll() {
logger.info("Retrieving all landlords");
List<Landlord> landlords = landlordMapper.findAll();
logger.debug("Found " + landlords.size() + " landlords");
return landlords;
}
}
|
2301_79970562/student_union_backend
|
src/main/java/org/example/main/service/impl/LandlordServiceImpl.java
|
Java
|
unknown
| 2,264
|
package org.example.main.service.impl;
import org.apache.log4j.Logger;
import org.example.main.dao.RecordMapper;
import org.example.main.entity.Record;
import org.example.main.service.RecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class RecordServiceImpl implements RecordService {
private static final Logger logger = Logger.getLogger(RecordServiceImpl.class);
@Autowired
private RecordMapper recordMapper;
@Override
public int add(Record record){
logger.info("Adding new record for house ID: " + record.getHouseId() + " and tenant ID: " + record.getTenantId());
int result = recordMapper.insert(record);
logger.info("Record added with ID: " + record.getRecordId() + ", result: " + result);
return result;
}
@Override
public int deleteById(long recordId){
logger.info("Deleting record by ID: " + recordId);
int result = recordMapper.deleteById(recordId);
logger.info("Record deletion result: " + result);
return result;
}
@Override
public List<Record> findAll(){
logger.info("Retrieving all records");
List<Record> records = recordMapper.findAll();
logger.debug("Found " + records.size() + " records");
return records;
}
@Override
public List<Record> findByHouseId(long houseId){
logger.info("Finding records by house ID: " + houseId);
List<Record> records = recordMapper.findByHouseId(houseId);
logger.debug("Found " + records.size() + " records for house ID: " + houseId);
return records;
}
@Override
public List<Record> findByTenantId(long tenantId){
logger.info("Finding records by tenant ID: " + tenantId);
List<Record> records = recordMapper.findByTenantId(tenantId);
logger.debug("Found " + records.size() + " records for tenant ID: " + tenantId);
return records;
}
}
|
2301_79970562/student_union_backend
|
src/main/java/org/example/main/service/impl/RecordServiceImpl.java
|
Java
|
unknown
| 2,035
|
package org.example.main.service.impl;
import org.apache.log4j.Logger;
import org.example.main.dao.RentalApplicationMapper;
import org.example.main.entity.RentalApplication;
import org.example.main.service.RentalApplicationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class RentalApplicationServiceImpl implements RentalApplicationService {
private static final Logger logger = Logger.getLogger(RentalApplicationServiceImpl.class);
@Autowired
private RentalApplicationMapper rentalApplicationMapper;
@Override
public int apply(RentalApplication application) {
logger.info("Applying for rental - tenant ID: " + application.getTenantId() + ", house ID: " + application.getHouseId());
int result = rentalApplicationMapper.insert(application);
logger.info("Rental application added with ID: " + application.getApplicationId() + ", result: " + result);
return result;
}
@Override
public int updateStatus(long applicationId, String status) {
logger.info("Updating rental application status - application ID: " + applicationId + ", status: " + status);
int result = rentalApplicationMapper.updateStatus(applicationId, status);
logger.info("Rental application status update result: " + result);
return result;
}
@Override
public RentalApplication findById(long applicationId) {
logger.info("Finding rental application by ID: " + applicationId);
RentalApplication application = rentalApplicationMapper.findById(applicationId);
logger.debug("Found rental application: " + application);
return application;
}
@Override
public List<RentalApplication> findByTenantId(long tenantId) {
logger.info("Finding rental applications by tenant ID: " + tenantId);
List<RentalApplication> applications = rentalApplicationMapper.findByTenantId(tenantId);
logger.debug("Found " + applications.size() + " rental applications for tenant ID: " + tenantId);
return applications;
}
@Override
public List<RentalApplication> findByHouseId(long houseId) {
logger.info("Finding rental applications by house ID: " + houseId);
List<RentalApplication> applications = rentalApplicationMapper.findByHouseId(houseId);
logger.debug("Found " + applications.size() + " rental applications for house ID: " + houseId);
return applications;
}
@Override
public RentalApplication findByTenantIdAndHouseIdAndType(long tenantId, long houseId, String type){
logger.info("Finding rental application by tenant ID: " + tenantId + ", house ID: " + houseId + ", type: " + type);
RentalApplication application = rentalApplicationMapper.findByTenantIdAndHouseIdAndType(tenantId, houseId, type);
logger.debug("Found rental application: " + application);
return application;
}
@Override
public List<RentalApplication> findAll() {
logger.info("Retrieving all rental applications");
List<RentalApplication> applications = rentalApplicationMapper.findAll();
logger.debug("Found " + applications.size() + " rental applications");
return applications;
}
@Override
public int delete(long applicationId){
logger.info("Deleting rental application by ID: " + applicationId);
int result = rentalApplicationMapper.deleteById(applicationId);
logger.info("Rental application deletion result: " + result);
return result;
}
}
|
2301_79970562/student_union_backend
|
src/main/java/org/example/main/service/impl/RentalApplicationServiceImpl.java
|
Java
|
unknown
| 3,640
|
package org.example.main.service.impl;
import org.apache.log4j.Logger;
import org.example.main.dao.TenantMapper;
import org.example.main.entity.Tenant;
import org.example.main.service.TenantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class TenantServiceImpl implements TenantService {
private static final Logger logger = Logger.getLogger(TenantServiceImpl.class);
@Autowired
private TenantMapper tenantMapper;
@Override
public int add(Tenant tenant) {
logger.info("Adding new tenant with username: " + tenant.getUsername());
int result = tenantMapper.insert(tenant);
logger.info("Tenant added with ID: " + tenant.getTenantId() + ", result: " + result);
return result;
}
@Override
public int deleteById(long tenantId) {
logger.info("Deleting tenant by ID: " + tenantId);
int result = tenantMapper.deleteById(tenantId);
logger.info("Tenant deletion result: " + result);
return result;
}
@Override
public int updateById(Tenant tenant) {
logger.info("Updating tenant with ID: " + tenant.getTenantId());
int result = tenantMapper.updateById(tenant);
logger.info("Tenant update result: " + result);
return result;
}
@Override
public Tenant findById(long tenantId) {
logger.info("Finding tenant by ID: " + tenantId);
Tenant tenant = tenantMapper.findById(tenantId);
logger.debug("Found tenant: " + tenant);
return tenant;
}
@Override
public Tenant findByUsername(String username) {
logger.info("Finding tenant by username: " + username);
Tenant tenant = tenantMapper.findByUsername(username);
logger.debug("Found tenant: " + tenant);
return tenant;
}
@Override
public List<Tenant> findAll() {
logger.info("Retrieving all tenants");
List<Tenant> tenants = tenantMapper.findAll();
logger.debug("Found " + tenants.size() + " tenants");
return tenants;
}
}
|
2301_79970562/student_union_backend
|
src/main/java/org/example/main/service/impl/TenantServiceImpl.java
|
Java
|
unknown
| 2,148
|
package org.example.main.utils;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@Data
@Schema(description = "通用响应结果", name = "CommonResult")
public class CommonResult<T> { // 添加泛型参数<T>
@Schema(name = "code", description = "响应状态码")
private int code; //响应状态码
@Schema(name = "msg", description = "响应信息")
private String msg; //响应信息
@Schema(name = "data", description = "响应数据")
private T data; // 使用泛型类型T
public CommonResult() {}
public CommonResult(Integer code, String msg, T data) { // 使用泛型类型T
this.code = code;
this.msg = msg;
this.data = data;
}
// 成功响应的静态方法
public static <T> CommonResult<T> success(T data) {
return new CommonResult<>(200, "success", data);
}
// 失败响应的静态方法
public static <T> CommonResult<T> failed(String message) {
return new CommonResult<>(500, message, null);
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() { // 返回泛型类型T
return data;
}
public void setData(T data) { // 使用泛型类型T
this.data = data;
}
}
|
2301_79970562/student_union_backend
|
src/main/java/org/example/main/utils/CommonResult.java
|
Java
|
unknown
| 1,461
|
package org.example.main.utils;
import org.apache.log4j.Logger;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import java.security.*;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.Map;
/**
* @ Description 国密公私钥对工具类
*/
public class KeyUtils {
public static final String PUBLIC_KEY = "publicKey";
public static final String PRIVATE_KEY = "privateKey";
private static SecureRandom SECURE_RANDOM ;
private static final Logger logger = Logger.getLogger(KeyUtils.class);
static {
try {
SECURE_RANDOM = SecureRandom.getInstanceStrong();
} catch (NoSuchAlgorithmException e) {
logger.warn("无法获取强随机数生成器,使用默认实现", e);
SECURE_RANDOM = new SecureRandom();
}
}
/**
* 生成国密公私钥对
*/
public static Map<String, String> generateSmKey() throws Exception {
KeyPairGenerator keyPairGenerator;
ECGenParameterSpec sm2Spec = new ECGenParameterSpec("sm2p256v1");
keyPairGenerator = KeyPairGenerator.getInstance("EC", new BouncyCastleProvider());
keyPairGenerator.initialize(sm2Spec);
keyPairGenerator.initialize(sm2Spec, SECURE_RANDOM);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();
String publicKeyStr = new String(Base64.getEncoder().encode(publicKey.getEncoded()));
String privateKeyStr = new String(Base64.getEncoder().encode(privateKey.getEncoded()));
return Map.of(PUBLIC_KEY, publicKeyStr, PRIVATE_KEY, privateKeyStr);
}
/**
* 将Base64转码的公钥串转化为公钥对象
*/
public static PublicKey createPublicKey(String publicKey) {
PublicKey publickey = null;
try {
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKey));
KeyFactory keyFactory = KeyFactory.getInstance("EC", new BouncyCastleProvider());
publickey = keyFactory.generatePublic(publicKeySpec);
} catch (Exception e) {
logger.error("将Base64转码的公钥串,转化为公钥对象异常:{}", e);
}
return publickey;
}
/**
* 将Base64转码的私钥串转化为私钥对象
*/
public static PrivateKey createPrivateKey(String privateKey) {
PrivateKey publickey = null;
try {
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey));
KeyFactory keyFactory = KeyFactory.getInstance("EC", new BouncyCastleProvider());
publickey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
} catch (Exception e) {
logger.error("将Base64转码的私钥串,转化为私钥对象异常:{}", e);
}
return publickey;
}
}
|
2301_79970562/student_union_backend
|
src/main/java/org/example/main/utils/KeyUtils.java
|
Java
|
unknown
| 3,094
|
package org.example.main.utils;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.util.Arrays;
@Component
@Aspect
@Order(1)
public class LogAspect {
private static final Logger logger = Logger.getLogger(LogAspect.class);
// 定义切点,匹配service包下的所有类的所有方法
@Pointcut("execution(public * org.example.main.service.*.*(..))")
public void serviceLog() {}
// 定义切点,匹配service.impl包下的所有类的所有方法
@Pointcut("execution(public * org.example.main.service.impl.*.*(..))")
public void serviceImplLog() {}
@Before("serviceImplLog()")
public void doBefore(JoinPoint joinPoint){
logger.info("Method Start: " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
logger.debug("Arguments: " + Arrays.toString(joinPoint.getArgs()));
}
@After("serviceImplLog()")
public void doAfter(JoinPoint joinPoint){
logger.info("Method End: " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
}
@AfterReturning(returning ="result",pointcut = "serviceImplLog()")
public void doAfterReturning(Object result){
logger.debug("Method Return: " + result);
}
@AfterThrowing(pointcut = "serviceImplLog()", throwing = "exception")
public void doAfterThrowing(JoinPoint joinPoint, Exception exception){
logger.error("Exception in method: " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName(), exception);
}
}
|
2301_79970562/student_union_backend
|
src/main/java/org/example/main/utils/LogAspect.java
|
Java
|
unknown
| 1,746
|
package org.example.main.utils;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@ComponentScan(value = "org.example.main.utils")
@Configuration
@EnableAspectJAutoProxy
public class LogConfig {
}
|
2301_79970562/student_union_backend
|
src/main/java/org/example/main/utils/LogConfig.java
|
Java
|
unknown
| 340
|
package org.example.main.utils;
import org.apache.log4j.Logger;
import org.bouncycastle.asn1.gm.GMObjectIdentifiers;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.engines.SM2Engine;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.crypto.params.ParametersWithRandom;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.jce.spec.ECParameterSpec;
import java.security.*;
/**
* @ Description SM2实现工具类
*/
public class Sm2Util {
private static final Logger logger = Logger.getLogger(Sm2Util.class);
/* 这行代码是在Java中用于向安全系统添加Bouncy Castle安全提供器的。
Bouncy Castle是一个流行的开源加密库,它提供了许多密码学算法和安全协议的实现。
通过调用Security.addProvider并传入BouncyCastleProvider对象,你可以注册Bouncy Castle提供的安全服务和算法到Java的安全框架中。
这样一来,你就可以在你的应用程序中使用Bouncy Castle所提供的加密算法、密钥生成和管理等功能。*/
static {
Security.addProvider(new BouncyCastleProvider());
}
// 使用更强的随机数生成器
private static SecureRandom SECURE_RANDOM;
static {
try {
// 尝试使用更强的随机数生成器
SECURE_RANDOM = SecureRandom.getInstanceStrong();
} catch (NoSuchAlgorithmException e) {
logger.warn("无法获取强随机数生成器,使用默认实现", e);
SECURE_RANDOM = new SecureRandom();
}
}
/**
* 根据publicKey对原始数据data,使用SM2加密
*/
public static byte[] encrypt(byte[] data, PublicKey publicKey) {
ECPublicKeyParameters localECPublicKeyParameters = getEcPublicKeyParameters(publicKey);
SM2Engine localSM2Engine = new SM2Engine();
localSM2Engine.init(true, new ParametersWithRandom(localECPublicKeyParameters, SECURE_RANDOM));
byte[] arrayOfByte2;
try {
arrayOfByte2 = localSM2Engine.processBlock(data, 0, data.length);
return arrayOfByte2;
} catch (InvalidCipherTextException e) {
logger.error("SM2加密失败:{}", e);
return null;
}
}
private static ECPublicKeyParameters getEcPublicKeyParameters(PublicKey publicKey) {
ECPublicKeyParameters localECPublicKeyParameters = null;
if (publicKey instanceof BCECPublicKey localECPublicKey) {
ECParameterSpec localECParameterSpec = localECPublicKey.getParameters();
ECDomainParameters localECDomainParameters = new ECDomainParameters(localECParameterSpec.getCurve(),
localECParameterSpec.getG(), localECParameterSpec.getN());
localECPublicKeyParameters = new ECPublicKeyParameters(localECPublicKey.getQ(), localECDomainParameters);
}
return localECPublicKeyParameters;
}
/**
* 根据privateKey对加密数据encode data,使用SM2解密
*/
public static byte[] decrypt(byte[] encodeData, PrivateKey privateKey) {
SM2Engine localSM2Engine = new SM2Engine();
BCECPrivateKey sm2PriK = (BCECPrivateKey) privateKey;
ECParameterSpec localECParameterSpec = sm2PriK.getParameters();
ECDomainParameters localECDomainParameters = new ECDomainParameters(localECParameterSpec.getCurve(),
localECParameterSpec.getG(), localECParameterSpec.getN());
ECPrivateKeyParameters localECPrivateKeyParameters = new ECPrivateKeyParameters(sm2PriK.getD(),
localECDomainParameters);
localSM2Engine.init(false, localECPrivateKeyParameters);
try {
return localSM2Engine.processBlock(encodeData, 0, encodeData.length);
} catch (InvalidCipherTextException e) {
logger.error("SM2解密失败:{}", e);
return null;
}
}
/**
* 私钥签名
*/
public static byte[] signByPrivateKey(byte[] data, PrivateKey privateKey) throws Exception {
Signature sig = Signature.getInstance(GMObjectIdentifiers.sm2sign_with_sm3.toString(), BouncyCastleProvider.PROVIDER_NAME);
sig.initSign(privateKey);
sig.update(data);
return sig.sign();
}
/**
* 公钥验签
*/
public static boolean verifyByPublicKey(byte[] data, PublicKey publicKey, byte[] signature) throws Exception {
Signature sig = Signature.getInstance(GMObjectIdentifiers.sm2sign_with_sm3.toString(), BouncyCastleProvider.PROVIDER_NAME);
sig.initVerify(publicKey);
sig.update(data);
return sig.verify(signature);
}
}
|
2301_79970562/student_union_backend
|
src/main/java/org/example/main/utils/Sm2Util.java
|
Java
|
unknown
| 5,011
|
package org.example.main.utils;
import io.swagger.v3.oas.models.ExternalDocumentation;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration //配置类
public class SwaggerConfig {
@Bean
public OpenAPI openAPI() {
return new OpenAPI()
.info(new Info()
.title("租房系统API文档") //文档的标题
.description("实训项目后台接口说明文档") //文档的描述
.version("v1.0.0") //文档的版本
.contact(new Contact()
.name("李诺贤"))) //文档的作者
.externalDocs(new ExternalDocumentation() //文档的扩展信息
.url("http://localhost:8089/main/doc.html"));//文档的访问地址
}
}
|
2301_79970562/student_union_backend
|
src/main/java/org/example/main/utils/SwaggerConfig.java
|
Java
|
unknown
| 1,021
|
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>中南民族大学校庆头像生成器</title>
<link rel="stylesheet" href="styles/style.css">
</head>
<body>
<div class="back">
<img class="background-image" src="images/scuec4.jpg" alt="背景图">
<div class="background-overlay"></div>
</div>
<div class="container">
<div class="header">
<h1 class="title">百变头像框</h1>
</div>
<div class="preview-section">
<div class="preview-title">预览效果</div>
<div class="canvas-container">
<canvas id="avatarCanvas" class="avatar-canvas"></canvas>
</div>
<div class="action-buttons">
<button class="btn save-btn" id="saveAvatar">
<span class="btn-text">保存头像</span>
</button>
<button class="btn reset-btn" id="resetAvatar">
<span class="btn-text">重置</span>
</button>
</div>
<div class="upload-section">
<input type="file" id="avatarUpload" accept="image/*" style="display: none;">
<button class="upload-btn" id="chooseAvatar">
<span class="upload-text">上传头像</span>
</button>
</div>
</div>
<div class="avatar_choose">
<div class="default-avatars">
<div class="section-header">
<span class="section-title">选择默认头像</span>
</div>
<div class="avatar-scroll">
<div class="avatar-list">
<div class="avatar-item" v-for="avatar in defaultAvatars" :key="avatar.id" @click="selectDefaultAvatar(avatar.id)">
<img class="avatar-img" :src="avatar.url" :alt="avatar.name" @error="handleImageError">
</div>
</div>
</div>
</div>
<div class="frame-section">
<div class="section-header">
<span class="section-title">选择头像框</span>
</div>
<div class="frame-scroll">
<div class="frame-list">
<div class="frame-item" :class="{ active: frame.id === selectedFrame }"
v-for="frame in frames" :key="frame.id"
@click="selectFrame(frame.id)">
<div class="frame-preview" v-if="frame.id === 'none'">
<span class="frame-text">无框</span>
</div>
<img class="frame-preview" v-else :src="frame.preview" :alt="frame.name" @error="handleFrameError">
</div>
</div>
</div>
</div>
</div>
<div class="tips">
<p class="tip-text">提示:选择头像后,点击喜欢的头像框预览效果,满意后保存头像。</p>
<p class="tip-text">注意:所有处理都在本地完成,不会上传您的头像到服务器。</p>
</div>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script src="scripts/script.js"></script>
</body>
</html>
|
2301_79614195/avatar3
|
index.html
|
HTML
|
unknown
| 3,606
|
const { createApp } = Vue;
createApp({
data() {
return {
avatarUrl: '',
frames: (() => {
const frames = [
{ id: 'none', preview: '', name: '无框', selected: true }
];
for (let i = 1; i <=26; i++) {
frames.push({
id: `frame${i}`,
preview: `images/plan${i}.png`,
name: `头像框 ${i}`,
selected: false
});
}
return frames;
})(),
defaultAvatars: [
{
id: 'avatar1',
url: 'images/user.jpeg',
name: '默认头像1',
fallback: 'https://via.placeholder.com/200x200/3498db/ffffff?text=头像1'
}
// {
// id: 'avatar2',
// url: 'images/user2.webp',
// name: '默认头像2',
// fallback: 'https://via.placeholder.com/200x200/e74c3c/ffffff?text=头像2'
// },
// {
// id: 'avatar3',
// url: 'images/user3.webp',
// name: '默认头像3',
// fallback: 'https://via.placeholder.com/200x200/2ecc71/ffffff?text=头像3'
// }
],
selectedFrame: 'none',
tempFilePaths: {},
canvas: null,
ctx: null,
isLoading: false
}
},
mounted() {
this.initCanvas();
this.drawDefaultAvatar();
this.bindEvents();
this.preloadImages();
},
methods: {
initCanvas() {
this.canvas = document.getElementById('avatarCanvas');
if (!this.canvas) {
console.error('Canvas元素未找到');
return;
}
this.ctx = this.canvas.getContext('2d');
this.canvas.width = 400; // 提高分辨率
this.canvas.height = 400;
},
bindEvents() {
// 绑定上传按钮事件
const chooseBtn = document.getElementById('chooseAvatar');
const uploadInput = document.getElementById('avatarUpload');
if (chooseBtn && uploadInput) {
chooseBtn.addEventListener('click', () => {
uploadInput.click();
});
uploadInput.addEventListener('change', this.handleFileUpload);
}
// 绑定保存和重置按钮事件
const saveBtn = document.getElementById('saveAvatar');
const resetBtn = document.getElementById('resetAvatar');
if (saveBtn) saveBtn.addEventListener('click', this.saveAvatar);
if (resetBtn) resetBtn.addEventListener('click', this.resetAvatar);
},
async preloadImages() {
// 预加载头像框图片
for (let frame of this.frames) {
if (frame.id !== 'none') {
await this.preloadImage(frame.preview);
}
}
},
preloadImage(src) {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = reject;
img.src = src;
});
},
handleFileUpload(event) {
const file = event.target.files[0];
if (!file) return;
// 检查文件类型
if (!file.type.startsWith('image/')) {
alert('请选择图片文件!');
return;
}
// 检查文件大小(限制为5MB)
if (file.size > 5 * 1024 * 1024) {
alert('图片大小不能超过5MB!');
return;
}
this.isLoading = true;
const reader = new FileReader();
reader.onload = (e) => {
this.avatarUrl = e.target.result;
this.drawAvatarWithFrame();
this.isLoading = false;
};
reader.onerror = () => {
alert('图片读取失败,请重试!');
this.isLoading = false;
};
reader.readAsDataURL(file);
// 重置文件输入,允许选择同一文件
event.target.value = '';
},
selectDefaultAvatar(avatarId) {
const selectedAvatar = this.defaultAvatars.find(avatar => avatar.id === avatarId);
if (selectedAvatar) {
this.isLoading = true;
// 首先尝试加载本地图片
const img = new Image();
img.onload = () => {
this.avatarUrl = selectedAvatar.url;
this.drawAvatarWithFrame();
this.isLoading = false;
};
img.onerror = () => {
// 如果本地图片加载失败,使用备用网络图片
console.warn(`本地图片 ${selectedAvatar.url} 加载失败,使用备用图片`);
this.avatarUrl = selectedAvatar.fallback;
this.drawAvatarWithFrame();
this.isLoading = false;
};
img.src = selectedAvatar.url;
}
},
handleImageError(event) {
const img = event.target;
const avatarItem = img.closest('.avatar-item');
if (avatarItem) {
const avatarId = Array.from(avatarItem.parentNode.children).indexOf(avatarItem);
const fallbackUrl = this.defaultAvatars[avatarId]?.fallback;
if (fallbackUrl) {
img.src = fallbackUrl;
}
}
},
handleFrameError(event) {
console.warn('头像框图片加载失败:', event.target.src);
},
selectFrame(frameId) {
this.selectedFrame = frameId;
if (this.avatarUrl) {
this.drawAvatarWithFrame();
}
},
drawDefaultAvatar() {
if (!this.ctx) return;
const ctx = this.ctx;
const width = this.canvas.width;
const height = this.canvas.height;
ctx.clearRect(0, 0, width, height);
// 绘制渐变背景
const gradient = ctx.createLinearGradient(0, 0, width, height);
gradient.addColorStop(0, '#34495e');
gradient.addColorStop(1, '#2c3e50');
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, width, height);
// 绘制边框
ctx.strokeStyle = '#ecf0f1';
ctx.lineWidth = 4;
ctx.strokeRect(2, 2, width - 4, height - 4);
// 绘制默认头像图标
ctx.fillStyle = '#ecf0f1';
ctx.font = 'bold 40px Arial';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText('👤', width/2, height/2 - 10);
// 绘制提示文字
ctx.font = '16px Arial';
ctx.fillStyle = '#bdc3c7';
ctx.fillText('头像', width/2, height/2 + 30);
},
drawAvatarWithFrame() {
if (!this.avatarUrl) {
this.drawDefaultAvatar();
return;
}
if (!this.ctx) return;
const ctx = this.ctx;
const canvasWidth = this.canvas.width;
const canvasHeight = this.canvas.height;
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
const avatarImg = new Image();
avatarImg.crossOrigin = 'anonymous';
avatarImg.onload = () => {
// 绘制头像(居中裁剪)
const avatarSize = Math.min(avatarImg.width, avatarImg.height);
const sx = (avatarImg.width - avatarSize) / 2;
const sy = (avatarImg.height - avatarSize) / 2;
ctx.drawImage(avatarImg, sx, sy, avatarSize, avatarSize, 0, 0, canvasWidth, canvasHeight);
// 绘制头像框
if (this.selectedFrame !== 'none') {
const selectedFrame = this.frames.find(frame => frame.id === this.selectedFrame);
if (selectedFrame && selectedFrame.preview) {
const frameImg = new Image();
frameImg.crossOrigin = 'anonymous';
frameImg.onload = () => {
ctx.drawImage(frameImg, 0, 0, canvasWidth, canvasHeight);
};
frameImg.onerror = () => {
console.error('头像框图片加载失败:', selectedFrame.preview);
};
frameImg.src = selectedFrame.preview;
}
}
};
avatarImg.onerror = () => {
console.error('头像图片加载失败');
this.drawDefaultAvatar();
};
avatarImg.src = this.avatarUrl;
},
saveAvatar() {
if (!this.avatarUrl) {
alert('请先选择头像!');
return;
}
if (this.isLoading) {
alert('图片正在加载中,请稍候...');
return;
}
try {
// 创建高分辨率副本用于下载
const tempCanvas = document.createElement('canvas');
const tempCtx = tempCanvas.getContext('2d');
tempCanvas.width = 800;
tempCanvas.height = 800;
// 绘制头像到临时canvas
const avatarImg = new Image();
avatarImg.onload = () => {
// 绘制头像
const avatarSize = Math.min(avatarImg.width, avatarImg.height);
const sx = (avatarImg.width - avatarSize) / 2;
const sy = (avatarImg.height - avatarSize) / 2;
tempCtx.drawImage(avatarImg, sx, sy, avatarSize, avatarSize, 0, 0, 800, 800);
// 绘制头像框
if (this.selectedFrame !== 'none') {
const selectedFrame = this.frames.find(frame => frame.id === this.selectedFrame);
if (selectedFrame && selectedFrame.preview) {
const frameImg = new Image();
frameImg.onload = () => {
tempCtx.drawImage(frameImg, 0, 0, 800, 800);
// 保存图片
tempCanvas.toBlob((blob) => {
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `中南民族大学校庆头像_${new Date().getTime()}.png`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
alert('头像保存成功!');
}, 'image/png', 0.95);
};
frameImg.src = selectedFrame.preview;
}
} else {
// 没有头像框的情况
tempCanvas.toBlob((blob) => {
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `中南民族大学校庆头像_${new Date().getTime()}.png`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
alert('头像保存成功!');
}, 'image/png', 0.95);
}
};
avatarImg.src = this.avatarUrl;
} catch (error) {
console.error('保存头像失败:', error);
alert('保存失败,请重试!');
}
},
resetAvatar() {
this.avatarUrl = '';
this.selectedFrame = 'none';
this.drawDefaultAvatar();
// 重置文件输入
const uploadInput = document.getElementById('avatarUpload');
if (uploadInput) {
uploadInput.value = '';
}
}
}
}).mount('.container');
|
2301_79614195/avatar3
|
scripts/script.js
|
JavaScript
|
unknown
| 14,347
|
/* 全局样式 */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Microsoft YaHei', Arial, sans-serif;
background: #f5f5f5;
}
.container {
min-height: 100vh;
color: #fff;
padding: 15px;
display: flex;
flex-direction: column;
position: relative;
z-index: 1;
max-width: 1200px;
margin: 0 auto;
width: 100%;
}
.background-image {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: -2;
object-fit: cover;
}
.background-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.4);
z-index: -1;
}
.header {
text-align: center;
margin-bottom: 20px;
padding: 0 10px;
}
.title {
display: block;
font-size: clamp(18px, 5vw, 22px);
font-weight: bold;
margin-bottom: 5px;
text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
color: #fff;
}
.preview-section {
display: flex;
flex-direction: column;
align-items: center;
margin-bottom: 25px;
padding: 0 10px;
}
.preview-title {
font-size: clamp(16px, 4vw, 18px);
margin-bottom: 15px;
font-weight: bold;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}
/* 修改后的容器样式 - 固定比例但响应式缩放 */
.canvas-container {
/* 使用视口单位实现响应式缩放 */
width: min(60vw, 50vh, 320px);
height: min(60vw, 50vh, 320px);
/* 保持正方形 */
aspect-ratio: 1/1;
overflow: hidden;
box-shadow: 0 8px 25px rgba(0, 0, 0, 0.4);
margin-bottom: 20px;
background: #2c3e50;
border-radius: 10px;
border: 3px solid #fff;
/* 添加过渡效果 */
transition: all 0.3s ease;
}
.avatar-canvas {
width: 100%;
height: 100%;
display: block;
}
.action-buttons {
display: flex;
gap: 15px;
width: 100%;
max-width: min(90vw, 300px);
justify-content: center;
}
.btn {
padding: clamp(10px, 2.5vw, 12px) clamp(20px, 5vw, 25px);
border-radius: 30px;
border: none;
font-size: clamp(14px, 3.5vw, 16px);
font-weight: bold;
transition: all 0.3s ease;
min-width: clamp(80px, 20vw, 100px);
cursor: pointer;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
}
.save-btn {
background: linear-gradient(135deg, #75809C, #5a647a);
color: white;
}
.save-btn:hover {
background: linear-gradient(135deg, #5a647a, #4a546b);
transform: translateY(-2px);
box-shadow: 0 6px 20px rgba(0, 0, 0, 0.3);
}
.reset-btn {
background: linear-gradient(135deg, #976666, #795252);
color: white;
}
.reset-btn:hover {
background: linear-gradient(135deg, #795252, #6a4545);
transform: translateY(-2px);
box-shadow: 0 6px 20px rgba(0, 0, 0, 0.3);
}
.upload-section {
margin-top: 30px;
margin-bottom: 20px;
padding: 0 10px;
width: 100%;
max-width: min(90vw, 400px);
}
.upload-btn {
width: 100%;
background: linear-gradient(135deg, #4d6085, #3d4d6a);
color: white;
padding: clamp(12px, 3vw, 15px);
border-radius: 30px;
box-shadow: 0 4px 15px rgba(52, 152, 219, 0.3);
border: none;
cursor: pointer;
font-size: clamp(14px, 3.5vw, 16px);
font-weight: bold;
transition: all 0.3s ease;
}
.upload-btn:hover {
background: linear-gradient(135deg, #3d4d6a, #2d3a50);
transform: translateY(-2px);
}
/* 关键修改:让选择区域左对齐 */
.avatar_choose {
margin-bottom: 20px;
display: flex;
flex-direction: column;
align-items: flex-start; /* 改为左对齐 */
padding: 0 10px;
width: 100%;
max-width: min(95vw, 800px); /* 限制最大宽度 */
}
.section-header {
margin-bottom: 12px;
padding: 0;
width: 100%;
}
.section-title {
display: block;
font-size: clamp(14px, 3.5vw, 16px);
font-weight: bold;
color: white;
text-align: left;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}
.avatar-scroll, .frame-scroll {
width: 100%;
height: clamp(70px, 15vh, 90px);
white-space: nowrap;
overflow-x: auto;
overflow-y: hidden;
padding: 0;
}
.avatar-list, .frame-list {
display: flex;
flex-direction: row;
height: 100%;
align-items: center;
gap: 12px;
}
.avatar-item {
width: clamp(60px, 12vw, 70px);
height: clamp(60px, 12vw, 70px);
flex-shrink: 0;
border: 2px solid transparent;
border-radius: 8px;
overflow: hidden;
transition: all 0.3s ease;
background: #34495e;
cursor: pointer;
box-shadow: 0 3px 10px rgba(0, 0, 0, 0.2);
}
.avatar-item:hover {
transform: scale(0.95);
border-color: #3498db;
}
.avatar-img {
width: 100%;
height: 100%;
object-fit: cover;
}
.default-avatars, .frame-section {
margin-bottom: 25px;
width: 100%;
}
.frame-item {
width: clamp(70px, 14vw, 80px);
height: clamp(70px, 14vw, 80px);
flex-shrink: 0;
border: 2px solid transparent;
border-radius: 8px;
overflow: hidden;
transition: all 0.3s ease;
background: #34495e;
cursor: pointer;
box-shadow: 0 3px 10px rgba(0, 0, 0, 0.2);
}
.frame-item.active {
border-color: #e74c3c;
transform: scale(1.05);
box-shadow: 0 5px 15px rgba(231, 76, 60, 0.4);
}
.frame-item:hover:not(.active) {
transform: scale(0.95);
border-color: #3498db;
}
.frame-preview {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
object-fit: cover;
}
.frame-text {
color: white;
font-size: clamp(12px, 2.5vw, 14px);
font-weight: bold;
}
.tips {
padding: 15px;
background: rgba(255, 255, 255, 0.15);
border-radius: 10px;
margin: 0 10px 20px;
backdrop-filter: blur(10px);
max-width: min(95vw, 800px);
align-self: flex-start; /* 提示区域也左对齐 */
}
.tip-text {
display: block;
font-size: clamp(12px, 3vw, 14px);
line-height: 1.6;
margin-bottom: 8px;
opacity: 0.9;
}
.avatar-list {
min-width: min-content;
}
.frame-list {
display: grid;
grid-template-rows: 1fr 1fr;
grid-template-columns: repeat(auto-fill, clamp(70px, 14vw, 80px));
grid-auto-flow: column;
gap: 12px;
width: max-content;
height: 100%;
}
/* 隐藏滚动条 */
.avatar-scroll::-webkit-scrollbar,
.frame-scroll::-webkit-scrollbar {
display: none;
}
.avatar-scroll,
.frame-scroll {
-ms-overflow-style: none;
scrollbar-width: none;
}
.frame-scroll {
width: 100%;
height: clamp(140px, 30vh, 172px);
white-space: nowrap;
overflow-x: auto;
overflow-y: hidden;
padding: 0;
}
/* 增强的响应式设计 */
@media (max-width: 768px) {
.container {
padding: 10px;
}
.canvas-container {
width: min(70vw, 60vh, 280px);
height: min(70vw, 60vh, 280px);
}
.avatar_choose {
max-width: 100%;
}
}
@media (max-width: 480px) {
.container {
padding: 8px;
}
.canvas-container {
width: min(80vw, 70vh, 240px);
height: min(80vw, 70vh, 240px);
border-width: 2px;
}
.action-buttons {
gap: 10px;
}
.avatar_choose {
padding: 0 5px;
}
}
@media (max-width: 360px) {
.canvas-container {
width: min(85vw, 75vh, 200px);
height: min(85vw, 75vh, 200px);
}
}
/* 超大屏幕适配 */
@media (min-width: 1200px) {
.container {
max-width: 1200px;
}
.canvas-container {
width: 320px;
height: 320px;
}
.avatar_choose {
max-width: 1000px;
}
}
/* 添加平滑的缩放动画 */
@media (prefers-reduced-motion: no-preference) {
.canvas-container {
will-change: transform;
}
}
|
2301_79614195/avatar3
|
style/style.css
|
CSS
|
unknown
| 8,147
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="style.css" rel="stylesheet" type="text/css" />
<title>InsCode</title>
</head>
<body>
<div class="container">
<img src="src/assets/logo.svg" alt="InsCode">
<div>欢迎来到 InsCode</div>
</div>
<script src="script.js"></script>
</body>
</html>
|
2301_80121773/HTML-CSS-JS
|
index.html
|
HTML
|
unknown
| 491
|
{ pkgs }: {
deps = [
pkgs.nodejs-18_x
pkgs.yarn
];
}
|
2301_80121773/HTML-CSS-JS
|
inscode.nix
|
Nix
|
unknown
| 67
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>跳动的心</title>
</head>
<body>
<div class="heart">
</div>
</body>
<style>
* {
margin: 0;
padding: 0;
}
html,
body {
height: 100%;
width: 100%;
background-color: pink
}
body {
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
}
.heart {
width: 200px;
height: 200px;
background: red;
position: relative;
transform: rotate(45deg);
box-shadow: 0 0 30px red;
animation: heartbit 1s alternate infinite;
}
.heart::before {
content: '';
width: 200px;
height: 100px;
background: red;
position: absolute;
left: 0;
top: -99px;
border-radius: 100px 100px 0 0;
box-shadow: 0 0 30px red;
}
.heart::after {
content: '';
width: 100px;
height: 200px;
background: red;
position: absolute;
left: -99px;
top: 0;
border-radius: 100px 0 0 100px;
box-shadow: 0 0 30px red;
}
@keyframes heartbit {
0% {
transform: rotate(45deg) scale(0.6);
}
100% {
transform: rotate(45deg) scale(1.4);
}
}
</style>
</html>
|
2301_80121773/HTML-CSS-JS
|
src/assets/跳动的心.html
|
HTML
|
unknown
| 1,480
|
html{
height: 100%;
width: 100%;
}
.container {
text-align: center;
padding: 64px;
}
|
2301_80121773/HTML-CSS-JS
|
style.css
|
CSS
|
unknown
| 93
|
import os
import sys
import subprocess
from flask import Flask, render_template, send_file
import tkinter as tk
from threading import Thread
app = Flask(__name__)
# 处理打包后的路径问题
def resource_path(relative_path):
if hasattr(sys, '_MEIPASS'):
return os.path.join(sys._MEIPASS, relative_path)
return os.path.join(os.path.abspath("."), relative_path)
# 关键路径定义
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
FFMPEG_PATH = resource_path(os.path.join('bin', 'ffmpeg.exe')) # 动态路径
STREAM_DIR = os.path.join(BASE_DIR, 'static', 'stream')
os.makedirs(STREAM_DIR, exist_ok=True)
def start_capture(ffmpeg_cmd):
return subprocess.Popen(ffmpeg_cmd, shell=True)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/stream/<filename>')
def stream(filename):
return send_file(os.path.join(STREAM_DIR, filename))
# 图形化操作界面
# 前置参数
ffmpeg_cmd = [
FFMPEG_PATH,
'-f', 'gdigrab',
'-framerate', '30',
'-i', 'desktop',
'-vf', 'scale=1920:-2',
'-c:v', 'libx264',
'-preset', 'veryfast',
'-tune', 'zerolatency',
'-f', 'hls',
'-hls_time', '2',
'-hls_list_size', '5',
'-hls_flags', 'delete_segments',
os.path.join(STREAM_DIR, 'stream.m3u8')
]
ipport = 54250
ipv4 = False
# 创建主窗口
root = tk.Tk()
root.title('ipv6投屏')
root.geometry('400x300')
root.resizable(False, False)
# ipv4勾选框
ipv4_var = tk.BooleanVar()
ipv4_var.set(False)
ipv4_button = tk.Checkbutton(root, text="使用IPv4而非ipv6", variable=ipv4_var)
ipv4_button.pack()
ipv4_button.place(x=50, y=150)
# 端口号输入框
ipport_var = tk.StringVar()
ipport_var.set('54250')
ipportlab = tk.Entry(root, textvariable=ipport_var, relief="sunken")
ipportlab.pack()
ipportlab.place(x=50, y=50, width=200, height=20)
# 帧率输入框
zhenlv_var = tk.StringVar()
zhenlv_var.set('30')
zhenlvlab = tk.Entry(root, textvariable=zhenlv_var, relief="sunken")
zhenlvlab.pack()
zhenlvlab.place(x=50, y=100, width=200, height=20)
# ipv6地址显示框
def get_ipv6_address1():
try:
# 调用ipconfig命令并获取其输出
result = subprocess.run(['ipconfig'], capture_output=True, text=True, check=True)
# 解析输出
lines = result.stdout.split('\n')
ipv6_addresses = []
for line in lines:
if '临时 IPv6 地址' in line:
# 提取IPv6地址,通常位于冒号分隔的字符串中
address = line.split(': ')[-1].strip()
if address: # 去除可能的空字符串
ipv6_addresses.append(address)
# 如果没有找到IPv6地址,返回空列表
if not ipv6_addresses:
return None
# 通常情况下,我们只关心第一个IPv6地址(取决于实际需求)
return ipv6_addresses[0]
except subprocess.CalledProcessError as e:
print(f"Error occurred: {e}")
return '未找到ipv6地址'
ipv6 = get_ipv6_address1()
ipv6_var = tk.StringVar()
ipv6lab = tk.Entry(root, textvariable=ipv6_var, state="readonly")
ipv6lab.pack()
ipv6lab.place(x=50, y=200, width=200, height=20)
# 增加一些描述
lab1 = tk.Label(root,text='端口号',relief='flat')
lab1.pack()
lab1.place(x=280, y=50)
lab2 = tk.Label(root,text='帧率',relief='flat')
lab2.pack()
lab2.place(x=280, y=100)
lab3 = tk.Label(root,text='ipv6地址',relief='flat')
lab3.pack()
lab3.place(x=280, y=200)
# 主按钮
def main():
# 处理各实时变量
ipv4 = ipv4_var.get()
ip = '::'
if ipv4:
ip = '0.0.0.0'
ipport = int(ipport_var.get())
ffmpeg_cmd[4] = zhenlv_var.get()
if not ipv4:
ipv6_var.set('http://[' + ipv6 + ']:' + ipport_var.get())
# 启动主程序
ffmpeg_process = start_capture(ffmpeg_cmd)
def run_flask():
try:
app.run(host=ip, port=ipport, debug=False)
finally:
ffmpeg_process.terminate()
flask_thread = Thread(target=run_flask)
flask_thread.daemon = True # 设置为守护线程,确保主程序退出时子线程也会退出
flask_thread.start()
# 定义按钮
buttonmain = tk.Button(root, text='开始投屏', command=main)
buttonmain.pack()
buttonmain.place(x=150, y=250, width=100, height=40)
# 运行应用程序
root.mainloop()
|
2301_80130186/ipv6
|
ipv6投屏0.2.0.py
|
Python
|
mit
| 4,526
|
from flask import Flask, Response, request, jsonify, render_template, redirect, url_for, session, send_from_directory, stream_with_context, send_file
from flask_sslify import SSLify
from PIL import ImageGrab
from PIL import Image, ImageDraw
import io
import time
import threading
from threading import Thread
import tkinter as tk
from tkinter import filedialog
from tkinter import messagebox
import pystray
import subprocess
import pyautogui
import os
import pyperclip
app = Flask(__name__)
app.secret_key = os.urandom(24).hex()
sslify = SSLify(app)
# 全局变量
try:
with open('config.txt','r') as config_file:
config_text = config_file.read()
exec(config_text)
except BaseException:
fps = 30
compression_quality = 10
ipv4 = False
enable_simulation = False
users = ['', '']
ipport = 54250
enable_video = True
enable_file_download = True
enable_file_upload = False
UPLOAD_FOLDER = ''
with open('config.txt','w') as config_file:
config_file.write('''
fps = 30
compression_quality = 10
ipv4 = False
enable_simulation = False
users = ['', '']
ipport = 54250
enable_video = True
enable_file_download = True
enable_file_upload = False
UPLOAD_FOLDER = ''
'''.strip())
# 不可配置全局变量
ip = ''
screen_width, screen_height = pyautogui.size()
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
sleeptime = 0.033
def gen():
while True:
img_byte_arr = io.BytesIO()
screen = ImageGrab.grab()
screen.save(img_byte_arr, format='JPEG', quality=compression_quality)
frame = img_byte_arr.getvalue()
screen.close()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
time.sleep(sleeptime)
# 视频帧
@app.route('/video_feed')
def video_feed():
return Response(gen(), mimetype='multipart/x-mixed-replace; boundary=frame')
# 普通点击映射(依然保留,可供单击使用)
@app.route('/click', methods=['POST'])
def handle_click():
if not enable_simulation or ('username' not in session):
return jsonify(status='disabled')
data = request.json
x_percent = data['x'] # 百分比坐标
y_percent = data['y']
button = data.get('button', 'left')
# 将百分比转换为实际坐标
actual_x = int((x_percent / 100) * screen_width)
actual_y = int((y_percent / 100) * screen_height)
if button == 'right':
pyautogui.rightClick(actual_x, actual_y)
else:
pyautogui.click(actual_x, actual_y)
return jsonify(status='success')
# 新增拖动映射,服务端只根据拖动起始和结束坐标模拟一次快速直线拖动
@app.route('/drag', methods=['POST'])
def handle_drag():
if not enable_simulation or ('username' not in session):
return jsonify(status='disabled')
data = request.json
start_x_percent = data['start_x']
start_y_percent = data['start_y']
end_x_percent = data['end_x']
end_y_percent = data['end_y']
button = data.get('button', 'left')
# 将百分比转换为实际坐标
actual_start_x = int((start_x_percent / 100) * screen_width)
actual_start_y = int((start_y_percent / 100) * screen_height)
actual_end_x = int((end_x_percent / 100) * screen_width)
actual_end_y = int((end_y_percent / 100) * screen_height)
# 移动到起始位置
pyautogui.moveTo(actual_start_x, actual_start_y)
# 按下鼠标按钮
pyautogui.mouseDown(button=button)
# 保持按下状态 0.3 秒
time.sleep(0.3)
# 快速直线拖动到目标位置(可根据需要调整拖动时长)
pyautogui.moveTo(actual_end_x, actual_end_y, duration=0.05)
# 释放鼠标按钮
pyautogui.mouseUp(button=button)
return jsonify(status='success')
# 按键映射
@app.route('/keypress', methods=['POST'])
def handle_keypress():
if not enable_simulation or ('username' not in session):
return jsonify(status='disabled')
data = request.json
key = data['key']
pyautogui.press(key)
return jsonify(status='success')
# 共享屏幕主页面(客户端页面)
index_html = '''
<html>
<head>
<style>
body, html {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
display: flex;
}
#click-area {
flex-grow: 1;
border: 1px solid black;
position: relative;
overflow: hidden;
}
img {
width: 100%;
height: 100%;
object-fit: contain;
}
#floating-button {
position: absolute;
top: 20px;
left: 20px;
width: 50px;
height: 50px;
background-color: #39c5bb;
color: white;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
user-select: none;
}
#floating-window {
position: absolute;
top: 80px;
left: 20px;
width: 200px;
background-color: white;
border: 1px solid #ccc;
border-radius: 5px;
padding: 10px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
display: none;
}
#floating-window label {
display: block;
margin-bottom: 10px;
}
.window-button {
width: 100%;
padding: 8px;
margin-bottom: 10px;
background-color: #39c5bb;
color: white;
border: none;
border-radius: 3px;
cursor: pointer;
text-align: center;
transition: background-color 0.3s;
}
.window-button:hover {
background-color: #2da49c;
}
</style>
</head>
<body>
<div id="click-area">
<img src="/video_feed" />
</div>
<div id="floating-button">⚙️</div>
<div id="floating-window">
<label>
<input type="checkbox" id="toggle-right-click"> 左键变右键
</label>
<button class="window-button" id="file-manager-btn">文件管理</button>
</div>
<script>
const clickArea = document.getElementById('click-area');
const floatingButton = document.getElementById('floating-button');
const floatingWindow = document.getElementById('floating-window');
const toggleRightClick = document.getElementById('toggle-right-click');
const fileManagerBtn = document.getElementById('file-manager-btn');
// 文件管理按钮点击事件 - 跳转到当前URL的/file路径
fileManagerBtn.addEventListener('click', () => {
// 获取当前URL并添加/file路径
const currentUrl = window.location.href;
// 处理可能已存在的路径
const baseUrl = currentUrl.split('/').slice(0, 3).join('/');
const fileUrl = `${baseUrl}/file`;
window.location.href = fileUrl;
});
let isDragging = false;
let offsetX, offsetY;
// 屏蔽右键默认菜单
clickArea.addEventListener('contextmenu', (event) => {
event.preventDefault();
});
// 悬浮按钮点击事件
floatingButton.addEventListener('click', () => {
floatingWindow.style.display = floatingWindow.style.display === 'none' ? 'block' : 'none';
});
// 悬浮按钮拖动事件
floatingButton.addEventListener('mousedown', (event) => {
isDragging = true;
offsetX = event.clientX - floatingButton.offsetLeft;
offsetY = event.clientY - floatingButton.offsetTop;
});
document.addEventListener('mousemove', (event) => {
if (isDragging) {
floatingButton.style.left = `${event.clientX - offsetX}px`;
floatingButton.style.top = `${event.clientY - offsetY}px`;
floatingWindow.style.left = `${event.clientX - offsetX}px`;
floatingWindow.style.top = `${event.clientY - offsetY + 60}px`;
}
});
document.addEventListener('mouseup', () => {
isDragging = false;
});
// 根据图片的渲染尺寸计算有效点击区域,并返回百分比坐标
function getImageCoordinates(event) {
const img = document.querySelector('img');
const rect = img.getBoundingClientRect();
const naturalWidth = img.naturalWidth;
const naturalHeight = img.naturalHeight;
const displayWidth = rect.width;
const displayHeight = rect.height;
const imgAspectRatio = naturalWidth / naturalHeight;
const displayAspectRatio = displayWidth / displayHeight;
let renderWidth, renderHeight, offsetX, offsetY;
if (displayAspectRatio > imgAspectRatio) {
renderHeight = displayHeight;
renderWidth = renderHeight * imgAspectRatio;
offsetX = (displayWidth - renderWidth) / 2;
offsetY = 0;
} else {
renderWidth = displayWidth;
renderHeight = renderWidth / imgAspectRatio;
offsetX = 0;
offsetY = (displayHeight - renderHeight) / 2;
}
const x = event.clientX - rect.left - offsetX;
const y = event.clientY - rect.top - offsetY;
if (x < 0 || x > renderWidth || y < 0 || y > renderHeight) {
return null;
}
const xPercent = (x / renderWidth) * 100;
const yPercent = (y / renderHeight) * 100;
return { xPercent, yPercent };
}
// 用于记录鼠标按下时的起始坐标
let dragStart = null;
// 鼠标按下时记录起始坐标(不立即发送点击指令)
clickArea.addEventListener('mousedown', (event) => {
event.preventDefault();
const coords = getImageCoordinates(event);
if (!coords) return;
const button = toggleRightClick.checked ? 'right' : (event.button === 2 ? 'right' : 'left');
dragStart = { x: coords.xPercent, y: coords.yPercent, button };
});
// 鼠标松开时,获取结束坐标,并发送一次拖动请求到服务端
clickArea.addEventListener('mouseup', (event) => {
event.preventDefault();
if (!dragStart) return;
const coords = getImageCoordinates(event);
if (!coords) {
dragStart = null;
return;
}
fetch('/drag', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
start_x: dragStart.x,
start_y: dragStart.y,
end_x: coords.xPercent,
end_y: coords.yPercent,
button: dragStart.button
}),
});
dragStart = null;
});
// 键盘事件映射
document.addEventListener('keydown', (event) => {
const key = event.key;
fetch('/keypress', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ key }),
});
});
// 窗口大小变化时重置图片尺寸
window.addEventListener('resize', () => {
const img = document.querySelector('img');
if (img) {
img.style.width = '100%';
img.style.height = '100%';
}
});
</script>
</body>
</html>
'''
@app.route('/')
def index():
if 'username' in session:
if enable_video == True:
return index_html
else:
return redirect(url_for('fileindex'))
else:
return redirect('/login')
# 登录页面
@app.route('/login', methods=['GET', 'POST'])
def login():
error_message = ""
if request.method == 'POST':
username = request.form['账户名']
password = request.form['密码']
if username == users[0] and password == users[1]:
session['username'] = username
return redirect(url_for('index'))
else:
error_message = "用户名或密码错误,请重新输入"
return f'''
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>用户登录</title>
<style>
/* 基础样式重置 */
* {{
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
}}
/* 页面布局 */
body {{
background-color: #f0f2f5;
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
padding: 20px;
}}
/* 登录容器 */
.login-container {{
width: 100%;
max-width: 400px;
}}
/* 登录卡片 */
.login-card {{
background-color: white;
border-radius: 10px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
padding: 30px;
transition: box-shadow 0.3s ease;
}}
.login-card:hover {{
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.15);
}}
/* 标题样式 */
.login-title {{
text-align: center;
font-size: 24px;
font-weight: 600;
color: #1a1a1a;
margin-bottom: 25px;
}}
/* 错误提示样式 */
.error-message {{
background-color: #fff0f0;
border: 1px solid #ffcccc;
color: #d8000c;
padding: 12px 15px;
border-radius: 6px;
margin-bottom: 20px;
font-size: 14px;
display: { 'block' if error_message else 'none' };
}}
/* 表单样式 */
.login-form {{
display: flex;
flex-direction: column;
gap: 20px;
}}
/* 表单组样式 */
.form-group {{
display: flex;
flex-direction: column;
gap: 8px;
}}
/* 标签样式 */
.form-label {{
font-size: 14px;
font-weight: 500;
color: #4b4b4b;
}}
/* 输入框样式 */
.form-input {{
width: 100%;
padding: 12px 15px;
border: 1px solid #ddd;
border-radius: 6px;
font-size: 16px;
transition: all 0.2s ease;
}}
.form-input:focus {{
border-color: #165DFF;
box-shadow: 0 0 0 3px rgba(22, 93, 255, 0.1);
outline: none;
}}
/* 按钮样式 */
.submit-btn {{
width: 100%;
padding: 12px;
background-color: #165DFF;
color: white;
border: none;
border-radius: 6px;
font-size: 16px;
font-weight: 500;
cursor: pointer;
transition: all 0.3s ease;
}}
.submit-btn:hover {{
background-color: #0E4BDB;
box-shadow: 0 4px 8px rgba(22, 93, 255, 0.2);
}}
</style>
</head>
<body>
<div class="login-container">
<div class="login-card">
<h2 class="login-title">登录</h2>
<!-- 错误提示区域 -->
<div class="error-message">{error_message}</div>
<form method="post" class="login-form">
<div class="form-group">
<label class="form-label">账户名:</label>
<input type="text" name="账户名" class="form-input" placeholder="请输入账户名">
</div>
<div class="form-group">
<label class="form-label">密码:</label>
<input type="password" name="密码" class="form-input" placeholder="请输入密码">
</div>
<input type="submit" value="登录" class="submit-btn">
</form>
</div>
</div>
</body>
</html>
'''
# 文件传输页面
HTML = '''
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>文件管理器</title>
<style>
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
line-height: 1.6;
color: #333;
max-width: 800px;
margin: 0 auto;
padding: 30px 20px;
background-color: #f8f9fa;
}
/* 返回按钮样式 */
.back-button {
position: absolute;
top: 30px;
left: 20px;
background-color: #95a5a6;
color: white;
border: none;
padding: 8px 16px;
border-radius: 4px;
cursor: pointer;
font-size: 0.9rem;
text-decoration: none;
transition: background-color 0.3s ease;
}
.back-button:hover {
background-color: #7f8c8d;
}
h1 {
color: #2c3e50;
margin-bottom: 30px;
padding-bottom: 10px;
border-bottom: 2px solid #3498db;
text-align: center;
}
h2 {
color: #34495e;
margin: 25px 0 15px;
font-size: 1.4rem;
}
.upload-form {
background-color: white;
padding: 25px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
margin-bottom: 30px;
transition: box-shadow 0.3s ease;
}
.upload-form:hover {
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.15);
}
input[type="file"] {
display: block;
margin-bottom: 15px;
padding: 8px;
border: 1px solid #ddd;
border-radius: 4px;
width: 100%;
cursor: pointer;
}
input[type="submit"] {
background-color: #3498db;
color: white;
border: none;
padding: 10px 20px;
border-radius: 4px;
cursor: pointer;
font-size: 1rem;
transition: background-color 0.3s ease;
}
input[type="submit"]:hover {
background-color: #2980b9;
}
ul {
list-style-type: none;
background-color: white;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
overflow: hidden;
}
.file-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 12px 20px;
border-bottom: 1px solid #f1f1f1;
}
.file-link {
color: #2980b9;
text-decoration: none;
transition: all 0.3s ease;
}
.file-link:hover {
color: #1a5276;
text-decoration: underline;
}
.delete-btn {
margin-left: 10px;
background-color: #e74c3c;
color: white;
border: none;
padding: 3px 8px;
border-radius: 3px;
cursor: pointer;
font-size: 0.8rem;
transition: background-color 0.3s ease;
}
.delete-btn:hover {
background-color: #c0392b;
}
/* 进度条样式 */
.progress-container {
width: 100%;
height: 8px;
background-color: #e0e0e0;
border-radius: 4px;
margin-top: 15px;
overflow: hidden;
display: none; /* 默认隐藏 */
}
.progress-bar {
height: 100%;
background-color: #3498db;
width: 0%;
transition: width 0.3s ease;
}
/* 状态提示样式 */
.status-message {
margin-top: 15px;
padding: 10px;
border-radius: 4px;
display: none;
}
.success {
background-color: #dff0d8;
color: #3c763d;
border: 1px solid #d6e9c6;
}
.error {
background-color: #f2dede;
color: #a94442;
border: 1px solid #ebccd1;
}
/* 空列表提示 */
.empty-message {
padding: 12px 20px;
color: #7f8c8d;
text-align: center;
}
</style>
</head>
<body>
<!-- 添加返回按钮 -->
<a href="../" class="back-button">返回</a>
<h1>文件管理器</h1>
<h2>上传文件</h2>
<form id="uploadForm" class="upload-form" method="POST" enctype="multipart/form-data">
<input type="file" name="file" id="fileInput" multiple>
<input type="submit" value="上传">
<div class="progress-container">
<div class="progress-bar" id="progressBar"></div>
</div>
<div class="status-message" id="statusMessage"></div>
</form>
<h2>文件列表</h2>
<ul id="fileList">
<!-- 文件列表将通过JavaScript动态生成 -->
<li class="empty-message">加载文件列表中...</li>
</ul>
<script>
// 页面加载时就获取文件列表
document.addEventListener('DOMContentLoaded', function() {
refreshFileList();
});
// 文件上传进度
const uploadForm = document.getElementById('uploadForm');
const progressBar = document.getElementById('progressBar');
const progressContainer = document.querySelector('.progress-container');
const statusMessage = document.getElementById('statusMessage');
const fileList = document.getElementById('fileList');
uploadForm.addEventListener('submit', function(e) {
e.preventDefault();
const formData = new FormData(this);
const xhr = new XMLHttpRequest();
xhr.open('POST', '/upload', true);
xhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
const percent = (e.loaded / e.total) * 100;
progressBar.style.width = percent + '%';
progressContainer.style.display = 'block';
}
});
xhr.addEventListener('load', function() {
progressContainer.style.display = 'none';
if (xhr.status === 200) {
showStatus('文件上传成功!', 'success');
refreshFileList();
} else {
showStatus('上传失败: ' + xhr.responseText, 'error');
}
// 重置表单
uploadForm.reset();
progressBar.style.width = '0%';
});
xhr.addEventListener('error', function() {
progressContainer.style.display = 'none';
showStatus('上传失败,请重试', 'error');
});
xhr.send(formData);
});
// 刷新文件列表 - 完全通过JavaScript生成,避免模板引擎问题
function refreshFileList() {
fetch('/file')
.then(response => {
// 假设服务器返回JSON格式的文件列表
if (response.headers.get('content-type').includes('application/json')) {
return response.json();
}
// 如果返回的是HTML,则尝试从中提取文件信息
return response.text().then(html => {
// 这里是一个后备方案,根据实际返回的HTML结构调整
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
const items = doc.querySelectorAll('.file-item');
return Array.from(items).map(item => {
const link = item.querySelector('.file-link');
return link ? link.textContent : '';
}).filter(name => name);
});
})
.then(files => {
// 清空现有列表
fileList.innerHTML = '';
// 检查文件列表是否为空
if (!files || files.length === 0) {
const emptyItem = document.createElement('li');
emptyItem.className = 'empty-message';
emptyItem.textContent = '暂无文件';
fileList.appendChild(emptyItem);
return;
}
// 动态生成文件列表项
files.forEach(file => {
const listItem = document.createElement('li');
listItem.className = 'file-item';
const fileLink = document.createElement('a');
fileLink.href = '/download/' + encodeURIComponent(file);
fileLink.className = 'file-link';
fileLink.textContent = file;
const deleteBtn = document.createElement('button');
deleteBtn.className = 'delete-btn';
deleteBtn.textContent = '删除';
deleteBtn.setAttribute('data-filename', file);
listItem.appendChild(fileLink);
listItem.appendChild(deleteBtn);
fileList.appendChild(listItem);
});
})
.catch(error => {
console.error('刷新文件列表失败:', error);
fileList.innerHTML = '<li class="empty-message">加载文件失败</li>';
});
}
// 显示状态消息
function showStatus(message, type) {
statusMessage.textContent = message;
statusMessage.className = 'status-message ' + type;
statusMessage.style.display = 'block';
// 3秒后隐藏消息
setTimeout(() => {
statusMessage.style.display = 'none';
}, 3000);
}
// 为删除按钮添加事件监听
fileList.addEventListener('click', function(e) {
if (e.target.classList.contains('delete-btn')) {
const filename = e.target.getAttribute('data-filename');
if (confirm(`确定要删除文件 "${filename}" 吗?`)) {
deleteFile(filename);
}
}
});
// 删除文件函数
function deleteFile(filename) {
fetch(`/delete/${encodeURIComponent(filename)}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
}
})
.then(response => response.json())
.then(data => {
if (data.status === 'success') {
showStatus('文件删除成功!', 'success');
refreshFileList();
} else {
showStatus('删除失败: ' + data.message, 'error');
}
})
.catch(error => {
console.error('删除文件失败:', error);
showStatus('删除失败,请重试', 'error');
});
}
</script>
</body>
</html>
'''
@app.route('/file')
def fileindex():
if 'username' in session:
if (not (enable_file_download or enable_file_upload)) or ('username' not in session) or (UPLOAD_FOLDER == ''):
return "服务端未允许文件传输", 403
# 获取上传文件夹中的文件列表
files = os.listdir(app.config['UPLOAD_FOLDER'])
# 生成带删除按钮的文件列表项
file_list = ''.join([f'<li class="file-item"><a href="/download/{file}" class="file-link">{file}</a><button class="delete-btn" data-filename="{file}">删除</button></li>' for file in files])
rendered_html = HTML.replace('{% for file in files %}', '').replace('{% endfor %}', '').replace('{{ file }}', '')
return rendered_html.replace('</ul>', f'{file_list}</ul>')
else:
return redirect('/login')
@app.route('/upload', methods=['POST'])
def upload_file():
if (not enable_file_upload) or ('username' not in session) or (UPLOAD_FOLDER == ''):
return jsonify({"status": "error", "message": "服务端未允许文件传输"}), 403
if 'file' not in request.files:
return jsonify({"status": "error", "message": "未找到文件"}), 400
file = request.files['file']
if file.filename == '':
return jsonify({"status": "error", "message": "文件名不能为空"}), 400
if file:
try:
file_path = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
with open(file_path,'wb') as f:
while chunk := file.stream.read(1024*1024):
f.write(chunk)
return jsonify({"status": "success", "message": "文件上传成功"})
except Exception as e:
return jsonify({"status": "error", "message": f"上传失败: {str(e)}"}), 500
@app.route('/download/<filename>')
def download_file(filename):
if (not enable_file_download) or ('username' not in session) or (UPLOAD_FOLDER == ''):
return "服务端未允许文件传输", 403
file_path = os.path.join(UPLOAD_FOLDER, filename)
return send_file(
file_path,
mimetype='application/octet-stream',
as_attachment=True,
download_name=filename # 指定下载时的文件名
)
@app.route('/delete/<filename>', methods=['POST'])
def delete_file(filename):
# 权限检查与文件上传保持一致
if (not enable_file_upload) or ('username' not in session) or (UPLOAD_FOLDER == ''):
return jsonify({"status": "error", "message": "没有删除权限"}), 403
try:
# 构建文件路径
file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
# 安全检查:确保文件在上传目录内
if not os.path.abspath(file_path).startswith(os.path.abspath(app.config['UPLOAD_FOLDER'])):
return jsonify({"status": "error", "message": "无效的文件路径"}), 400
# 检查文件是否存在
if not os.path.exists(file_path) or not os.path.isfile(file_path):
return jsonify({"status": "error", "message": "文件不存在"}), 404
# 删除文件
os.remove(file_path)
return jsonify({"status": "success", "message": "文件已删除"})
except Exception as e:
return jsonify({"status": "error", "message": f"删除失败: {str(e)}"}), 500
# 添加文件列表JSON接口,用于前端异步刷新
@app.route('/file-list')
def file_list():
if (not (enable_file_download or enable_file_upload)) or ('username' not in session) or (UPLOAD_FOLDER == ''):
return jsonify([]), 403
# 获取上传文件夹中的文件列表
try:
files = os.listdir(app.config['UPLOAD_FOLDER'])
# 过滤掉目录,只保留文件
files = [f for f in files if os.path.isfile(os.path.join(app.config['UPLOAD_FOLDER'], f))]
return jsonify(files)
except Exception as e:
return jsonify([]), 500
# 图形化设计(Tkinter 界面)
# 系统托盘
class TrayApp:
def __init__(self, root):
self.root = root
self.root.title("系统托盘包装")
self.root.geometry("400x300")
# 跟踪托盘图标状态
self.tray_icon = None
self.tray_running = False
# 设置窗口关闭事件
self.root.protocol("WM_DELETE_WINDOW", self.on_close)
def create_tray_icon(self):
"""创建系统托盘图标和菜单"""
# 确保之前的图标已被正确清理
if self.tray_icon:
try:
self.tray_icon.stop()
except:
pass
# 创建一个简单的图标(使用PIL绘制)
image = Image.new('RGB', (64, 64), color='white')
draw = ImageDraw.Draw(image)
draw.text((10, 25), "", fill='black')
# 创建菜单
menu = pystray.Menu(
pystray.MenuItem("恢复", self.restore_window),
pystray.MenuItem("退出", self.quit_app)
)
# 创建新的托盘图标
self.tray_icon = pystray.Icon("TkApp", image, "Tkinter应用", menu)
return self.tray_icon
def on_close(self):
"""处理窗口关闭事件"""
# 询问用户是隐藏到托盘还是关闭
result = messagebox.askyesnocancel("关闭选项", "是否隐藏到系统托盘")
if result is None: # 取消操作
return
elif result: # 隐藏到系统托盘
self.root.withdraw() # 隐藏窗口
# 确保在新线程中启动托盘图标
if not self.tray_running:
def run_tray():
icon = self.create_tray_icon()
self.tray_running = True
icon.run()
self.tray_running = False
threading.Thread(target=run_tray, daemon=True).start()
else: # 完全关闭
self.quit_app()
def restore_window(self, icon=None, item=None):
"""从系统托盘恢复窗口"""
# 停止托盘图标
if icon:
icon.stop()
# 更新状态
self.tray_running = False
# 显示窗口
self.root.deiconify()
self.root.lift() # 把窗口提到最前面
def quit_app(self, icon=None, item=None):
"""完全退出应用程序"""
# 停止托盘图标
if icon:
icon.stop()
# 更新状态
self.tray_running = False
# 销毁窗口
self.root.destroy()
# 创建主窗口
root = tk.Tk()
rapp = TrayApp(root)
root.title('隧影')
root.geometry('800x350')
root.resizable(False, False)
# 左侧设置
ipport_var = tk.StringVar()
ipport_var.set(str(ipport))
ipportlab = tk.Entry(root, textvariable=ipport_var, relief="sunken")
ipportlab.pack()
ipportlab.place(x=50, y=50, width=200, height=20)
lab1 = tk.Label(root, text='投屏端口号', relief='flat')
lab1.pack()
lab1.place(x=280, y=50)
zhenlv_var = tk.StringVar()
zhenlv_var.set(str(fps))
zhenlvlab = tk.Entry(root, textvariable=zhenlv_var, relief="sunken")
zhenlvlab.pack()
zhenlvlab.place(x=50, y=100, width=200, height=20)
lab2 = tk.Label(root, text='帧率(-1为不限制)', relief='flat')
lab2.pack()
lab2.place(x=280, y=100)
quality_var = tk.StringVar()
quality_var.set(str(compression_quality))
qualitylab = tk.Entry(root, textvariable=quality_var, relief="sunken")
qualitylab.pack()
qualitylab.place(x=50, y=150, width=200, height=20)
lab3 = tk.Label(root, text='压缩质量(1-100)', relief='flat')
lab3.pack()
lab3.place(x=280, y=150)
ipv4_var = tk.BooleanVar()
ipv4_var.set(ipv4)
ipv4_button = tk.Checkbutton(root, text="使用IPv4而非ipv6", variable=ipv4_var)
ipv4_button.pack()
ipv4_button.place(x=50, y=200)
# ipv6地址显示框及获取函数
def get_ipv6_address():
try:
result = subprocess.run(['ipconfig'], capture_output=True, text=True, check=True)
lines = result.stdout.split('\n')
ipv6_addresses = []
for line in lines:
if '临时 IPv6 地址' in line:
address = line.split(': ')[-1].strip()
if address:
ipv6_addresses.append(address)
if not ipv6_addresses:
return '::1'
return ipv6_addresses[0]
except subprocess.CalledProcessError as e:
print(f"Error occurred: {e}")
return '::1'
def get_ipv4_address():
try:
result = subprocess.run(['ipconfig'], capture_output=True, text=True, check=True)
lines = result.stdout.split('\n')
ipv4_addresses = []
for line in lines:
if ('192.' in line) and ('IPv4 地址' in line):
address = line.split(': ')[-1].strip()
if address:
ipv4_addresses.append(address)
if not ipv4_addresses:
return '127.0.0.1'
return ipv4_addresses[0]
except subprocess.CalledProcessError as e:
print(f"Error occurred: {e}")
return '127.0.0.1'
ipv6_var = tk.StringVar()
ipv6lab = tk.Entry(root, textvariable=ipv6_var, state="readonly")
ipv6lab.pack()
ipv6lab.place(x=50, y=250, width=200, height=20)
lab4 = tk.Label(root, text='投屏访问地址', relief='flat')
lab4.pack()
lab4.place(x=280, y=250)
simulation_var = tk.BooleanVar()
simulation_var.set(enable_simulation)
simulation_button = tk.Checkbutton(root, text="远程控制", variable=simulation_var)
simulation_button.pack()
simulation_button.place(x=230, y=200)
enable_video_var = tk.BooleanVar()
enable_video_var.set(enable_video)
enable_video_button = tk.Checkbutton(root, text="投屏", variable=enable_video_var)
enable_video_button.pack()
enable_video_button.place(x=360, y=200)
# 右侧设置
username_var = tk.StringVar()
username_var.set(users[0])
usernamelab = tk.Entry(root, textvariable=username_var, relief="sunken")
usernamelab.pack()
usernamelab.place(x=450, y=50, width=200, height=20)
labr1 = tk.Label(root, text='用户名', relief='flat')
labr1.pack()
labr1.place(x=680, y=50)
password_var = tk.StringVar()
password_var.set(users[1])
passwordlab = tk.Entry(root, textvariable=password_var, relief="sunken")
passwordlab.pack()
passwordlab.place(x=450, y=100, width=200, height=20)
labr2 = tk.Label(root, text='密码', relief='flat')
labr2.pack()
labr2.place(x=680, y=100)
filesend_var = tk.StringVar()
filesend_var.set(UPLOAD_FOLDER)
filesendlab = tk.Entry(root, textvariable=filesend_var, relief="sunken")
filesendlab.pack()
filesendlab.place(x=450, y=150, width=200, height=20)
labr3 = tk.Label(root, text='传输用文件夹路径', relief='flat')
labr3.pack()
labr3.place(x=655, y=150)
def choose_flie_path(windowtitle = '选择文件夹'):
global filesend_var
filesend_var.set(filedialog.askdirectory(title = windowtitle))
return None
buttonmain = tk.Button(root, text='选择', command=choose_flie_path)
buttonmain.pack()
buttonmain.place(x=680, y=175, width=50, height=20)
file_address_var = tk.StringVar()
file_addresslab = tk.Entry(root, textvariable=file_address_var, state="readonly")
file_addresslab.pack()
file_addresslab.place(x=450, y=250, width=200, height=20)
labr5 = tk.Label(root, text='文件访问地址', relief='flat')
labr5.pack()
labr5.place(x=680, y=250)
file_download_var = tk.BooleanVar()
file_download_var.set(enable_file_download)
file_download_button = tk.Checkbutton(root, text="文件下载", variable=file_download_var)
file_download_button.pack()
file_download_button.place(x=450, y=200)
file_upload_var = tk.BooleanVar()
file_upload_var.set(enable_file_upload)
file_upload_button = tk.Checkbutton(root, text="文件上传和删除", variable=file_upload_var)
file_upload_button.pack()
file_upload_button.place(x=630, y=200)
# 一键复制地址按钮
def copy_address():
pyperclip.copy('投屏访问地址\n'+ipv6_var.get()+'\n文件访问地址\n'+file_address_var.get())
buttonmain = tk.Button(root, text='复制地址', command=copy_address)
buttonmain.pack()
buttonmain.place(x=450, y=300, width=100, height=40)
# 保存配置按钮
def save_config():
with open('config.txt','w') as config_file:
ipv4 = ipv4_var.get()
ipport = int(ipport_var.get())
fps = int(zhenlv_var.get()) # 帧率 (fps)
compression_quality = int(quality_var.get()) # 图像压缩质量 (1-100)
compression_quality = round(95 * compression_quality / 100)
enable_simulation = simulation_var.get() # 是否启用远程控制和文件传输
enable_file_download = file_download_var.get()
enable_file_upload = file_upload_var.get()
enable_video = enable_video_var.get()
UPLOAD_FOLDER = filesend_var.get() # 文件传输文件夹路径
users[0] = username_var.get()
users[1] = password_var.get()
config_file.write(f'''
fps = {fps}
compression_quality = {compression_quality}
ipv4 = {ipv4}
enable_simulation = {enable_simulation}
users = {users}
ipport = {ipport}
enable_video = {enable_video}
enable_file_download = {enable_file_download}
enable_file_upload = {enable_file_upload}
UPLOAD_FOLDER = '{UPLOAD_FOLDER.replace('\\','\\\\')}'
'''.strip())
buttonmain = tk.Button(root, text='保存配置', command=save_config)
buttonmain.pack()
buttonmain.place(x=700, y=0, width=100, height=40)
# 主按钮
qidong = False
def main():
global qidong, fps, sleeptime, compression_quality, enable_simulation, ip, ipport, users, UPLOAD_FOLDER, enable_file_download, enable_file_upload, enable_video, ipv4
if not qidong:
qidong = True
ipv4 = ipv4_var.get()
ip = '::'
if ipv4:
ip = '0.0.0.0'
ipport = int(ipport_var.get())
fps = int(zhenlv_var.get()) # 帧率 (fps)
if fps == -1:
sleeptime = 0
else:
sleeptime = 1 / fps
compression_quality = int(quality_var.get()) # 图像压缩质量 (1-100)
compression_quality = round(95 * compression_quality / 100)
enable_simulation = simulation_var.get() # 是否启用远程控制和文件传输
enable_file_download = file_download_var.get()
enable_file_upload = file_upload_var.get()
enable_video = enable_video_var.get()
UPLOAD_FOLDER = filesend_var.get() # 文件传输文件夹路径
if UPLOAD_FOLDER != '':
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
users[0] = username_var.get()
users[1] = password_var.get()
if not ipv4:
ipv6_var.set('https://[' + get_ipv6_address() + ']:' + ipport_var.get())
file_address_var.set(ipv6_var.get()+'/file')
else:
ipv6_var.set('https://' + get_ipv4_address() + ':' + ipport_var.get())
file_address_var.set(ipv6_var.get()+'/file')
# 启动 Flask 服务
def run_flask():
app.run(ssl_context='adhoc', host=ip, port=ipport, threaded=True)
flask_thread = Thread(target=run_flask)
flask_thread.daemon = True
flask_thread.start()
buttonmain = tk.Button(root, text='开始投屏', command=main)
buttonmain.pack()
buttonmain.place(x=250, y=300, width=100, height=40)
#启动窗口
root.mainloop()
|
2301_80130186/ipv6
|
隧影0.0.15s.py
|
Python
|
mit
| 46,506
|
import os
import asyncio
import json
import cv2
import numpy as np
from aiohttp import web
from aiohttp_session import setup, get_session, session_middleware
from aiohttp_session.cookie_storage import EncryptedCookieStorage
from mss import mss
from aiortc import RTCPeerConnection, RTCSessionDescription
from aiortc.mediastreams import VideoStreamTrack
from av import VideoFrame
import time
import socket
import struct
import threading
import ssl
import tempfile
import cryptography
from cryptography import x509
from cryptography.x509.oid import NameOID
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.fernet import Fernet
import datetime
import pyautogui
import subprocess
import sys
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, QFormLayout,
QSpinBox, QLineEdit, QPushButton, QHBoxLayout, QCheckBox,
QLabel, QFileDialog, QGroupBox, QGridLayout, QTextEdit)
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont, QIntValidator
# ====== 全局参数(可修改) ======
TARGET_FPS = 30 # 目标帧率
MAX_WIDTH = 1600 # 超过此宽度则等比缩放
STUN_PORT = 54250 # STUN 服务端口
WEB_PORT = 55555 # Web 服务端口(HTTPS)
users = ("", "") # (用户名, 密码)
enable_file_download = True
enable_file_upload = False
enable_video = True
enable_control = False
enable_ipv4 = True
enable_ipv6 = False
UPLOAD_FOLDER = ''
try:
with open('config.txt','r') as config_file:
config_text = config_file.read()
exec(config_text)
except BaseException:
print('读入参数错误,使用默认配置')
# ============================
STUN_HOST = "::" # STUN 服务监听地址
WEB_HOST_V4 = "0.0.0.0" # Web 服务 IPv4 地址
WEB_HOST_V6 = "::" # Web 服务 IPv6 地址
screen_width, screen_height = pyautogui.size()
CURSOR = False # 是否捕获鼠标
MONITOR_INDEX = 1 # mss().monitors[1] 是主屏
SECRET_KEY = Fernet.generate_key().decode()
# ============================
index_html = '''
<!doctype html>
<html lang="zh">
<head>
<meta charset="utf-8" />
<title>屏幕播放</title>
<meta name="viewport" content="width=device-width,initial-scale=1" />
<style>
body {
margin: 0;
padding: 0;
background: black;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
video {
max-width: 100%;
max-height: 100%;
object-fit: contain;
background: black;
}
#click-area {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 10;
}
#floating-button {
position: absolute;
top: 20px;
left: 20px;
width: 50px;
height: 50px;
background-color: #39c5bb;
color: white;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
user-select: none;
z-index: 20;
}
#floating-window {
position: absolute;
top: 80px;
left: 20px;
width: 200px;
background-color: white;
border: 1px solid #ccc;
border-radius: 5px;
padding: 10px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
display: none;
z-index: 20;
}
#floating-window label {
display: block;
margin-bottom: 10px;
}
.window-button {
width: 100%;
padding: 8px;
margin-bottom: 10px;
background-color: #39c5bb;
color: white;
border: none;
border-radius: 3px;
cursor: pointer;
text-align: center;
transition: background-color 0.3s;
}
.window-button:hover {
background-color: #2da49c;
}
.error-message {
position: fixed;
bottom: 20px;
left: 20px;
background-color: #ff4444;
color: white;
padding: 10px 15px;
border-radius: 4px;
display: none;
z-index: 100;
}
</style>
</head>
<body>
<video id="video" autoplay playsinline muted></video>
<div id="click-area"></div>
<div id="floating-button">设置</div>
<div id="floating-window">
<label>
<input type="checkbox" id="toggle-right-click"> 左键变右键
</label>
<button class="window-button" id="file-manager-btn">文件管理</button>
</div>
<div class="error-message" id="errorMessage"></div>
<script>
const videoEl = document.getElementById('video');
const errorMessage = document.getElementById('errorMessage');
let pc;
// 显示错误消息
function showError(message) {
errorMessage.textContent = message;
errorMessage.style.display = 'block';
setTimeout(() => {
errorMessage.style.display = 'none';
}, 5000);
}
// 视频相关逻辑保持不变,但修复了ICE服务器配置
async function start() {
if (pc) {
pc.close();
pc = null;
}
try {
// 修复ICE服务器配置,使用默认端口或正确的端口号
const iceServers = [];
const port = window.location.port || (window.location.protocol === 'https:' ? 443 : 80);
// 仅当不是默认端口时才添加端口号
const stunUrl = `stun:${window.location.hostname}${port && (port !== '80' && port !== '443') ? `:${port}` : ''}`;
iceServers.push({ urls: stunUrl });
pc = new RTCPeerConnection({ iceServers });
// 接收远端视频
pc.addTransceiver('video', { direction: 'recvonly' });
pc.ontrack = (ev) => {
videoEl.srcObject = ev.streams[0];
};
const offer = await pc.createOffer();
await pc.setLocalDescription(offer);
const resp = await fetch('/offer', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ sdp: offer.sdp, type: offer.type })
});
if (!resp.ok) {
throw new Error(`服务器响应错误: ${resp.status}`);
}
const answer = await resp.json();
await pc.setRemoteDescription(answer);
} catch (error) {
console.error('初始化错误:', error);
showError(`初始化失败: ${error.message}`);
}
}
start();
window.addEventListener("beforeunload", () => {
if (pc) pc.close();
});
// 从2.html添加的键鼠映射和悬浮窗逻辑
const clickArea = document.getElementById('click-area');
const floatingButton = document.getElementById('floating-button');
const floatingWindow = document.getElementById('floating-window');
const toggleRightClick = document.getElementById('toggle-right-click');
const fileManagerBtn = document.getElementById('file-manager-btn');
// 文件管理按钮点击事件 - 跳转到当前URL的/file路径
fileManagerBtn.addEventListener('click', () => {
try {
// 获取当前URL并添加/file路径
const currentUrl = window.location.href;
// 处理可能已存在的路径
const baseUrl = currentUrl.split('/').slice(0, 3).join('/');
const fileUrl = `${baseUrl}/file`;
window.location.href = fileUrl;
} catch (error) {
console.error('文件管理跳转错误:', error);
showError('无法打开文件管理');
}
});
let isDragging = false;
let offsetX, offsetY;
// 屏蔽右键默认菜单
clickArea.addEventListener('contextmenu', (event) => {
event.preventDefault();
});
// 悬浮按钮点击事件
floatingButton.addEventListener('click', () => {
floatingWindow.style.display = floatingWindow.style.display === 'none' ? 'block' : 'none';
});
// 悬浮按钮拖动事件
floatingButton.addEventListener('mousedown', (event) => {
isDragging = true;
offsetX = event.clientX - floatingButton.offsetLeft;
offsetY = event.clientY - floatingButton.offsetTop;
});
document.addEventListener('mousemove', (event) => {
if (isDragging) {
floatingButton.style.left = `${event.clientX - offsetX}px`;
floatingButton.style.top = `${event.clientY - offsetY}px`;
floatingWindow.style.left = `${event.clientX - offsetX}px`;
floatingWindow.style.top = `${event.clientY - offsetY + 60}px`;
}
});
document.addEventListener('mouseup', () => {
isDragging = false;
});
// 根据视频的渲染尺寸计算有效点击区域,并返回百分比坐标
function getVideoCoordinates(event) {
const video = document.querySelector('video');
const rect = video.getBoundingClientRect();
const naturalWidth = video.videoWidth;
const naturalHeight = video.videoHeight;
const displayWidth = rect.width;
const displayHeight = rect.height;
const videoAspectRatio = naturalWidth / naturalHeight;
const displayAspectRatio = displayWidth / displayHeight;
let renderWidth, renderHeight, offsetX, offsetY;
if (displayAspectRatio > videoAspectRatio) {
renderHeight = displayHeight;
renderWidth = renderHeight * videoAspectRatio;
offsetX = (displayWidth - renderWidth) / 2;
offsetY = 0;
} else {
renderWidth = displayWidth;
renderHeight = renderWidth / videoAspectRatio;
offsetX = 0;
offsetY = (displayHeight - renderHeight) / 2;
}
const x = event.clientX - rect.left - offsetX;
const y = event.clientY - rect.top - offsetY;
if (x < 0 || x > renderWidth || y < 0 || y > renderHeight) {
return null;
}
const xPercent = (x / renderWidth) * 100;
const yPercent = (y / renderHeight) * 100;
return { xPercent, yPercent };
}
// 用于记录鼠标按下时的起始坐标
let dragStart = null;
// 鼠标按下时记录起始坐标
clickArea.addEventListener('mousedown', (event) => {
event.preventDefault();
const coords = getVideoCoordinates(event);
if (!coords) return;
const button = toggleRightClick.checked ? 'right' : (event.button === 2 ? 'right' : 'left');
dragStart = { x: coords.xPercent, y: coords.yPercent, button };
});
// 鼠标松开时发送拖动请求
clickArea.addEventListener('mouseup', async (event) => {
event.preventDefault();
if (!dragStart) return;
const coords = getVideoCoordinates(event);
if (!coords) {
dragStart = null;
return;
}
try {
const response = await fetch('/drag', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
start_x: dragStart.x,
start_y: dragStart.y,
end_x: coords.xPercent,
end_y: coords.yPercent,
button: dragStart.button
}),
});
if (!response.ok) {
throw new Error(`服务器未找到此接口: ${response.status}`);
}
} catch (error) {
console.error('拖动请求错误:', error);
showError('操作无法执行: 服务器不支持此功能');
} finally {
dragStart = null;
}
});
// 键盘事件映射
document.addEventListener('keydown', async (event) => {
const key = event.key;
try {
const response = await fetch('/keypress', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ key }),
});
if (!response.ok) {
throw new Error(`服务器未找到此接口: ${response.status}`);
}
} catch (error) {
console.error('键盘事件错误:', error);
showError('操作无法执行: 服务器不支持此功能');
}
});
// 窗口大小变化时重置视频尺寸
window.addEventListener('resize', () => {
const video = document.querySelector('video');
if (video) {
video.style.maxWidth = '100%';
video.style.maxHeight = '100%';
}
});
</script>
</body>
</html>
'''
login_html = '''
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>用户登录</title>
<style>
body {{
font-family: Arial, sans-serif;
background-color: #f0f2f5;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}}
.login-container {{
background-color: #ffffff;
padding: 40px 50px;
border-radius: 12px;
box-shadow: 0 8px 20px rgba(0,0,0,0.1);
width: 350px;
text-align: center;
}}
.login-container h2 {{
margin-bottom: 30px;
color: #333333;
}}
.login-container input[type="text"],
.login-container input[type="password"] {{
width: 100%;
padding: 12px 15px;
margin: 10px 0;
border: 1px solid #ddd;
border-radius: 6px;
box-sizing: border-box;
font-size: 14px;
}}
.login-container button {{
width: 100%;
padding: 12px 15px;
margin-top: 20px;
background-color: #39c5bb;
border: none;
border-radius: 6px;
color: white;
font-size: 16px;
cursor: pointer;
transition: background-color 0.3s;
}}
.login-container button:hover {{
background-color: #80dbd5;
}}
.error-message {{
background-color: #fff0f0;
border: 1px solid #ffcccc;
color: #d8000c;
padding: 12px 15px;
border-radius: 6px;
margin-bottom: 20px;
font-size: 14px;
display: {error_display};
}}
</style>
</head>
<body>
<div class="login-container">
<h2>隧 影 投 屏</h2>
<form method="post" action="/login">
<div class="error-message">{error_message}</div>
<input type="text" name="账户名" placeholder="账户名">
<input type="password" name="密码" placeholder="密码">
<button type="submit">登录</button>
</form>
</div>
</body>
</html>
'''
file_html = '''
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>文件管理器</title>
<style>
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
line-height: 1.6;
color: #333;
max-width: 800px;
margin: 0 auto;
padding: 30px 20px;
background-color: #f8f9fa;
}
/* 返回按钮样式 */
.back-button {
position: absolute;
top: 30px;
left: 20px;
background-color: #95a5a6;
color: white;
border: none;
padding: 8px 16px;
border-radius: 4px;
cursor: pointer;
font-size: 0.9rem;
text-decoration: none;
transition: background-color 0.3s ease;
}
.back-button:hover {
background-color: #7f8c8d;
}
h1 {
color: #2c3e50;
margin-bottom: 30px;
padding-bottom: 10px;
border-bottom: 2px solid #3498db;
text-align: center;
}
h2 {
color: #34495e;
margin: 25px 0 15px;
font-size: 1.4rem;
}
.upload-form {
background-color: white;
padding: 25px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
margin-bottom: 30px;
transition: box-shadow 0.3s ease;
}
.upload-form:hover {
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.15);
}
input[type="file"] {
display: block;
margin-bottom: 15px;
padding: 8px;
border: 1px solid #ddd;
border-radius: 4px;
width: 100%;
cursor: pointer;
}
input[type="submit"] {
background-color: #3498db;
color: white;
border: none;
padding: 10px 20px;
border-radius: 4px;
cursor: pointer;
font-size: 1rem;
transition: background-color 0.3s ease;
}
input[type="submit"]:hover {
background-color: #2980b9;
}
ul {
list-style-type: none;
background-color: white;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
overflow: hidden;
}
.file-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 12px 20px;
border-bottom: 1px solid #f1f1f1;
}
.file-link {
color: #2980b9;
text-decoration: none;
transition: all 0.3s ease;
}
.file-link:hover {
color: #1a5276;
text-decoration: underline;
}
.delete-btn {
margin-left: 10px;
background-color: #e74c3c;
color: white;
border: none;
padding: 3px 8px;
border-radius: 3px;
cursor: pointer;
font-size: 0.8rem;
transition: background-color 0.3s ease;
}
.delete-btn:hover {
background-color: #c0392b;
}
/* 进度条样式 */
.progress-container {
width: 100%;
height: 8px;
background-color: #e0e0e0;
border-radius: 4px;
margin-top: 15px;
overflow: hidden;
display: none; /* 默认隐藏 */
}
.progress-bar {
height: 100%;
background-color: #3498db;
width: 0%;
transition: width 0.3s ease;
}
/* 状态提示样式 */
.status-message {
margin-top: 15px;
padding: 10px;
border-radius: 4px;
display: none;
}
.success {
background-color: #dff0d8;
color: #3c763d;
border: 1px solid #d6e9c6;
}
.error {
background-color: #f2dede;
color: #a94442;
border: 1px solid #ebccd1;
}
/* 空列表提示 */
.empty-message {
padding: 12px 20px;
color: #7f8c8d;
text-align: center;
}
</style>
</head>
<body>
<!-- 添加返回按钮 -->
<a href="../" class="back-button">返回</a>
<h1>文件管理器</h1>
<h2>上传文件</h2>
<form id="uploadForm" class="upload-form" method="POST" enctype="multipart/form-data">
<input type="file" name="file" id="fileInput" multiple>
<input type="submit" value="上传">
<div class="progress-container">
<div class="progress-bar" id="progressBar"></div>
</div>
<div class="status-message" id="statusMessage"></div>
</form>
<h2>文件列表</h2>
<ul id="fileList">
<!-- 文件列表通过JavaScript动态生成 -->
<li class="empty-message">加载文件列表中...</li>
</ul>
<script>
// 页面加载时就获取文件列表
document.addEventListener('DOMContentLoaded', function() {
refreshFileList();
});
// 文件上传进度
const uploadForm = document.getElementById('uploadForm');
const progressBar = document.getElementById('progressBar');
const progressContainer = document.querySelector('.progress-container');
const statusMessage = document.getElementById('statusMessage');
const fileList = document.getElementById('fileList');
uploadForm.addEventListener('submit', function(e) {
e.preventDefault();
const formData = new FormData(this);
const xhr = new XMLHttpRequest();
xhr.open('POST', '/upload', true);
xhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
const percent = (e.loaded / e.total) * 100;
progressBar.style.width = percent + '%';
progressContainer.style.display = 'block';
}
});
xhr.addEventListener('load', function() {
progressContainer.style.display = 'none';
if (xhr.status === 200) {
showStatus('文件上传成功!', 'success');
refreshFileList();
} else {
showStatus('上传失败: ' + xhr.responseText, 'error');
}
// 重置表单
uploadForm.reset();
progressBar.style.width = '0%';
});
xhr.addEventListener('error', function() {
progressContainer.style.display = 'none';
showStatus('上传失败,请重试', 'error');
});
xhr.send(formData);
});
// 刷新文件列表
function refreshFileList() {
fetch('/file', {
headers: { "Accept": "application/json" }
})
.then(response => response.json())
.then(files => {
fileList.innerHTML = '';
if (!files || files.length === 0) {
const emptyItem = document.createElement('li');
emptyItem.className = 'empty-message';
emptyItem.textContent = '暂无文件';
fileList.appendChild(emptyItem);
return;
}
files.forEach(file => {
const listItem = document.createElement('li');
listItem.className = 'file-item';
const fileLink = document.createElement('a');
fileLink.href = '/download/' + encodeURIComponent(file);
fileLink.className = 'file-link';
fileLink.textContent = file;
fileLink.setAttribute('download', file);
const deleteBtn = document.createElement('button');
deleteBtn.className = 'delete-btn';
deleteBtn.textContent = '删除';
deleteBtn.setAttribute('data-filename', file);
listItem.appendChild(fileLink);
listItem.appendChild(deleteBtn);
fileList.appendChild(listItem);
});
})
.catch(error => {
console.error('刷新文件列表失败:', error);
fileList.innerHTML = '<li class="empty-message">加载文件失败</li>';
});
}
// 显示状态消息
function showStatus(message, type) {
statusMessage.textContent = message;
statusMessage.className = 'status-message ' + type;
statusMessage.style.display = 'block';
// 3秒后隐藏消息
setTimeout(() => {
statusMessage.style.display = 'none';
}, 3000);
}
// 为删除按钮添加事件监听
fileList.addEventListener('click', function(e) {
if (e.target.classList.contains('delete-btn')) {
const filename = e.target.getAttribute('data-filename');
if (confirm(`确定要删除文件 "${filename}" 吗?`)) {
deleteFile(filename);
}
}
});
// 删除文件函数
function deleteFile(filename) {
fetch(`/delete/${encodeURIComponent(filename)}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
}
})
.then(response => response.json())
.then(data => {
if (data.status === 'success') {
showStatus('文件删除成功!', 'success');
refreshFileList();
} else {
showStatus('删除失败: ' + data.message, 'error');
}
})
.catch(error => {
console.error('删除文件失败:', error);
showStatus('删除失败,请重试', 'error');
});
}
</script>
</body>
</html>
'''
class ScreenTrack(VideoStreamTrack):
kind = "video"
def __init__(self, monitor_index=1, fps=20, max_width=1280, cursor=True):
super().__init__()
self.sct = mss()
self.monitor = self.sct.monitors[monitor_index]
self.frame_interval = 1.0 / fps
self.max_width = max_width
self.cursor = cursor
self._last_ts = time.time()
async def recv(self) -> VideoFrame:
now = time.time()
sleep_time = self.frame_interval - (now - self._last_ts)
if sleep_time > 0:
await asyncio.sleep(sleep_time)
self._last_ts = time.time()
raw = self.sct.grab(self.monitor)
img = np.asarray(raw) # (H, W, 4) BGRA
frame_bgr = cv2.cvtColor(img, cv2.COLOR_BGRA2BGR)
h, w = frame_bgr.shape[:2]
if w > self.max_width:
scale = self.max_width / w
frame_bgr = cv2.resize(frame_bgr, (int(w*scale), int(h*scale)), interpolation=cv2.INTER_AREA)
av_frame = VideoFrame.from_ndarray(frame_bgr, format="bgr24")
av_frame = av_frame.reformat(format="yuv420p")
pts, time_base = await self.next_timestamp()
av_frame.pts = pts
av_frame.time_base = time_base
return av_frame
routes = web.RouteTableDef()
pcs = set()
# ===================主页面接口=====================
@routes.get("/")
async def index(request):
session = await get_session(request)
if 'username' not in session:
raise web.HTTPFound('/login')
if not enable_video:
raise web.HTTPFound('/file')
return web.Response(
text=index_html,
content_type="text/html"
)
@routes.route('*', '/login')
async def login(request):
"""登录视图,处理GET和POST请求"""
error_message = ""
if request.method == 'POST':
# 解析表单数据
data = await request.post()
username = data.get('账户名', '').strip()
password = data.get('密码', '').strip()
if username == users[0] and password == users[1]:
session = await get_session(request)
session['username'] = username
raise web.HTTPFound('/')
else:
error_message = "用户名或密码错误,请重新输入"
# 格式化 HTML,填入错误提示和显示状态
return web.Response(
text=login_html.format(
error_message=error_message,
error_display="block" if error_message else "none"
),
content_type='text/html'
)
@routes.post("/offer")
async def offer(request):
params = await request.json()
offer = RTCSessionDescription(sdp=params["sdp"], type=params["type"])
pc = RTCPeerConnection()
pcs.add(pc)
@pc.on("connectionstatechange")
async def on_state_change():
print("Connection state:", pc.connectionState)
if pc.connectionState in ("failed", "closed", "disconnected"):
await pc.close()
pcs.discard(pc)
screen_track = ScreenTrack(
monitor_index=MONITOR_INDEX,
fps=TARGET_FPS,
max_width=MAX_WIDTH,
cursor=CURSOR
)
pc.addTrack(screen_track)
await pc.setRemoteDescription(offer)
answer = await pc.createAnswer()
await pc.setLocalDescription(answer)
return web.Response(
content_type="application/json",
text=json.dumps({"sdp": pc.localDescription.sdp, "type": pc.localDescription.type})
)
@routes.get("/health")
async def health(_):
session = await get_session(request)
if 'username' not in session:
raise web.HTTPFound('/login')
return web.json_response({"ok": True, "peers": len(pcs)})
# 远程控制映射接口
@routes.post("/click")
async def handle_click(request):
session = await get_session(request)
if 'username' not in session:
raise web.HTTPFound('/login')
if not enable_control:
return web.json_response({"status": "disabled"}, status=403)
data = await request.json()
x_percent = data['x']
y_percent = data['y']
button = data.get('button', 'left')
actual_x = int((x_percent / 100) * screen_width)
actual_y = int((y_percent / 100) * screen_height)
if button == 'right':
pyautogui.rightClick(actual_x, actual_y)
else:
pyautogui.click(actual_x, actual_y)
return web.json_response({"status": "success"}, status=200)
@routes.post("/drag")
async def handle_drag(request):
session = await get_session(request)
if 'username' not in session:
raise web.HTTPFound('/login')
if not enable_control:
return web.json_response({"status": "disabled"}, status=403)
data = await request.json()
start_x_percent = data['start_x']
start_y_percent = data['start_y']
end_x_percent = data['end_x']
end_y_percent = data['end_y']
button = data.get('button', 'left')
actual_start_x = int((start_x_percent / 100) * screen_width)
actual_start_y = int((start_y_percent / 100) * screen_height)
actual_end_x = int((end_x_percent / 100) * screen_width)
actual_end_y = int((end_y_percent / 100) * screen_height)
pyautogui.moveTo(actual_start_x, actual_start_y)
pyautogui.mouseDown(button=button)
time.sleep(0.3)
pyautogui.moveTo(actual_end_x, actual_end_y, duration=0.05)
pyautogui.mouseUp(button=button)
return web.json_response({"status": "success"}, status=200)
@routes.post("/keypress")
async def handle_keypress(request):
session = await get_session(request)
if 'username' not in session:
raise web.HTTPFound('/login')
if not enable_control:
return web.json_response({"status": "disabled"}, status=403)
data = await request.json()
key = data['key']
pyautogui.press(key)
return web.json_response({"status": "success"}, status=200) # 200表示成功
# ========================文件传输接口========================
@routes.get('/file')
async def fileindex(request):
session = await get_session(request)
if 'username' not in session:
raise web.HTTPFound('/login')
if (not (enable_file_download or enable_file_upload)) or (UPLOAD_FOLDER == ''):
return web.Response(text="服务端未允许文件传输", status=403)
# 判断请求是否是 Ajax/json 请求
accept = request.headers.get("Accept", "")
if "application/json" in accept:
files = os.listdir(UPLOAD_FOLDER)
return web.json_response(files)
else:
return web.Response(text=file_html, content_type="text/html")
@routes.post('/upload')
async def upload_file(request):
session = await get_session(request)
if (not enable_file_upload) or ('username' not in session) or (UPLOAD_FOLDER == ''):
return web.json_response({"status": "error", "message": "服务端未允许文件传输"}, status=403)
reader = await request.multipart()
field = await reader.next()
if field is None or field.name != "file":
return web.json_response({"status": "error", "message": "未找到文件"}, status=400)
filename = field.filename
if not filename:
return web.json_response({"status": "error", "message": "文件名不能为空"}, status=400)
file_path = os.path.join(UPLOAD_FOLDER, filename)
try:
with open(file_path, 'wb') as f:
while True:
chunk = await field.read_chunk(1024 * 1024)
if not chunk:
break
f.write(chunk)
return web.json_response({"status": "success", "message": "文件上传成功"})
except Exception as e:
return web.json_response({"status": "error", "message": f"上传失败: {str(e)}"}, status=500)
@routes.get('/download/{filename}')
async def download_file(request):
session = await get_session(request)
if (not enable_file_download) or ('username' not in session) or (UPLOAD_FOLDER == ''):
return web.Response(text="服务端未允许文件传输", status=403)
filename = request.match_info['filename']
file_path = os.path.join(UPLOAD_FOLDER, filename)
if not os.path.exists(file_path):
return web.Response(text="文件不存在", status=404)
return web.FileResponse(path=file_path)
@routes.post('/delete/{filename}')
async def delete_file(request):
session = await get_session(request)
if (not enable_file_upload) or ('username' not in session) or (UPLOAD_FOLDER == ''):
return web.json_response({"status": "error", "message": "没有删除权限"}, status=403)
filename = request.match_info['filename']
file_path = os.path.join(UPLOAD_FOLDER, filename)
try:
if not os.path.abspath(file_path).startswith(os.path.abspath(UPLOAD_FOLDER)):
return web.json_response({"status": "error", "message": "无效的文件路径"}, status=400)
if not os.path.exists(file_path) or not os.path.isfile(file_path):
return web.json_response({"status": "error", "message": "文件不存在"}, status=404)
os.remove(file_path)
return web.json_response({"status": "success", "message": "文件已删除"})
except Exception as e:
return web.json_response({"status": "error", "message": f"删除失败: {str(e)}"}, status=500)
@routes.get('/file-list')
async def file_list(request):
session = await get_session(request)
if (not (enable_file_download or enable_file_upload)) or ('username' not in session) or (UPLOAD_FOLDER == ''):
return web.json_response([], status=403)
try:
files = [f for f in os.listdir(UPLOAD_FOLDER) if os.path.isfile(os.path.join(UPLOAD_FOLDER, f))]
return web.json_response(files)
except Exception:
return web.json_response([], status=500)
# 关闭网页服务
async def on_shutdown(app):
coros = [pc.close() for pc in pcs]
await asyncio.gather(*coros, return_exceptions=True)
pcs.clear()
# ========== 简易 STUN 服务器 ==========
def run_stun_server(host=STUN_HOST, port=STUN_PORT):
sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)
except OSError:
pass
sock.bind((host, port))
print(f"STUN server listening on [{host}]:{port}")
while True:
data, addr = sock.recvfrom(2048)
if len(data) < 20:
continue
msg_type, msg_len, magic_cookie = struct.unpack("!HHI", data[:8])
if magic_cookie != 0x2112A442:
continue
if msg_type != 0x0001:
continue
trans_id = data[8:20]
attrs = b""
ip_str, portnum = addr[0], addr[1]
try:
ip_bytes = socket.inet_pton(socket.AF_INET, ip_str)
x_port = portnum ^ (0x2112)
x_ip = struct.unpack("!I", ip_bytes)[0] ^ 0x2112A442
attr = struct.pack("!HHBBH", 0x0020, 8, 0, 0x01, x_port) + struct.pack("!I", x_ip)
attrs += attr
except OSError:
try:
ip_bytes = socket.inet_pton(socket.AF_INET6, ip_str)
x_port = portnum ^ (0x2112)
x_ip = bytearray(ip_bytes)
cookie = struct.pack("!I", 0x2112A442) + trans_id
for i in range(16):
x_ip[i] ^= cookie[i % len(cookie)]
attr = struct.pack("!HHBBH", 0x0020, 20, 0, 0x02, x_port) + bytes(x_ip)
attrs += attr
except OSError:
pass
if not attrs:
continue
msg_type = 0x0101
msg_len = len(attrs)
header = struct.pack("!HHI", msg_type, msg_len, 0x2112A442) + trans_id
resp = header + attrs
sock.sendto(resp, addr)
# ========== 生成临时 HTTPS 证书 ==========
def generate_ssl_context():
cert_file = "server.crt"
key_file = "server.key"
# 如果证书和私钥已经存在,直接加载
if os.path.exists(cert_file) and os.path.exists(key_file):
ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
ssl_ctx.load_cert_chain(cert_file, key_file)
print(f"Loaded existing certificate: {cert_file}, {key_file}")
return ssl_ctx
# 生成新的证书和私钥
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
subject = issuer = x509.Name([
x509.NameAttribute(NameOID.COMMON_NAME, u"localhost")
])
cert = (
x509.CertificateBuilder()
.subject_name(subject)
.issuer_name(issuer)
.public_key(key.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(datetime.datetime.now(datetime.UTC) - datetime.timedelta(days=1))
.not_valid_after(datetime.datetime.now(datetime.UTC) + datetime.timedelta(days=365)) # 有效期1年
.sign(key, hashes.SHA256())
)
# 写入当前目录
with open(cert_file, "wb") as f:
f.write(cert.public_bytes(serialization.Encoding.PEM))
with open(key_file, "wb") as f:
f.write(
key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption()
)
)
ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
ssl_ctx.load_cert_chain(cert_file, key_file)
print(f"Generated new certificate: {cert_file}, {key_file}")
return ssl_ctx
async def main_async():
threading.Thread(target=run_stun_server, daemon=True).start()
storage = EncryptedCookieStorage(
SECRET_KEY,
cookie_name="MYSESSION",
max_age=None,
httponly=True,
secure=True
)
app = web.Application(middlewares=[session_middleware(storage)])
setup(app, storage)
app.add_routes(routes)
app.on_shutdown.append(on_shutdown)
runner = web.AppRunner(app)
await runner.setup()
ssl_ctx = generate_ssl_context()
site_v4 = web.TCPSite(runner, host=WEB_HOST_V4, port=WEB_PORT, ssl_context=ssl_ctx)
site_v6 = web.TCPSite(runner, host=WEB_HOST_V6, port=WEB_PORT, ssl_context=ssl_ctx)
if enable_ipv4:
await site_v4.start()
if enable_ipv6:
await site_v6.start()
print(f"HTTPS Web server listening on {WEB_HOST_V4}:{WEB_PORT} and [{WEB_HOST_V6}]:{WEB_PORT}")
while True:
await asyncio.sleep(3600)
def main():
asyncio.run(main_async())
# ============================UI界面==============================
class ConfigWindow(QMainWindow):
def __init__(self):
super().__init__()
font = QFont()
font.setFamily("SimHei")
font.setPointSize(10)
self.setFont(font)
self.initUI()
def initUI(self):
self.setWindowTitle('隧影投屏')
self.setGeometry(100, 100, 700, 900)
self.setFixedSize(700, 900) # 锁定窗口大小
central_widget = QWidget()
central_widget.setStyleSheet("""
QWidget { background-color: #f5f5f5; }
QLabel { color: #333333; }
QLabel#titleLabel {
font-size: 16px;
font-weight: bold;
color: #2c3e50;
margin: 10px 0;
}
QGroupBox {
border: 1px solid #ddd;
border-radius: 6px;
margin-top: 10px;
padding: 15px;
background-color: white;
}
QGroupBox::title {
subcontrol-origin: margin;
left: 10px;
padding: 0 5px 0 5px;
color: #34495e;
font-weight: bold;
}
QPushButton {
background-color: #3498db;
color: white;
border: none;
padding: 6px 12px;
border-radius: 4px;
font-size: 10px;
}
QPushButton:hover { background-color: #2980b9; }
QPushButton:pressed { background-color: #2471a3; }
QPushButton#startBtn { background-color: #2ecc71; }
QPushButton#startBtn:hover { background-color: #27ae60; }
QPushButton#startBtn:pressed { background-color: #219653; }
QPushButton#browseBtn { background-color: #95a5a6; }
QPushButton#browseBtn:hover { background-color: #7f8c8d; }
QLineEdit, QCheckBox {
padding: 5px;
border: 1px solid #bdc3c7;
border-radius: 3px;
background-color: white;
}
QLineEdit:focus {
border-color: #3498db;
outline: none;
}
""")
self.setCentralWidget(central_widget)
main_layout = QVBoxLayout(central_widget)
main_layout.setContentsMargins(20, 20, 20, 20)
main_layout.setSpacing(15)
# 视频参数分组
video_group = QGroupBox("视频参数设置")
video_layout = QFormLayout()
video_layout.setRowWrapPolicy(QFormLayout.DontWrapRows)
video_layout.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)
video_layout.setLabelAlignment(Qt.AlignLeft)
video_layout.setVerticalSpacing(10)
# 目标帧率 - 使用QLineEdit并添加整数验证
self.fps_edit = QLineEdit()
self.fps_edit.setText(str(TARGET_FPS))
self.fps_edit.setValidator(QIntValidator(1, 120)) # 限制1-120之间的整数
video_layout.addRow('目标帧率:', self.fps_edit)
# 最大宽度 - 使用QLineEdit并添加整数验证
self.width_edit = QLineEdit()
self.width_edit.setText(str(MAX_WIDTH))
self.width_edit.setValidator(QIntValidator(320, 4096)) # 限制320-4096之间的整数
video_layout.addRow('最大宽度:', self.width_edit)
video_group.setLayout(video_layout)
main_layout.addWidget(video_group)
# 网络参数分组
network_group = QGroupBox("网络参数设置")
network_layout = QFormLayout()
network_layout.setRowWrapPolicy(QFormLayout.DontWrapRows)
network_layout.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)
network_layout.setLabelAlignment(Qt.AlignLeft)
network_layout.setVerticalSpacing(10)
# STUN端口
self.stun_port_edit = QLineEdit()
self.stun_port_edit.setText(str(STUN_PORT))
self.stun_port_edit.setValidator(QIntValidator(1, 65535)) # 限制1-65535之间的整数
network_layout.addRow('STUN端口:', self.stun_port_edit)
# Web端口
self.web_port_edit = QLineEdit()
self.web_port_edit.setText(str(WEB_PORT))
self.web_port_edit.setValidator(QIntValidator(1, 65535)) # 限制1-65535之间的整数
network_layout.addRow('Web端口:', self.web_port_edit)
# IPv4/IPv6设置
ip_layout = QHBoxLayout()
self.ipv4_check = QCheckBox("启用IPv4")
self.ipv4_check.setChecked(enable_ipv4)
self.ipv6_check = QCheckBox("启用IPv6")
self.ipv6_check.setChecked(enable_ipv6)
ip_layout.addWidget(self.ipv4_check)
ip_layout.addWidget(self.ipv6_check)
ip_layout.addStretch()
network_layout.addRow('网络协议:', ip_layout)
network_group.setLayout(network_layout)
main_layout.addWidget(network_group)
# 认证与存储分组
auth_group = QGroupBox("认证与存储设置")
auth_layout = QFormLayout()
auth_layout.setRowWrapPolicy(QFormLayout.DontWrapRows)
auth_layout.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)
auth_layout.setLabelAlignment(Qt.AlignLeft)
auth_layout.setVerticalSpacing(10)
self.username_edit = QLineEdit()
self.username_edit.setText(users[0])
auth_layout.addRow('用户名:', self.username_edit)
self.password_edit = QLineEdit()
self.password_edit.setEchoMode(QLineEdit.Password)
self.password_edit.setText(users[1])
auth_layout.addRow('密码:', self.password_edit)
folder_layout = QHBoxLayout()
self.folder_edit = QLineEdit()
self.folder_edit.setText(UPLOAD_FOLDER)
self.browse_btn = QPushButton('浏览...')
self.browse_btn.setObjectName("browseBtn")
self.browse_btn.clicked.connect(self.browse_folder)
folder_layout.addWidget(self.folder_edit)
folder_layout.addWidget(self.browse_btn)
auth_layout.addRow('上传文件夹:', folder_layout)
auth_group.setLayout(auth_layout)
main_layout.addWidget(auth_group)
# 功能选项分组
features_group = QGroupBox("功能选项设置")
features_layout = QGridLayout()
features_layout.setSpacing(10)
self.download_check = QCheckBox("允许文件下载")
self.download_check.setChecked(enable_file_download)
features_layout.addWidget(self.download_check, 0, 0)
self.upload_check = QCheckBox("允许文件上传")
self.upload_check.setChecked(enable_file_upload)
features_layout.addWidget(self.upload_check, 0, 1)
self.video_check = QCheckBox("启用视频功能")
self.video_check.setChecked(enable_video)
features_layout.addWidget(self.video_check, 1, 0)
self.control_check = QCheckBox("启用控制功能")
self.control_check.setChecked(enable_control)
features_layout.addWidget(self.control_check, 1, 1)
features_group.setLayout(features_layout)
main_layout.addWidget(features_group)
# 基础显示控件(可复制但不可修改)
display_group = QGroupBox("网络地址显示")
display_layout = QVBoxLayout()
display_group.setFixedHeight(130)
# 创建只读文本编辑框
self.info_display = QTextEdit()
self.info_display.setReadOnly(True) # 设置为只读
self.info_display.setFixedHeight(40)
# 复制按钮
copy_layout = QHBoxLayout()
self.copy_btn = QPushButton("复制内容")
self.copy_btn.setObjectName("copyBtn")
self.copy_btn.clicked.connect(self.copy_content)
copy_layout.addWidget(self.copy_btn)
copy_layout.addStretch()
display_layout.addWidget(self.info_display)
display_layout.addLayout(copy_layout)
display_group.setLayout(display_layout)
main_layout.addWidget(display_group)
# 启动按钮
self.status_label = QLabel('')
self.status_label.setAlignment(Qt.AlignCenter)
self.status_label.setStyleSheet("""
color: #2c3e50;
padding: 8px;
border-radius: 4px;
background-color: #ecf0f1;
""")
main_layout.addWidget(self.status_label)
btn_layout = QHBoxLayout()
btn_layout.setSpacing(15)
self.save_btn = QPushButton('保存配置')
self.save_btn.clicked.connect(self.save_config_txt)
btn_layout.addWidget(self.save_btn)
self.start_btn = QPushButton('启动程序')
self.start_btn.setObjectName("startBtn")
self.start_btn.clicked.connect(self.start_program)
btn_layout.addWidget(self.start_btn)
btn_layout.addStretch()
main_layout.addLayout(btn_layout)
def browse_folder(self):
folder = QFileDialog.getExistingDirectory(self, "选择上传文件夹", UPLOAD_FOLDER)
if folder:
self.folder_edit.setText(folder)
def save_config(self):
global TARGET_FPS, MAX_WIDTH, STUN_PORT, WEB_PORT, users
global enable_file_download, enable_file_upload, enable_video
global enable_control, enable_ipv4, enable_ipv6, UPLOAD_FOLDER
# 从文本框获取值时需要转换为整数
try:
TARGET_FPS = int(self.fps_edit.text())
MAX_WIDTH = int(self.width_edit.text())
STUN_PORT = int(self.stun_port_edit.text())
WEB_PORT = int(self.web_port_edit.text())
users = (self.username_edit.text(), self.password_edit.text())
enable_file_download = self.download_check.isChecked()
enable_file_upload = self.upload_check.isChecked()
enable_video = self.video_check.isChecked()
enable_control = self.control_check.isChecked()
enable_ipv4 = self.ipv4_check.isChecked()
enable_ipv6 = self.ipv6_check.isChecked()
UPLOAD_FOLDER = self.folder_edit.text()
self.status_label.setStyleSheet("""
color: #27ae60;
padding: 8px;
border-radius: 4px;
background-color: #eafaf1;
font-weight: bold;
""")
except ValueError:
self.status_label.setText('输入错误,请检查数字参数')
self.status_label.setStyleSheet("""
color: #e74c3c;
padding: 8px;
border-radius: 4px;
background-color: #fdedeb;
font-weight: bold;
""")
def save_config_txt(self):
self.save_config()
config_file = open('config.txt','w')
config_file.write(f'''
TARGET_FPS = {TARGET_FPS}
MAX_WIDTH = {MAX_WIDTH}
STUN_PORT = {STUN_PORT}
WEB_PORT = {WEB_PORT}
users = (\"{users[0]}\", \"{users[1]}\")
enable_file_download = {enable_file_download}
enable_file_upload = {enable_file_upload}
enable_video = {enable_video}
enable_control = {enable_control}
enable_ipv4 = {enable_ipv4}
enable_ipv6 = {enable_ipv6}
UPLOAD_FOLDER = \"{UPLOAD_FOLDER}\"
'''.replace(' ','').strip('\n'))
config_file.close()
self.status_label.setText('配置已保存')
def start_program(self):
# 先尝试保存配置
try:
# 验证输入是否有效
int(self.fps_edit.text())
int(self.width_edit.text())
int(self.stun_port_edit.text())
int(self.web_port_edit.text())
self.save_config()
self.status_label.setText('程序正在启动...')
self.status_label.setStyleSheet("""
color: #f39c12;
padding: 8px;
border-radius: 4px;
background-color: #fef5e7;
font-weight: bold;
""")
threading.Thread(target=main, daemon=True).start()
self.status_label.setText('程序已启动')
self.status_label.setStyleSheet("""
color: #27ae60;
padding: 8px;
border-radius: 4px;
background-color: #eafaf1;
font-weight: bold;
""")
# 显示网络地址
def get_address():
result = subprocess.run(['ipconfig'], capture_output=True, text=True, check=True)
lines = result.stdout.split('\n')
address4 = '127.0.0.1'
address6 = '[::1]'
for line in lines:
if ('192.' in line) and ('IPv4 地址' in line):
address4 = line.split(': ')[-1].strip()
if '临时 IPv6 地址' in line:
address6 = '['+line.split(': ')[-1].strip()+']'
return [address4,address6]
address = get_address()
self.set_display_text('https://' + address[0] + ':' + str(WEB_PORT) + '\n'+
'https://' + address[1] + ':' + str(WEB_PORT))
except ValueError:
self.status_label.setText('输入错误,无法启动程序')
self.status_label.setStyleSheet("""
color: #e74c3c;
padding: 8px;
border-radius: 4px;
background-color: #fdedeb;
font-weight: bold;
""")
# 设置显示内容的方法
def set_display_text(self, text):
self.info_display.setText(text)
# 追加显示内容的方法
def append_display_text(self, text):
self.info_display.append(text)
# 复制当前显示的内容
def copy_content(self):
text = self.info_display.toPlainText()
if text:
clipboard = QApplication.clipboard()
clipboard.setText(text)
self.status_label.setText('内容已复制到剪贴板')
self.status_label.setStyleSheet("""
color: #f39c12;
padding: 8px;
border-radius: 4px;
background-color: #fef5e7;
font-weight: bold;
""")
if __name__ == '__main__':
app = QApplication(sys.argv)
window = ConfigWindow()
window.show()
sys.exit(app.exec_())
|
2301_80130186/ipv6
|
隧影0.3.0.py
|
Python
|
mit
| 56,440
|
FROM python:3.10-slim
WORKDIR /app
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
COPY main.py ./
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
|
2301_80138456/bilibili-download-web
|
backend/Dockerfile
|
Dockerfile
|
unknown
| 195
|
from fastapi import FastAPI, Query, HTTPException, Response
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import StreamingResponse
import requests
import re
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
# 定义请求头
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/108.0.0.0 Safari/537.36",
"Referer": "https://www.bilibili.com/"
}
# 提取视频 ID
def extract_id(url: str):
# 提取 BVID
m = re.search(r"BV[0-9A-Za-z]+", url)
if m:
return {"type": "bvid", "id": m.group(0)}
# 提取 AV 号
m2 = re.search(r"av(\d+)", url)
if m2:
return {"type": "aid", "id": m2.group(1)}
# 短链处理
if "b23.tv" in url:
try:
# 使用定义的请求头处理短链接跳转
r = requests.get(url, allow_redirects=True, timeout=8, headers=headers)
return extract_id(r.url)
except Exception:
return None
return None
@app.get("/api/info")
def info(url: str = Query(..., description="B站视频链接")):
parsed = extract_id(url)
if not parsed:
raise HTTPException(status_code=400, detail=f"无法提取视频 ID: {url}")
api = "https://api.bilibili.com/x/web-interface/view"
params = {parsed["type"]: parsed["id"]}
# 使用请求头获取视频信息
r = requests.get(api, params=params, timeout=8, headers=headers)
try:
j = r.json()
except Exception:
raise HTTPException(status_code=502, detail="B站 API 响应异常")
if j.get("code") != 0:
raise HTTPException(status_code=502, detail=f"view 接口错误: {j.get('message')}")
data = j["data"]
title = data.get("title")
bvid = data.get("bvid")
pages = data.get("pages", [])
if not pages:
raise HTTPException(status_code=502, detail="未找到视频页")
# 返回所有分 P 信息
parts = [{"cid": p["cid"], "part": p["part"]} for p in pages]
return {"title": title, "bvid": bvid, "parts": parts}
@app.get("/api/playurl")
def playurl(bvid: str, cid: int, qn: int = 80):
"""获取视频播放直链,qn: 清晰度(16=360p,32=480p,64=720p,80=1080p,116=1080p+)"""
play_api = "https://api.bilibili.com/x/player/playurl"
params = {"bvid": bvid, "cid": cid, "qn": qn, "otype": "json"}
# 使用请求头获取播放链接
r = requests.get(play_api, params=params, timeout=8, headers=headers)
pj = r.json()
if pj.get("code") != 0:
raise HTTPException(status_code=502, detail=f"playurl 接口错误: {pj.get('message')}")
play_data = pj.get("data", {})
urls = []
if play_data.get("durl"):
urls = [d.get("url") for d in play_data["durl"] if d.get("url")]
elif play_data.get("dash"):
videos = play_data["dash"].get("video", [])
if videos:
urls.append(videos[0].get("baseUrl"))
return {"urls": urls}
@app.get("/api/download")
def download(bvid: str, cid: int, qn: int = 80):
try:
play = playurl(bvid, cid, qn)
if not play["urls"]:
raise HTTPException(status_code=502, detail="未找到下载链接(可能需要登录 Cookie)")
play_url = play["urls"][0]
# 重新定义本地请求头(避免和全局 headers 冲突)
dl_headers = {
"User-Agent": headers["User-Agent"],
"Referer": headers["Referer"],
}
r = requests.get(play_url, stream=True, timeout=30, headers=dl_headers)
def iter_stream():
try:
for chunk in r.iter_content(1024 * 64):
if chunk:
yield chunk
finally:
r.close()
return StreamingResponse(
iter_stream(),
media_type="video/mp4",
headers={
"Content-Disposition": f'attachment; filename=\"{bvid}_{cid}.mp4\"'
},
)
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=f"下载失败: {str(e)}")
|
2301_80138456/bilibili-download-web
|
backend/main.py
|
Python
|
unknown
| 4,265
|
<!-- SUWJTech -->
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>B站视频下载器</title>
<style>
/* 全局样式重置与基础设置 */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
transition: all 0.3s ease;
}
body {
font-family: "Microsoft YaHei", "PingFang SC", sans-serif;
background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
min-height: 100vh;
padding: 20px;
display: flex;
flex-direction: column;
align-items: center;
}
/* 容器样式 - 卡片化设计 */
.container {
width: 100%;
max-width: 800px;
background: #fff;
border-radius: 12px;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
padding: 30px;
margin-top: 50px;
}
/* 标题样式 */
.page-title {
color: #fb7299;
/* B站粉色系 */
text-align: center;
margin-bottom: 30px;
font-size: 24px;
font-weight: 600;
display: flex;
align-items: center;
justify-content: center;
}
.page-title::before,
.page-title::after {
content: "";
width: 40px;
height: 2px;
background: #fb7299;
margin: 0 15px;
}
/* 输入框与按钮区域 */
.input-group {
display: flex;
gap: 15px;
margin-bottom: 30px;
}
#url {
flex: 1;
padding: 12px 18px;
border: 2px solid #e5e6eb;
border-radius: 8px;
font-size: 16px;
outline: none;
}
#url:focus {
border-color: #00a1d6;
/* B站蓝色系 */
box-shadow: 0 0 0 3px rgba(0, 161, 214, 0.1);
}
#url::placeholder {
color: #c9cdcf;
}
/* 按钮通用样式 */
.btn {
padding: 12px 24px;
border: none;
border-radius: 8px;
font-size: 16px;
font-weight: 500;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
}
.btn-primary {
background: #00a1d6;
color: #fff;
}
.btn-primary:hover {
background: #0086b3;
transform: translateY(-2px);
}
.btn-primary:active {
transform: translateY(0);
}
.btn-download {
background: #f47521;
/* B站橙色系 */
color: #fff;
padding: 8px 16px;
font-size: 14px;
}
.btn-download:hover {
background: #e06818;
transform: translateY(-1px);
}
/* 清晰度选择框样式 */
.quality-select {
padding: 6px 10px;
border: 1px solid #e5e6eb;
border-radius: 6px;
font-size: 14px;
color: #4e5969;
background-color: #fff;
outline: none;
}
.quality-select:focus {
border-color: #00a1d6;
}
/* 视频信息展示区域 */
#info {
width: 100%;
}
.video-title {
color: #333;
font-size: 20px;
margin-bottom: 20px;
padding-bottom: 10px;
border-bottom: 1px solid #f0f0f0;
}
.video-parts {
display: flex;
flex-direction: column;
gap: 12px;
}
.part-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 12px 18px;
background: #f9fafc;
border-radius: 8px;
}
.part-name {
color: #4e5969;
font-size: 16px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
/* 加载状态提示 */
.loading {
color: #00a1d6;
text-align: center;
padding: 20px;
font-size: 16px;
}
/* 错误提示样式 */
.error {
color: #f53f3f;
text-align: center;
padding: 20px;
font-size: 16px;
background: #fff2f2;
border-radius: 8px;
}
/* 响应式适配 - 手机端 */
@media (max-width: 768px) {
.container {
padding: 20px;
margin-top: 30px;
}
.page-title {
font-size: 20px;
}
.page-title::before,
.page-title::after {
width: 30px;
}
.input-group {
flex-direction: column;
gap: 10px;
}
.btn {
padding: 12px;
}
.part-item {
flex-direction: column;
align-items: flex-start;
gap: 10px;
}
.part-name {
white-space: normal;
line-height: 1.5;
}
.btn-download {
align-self: flex-end;
}
}
</style>
</head>
<body>
<div class="container">
<h2 class="page-title">B站视频下载</h2>
<div class="input-group">
<input id="url" placeholder="请输入B站视频链接(支持BV号/AV号链接)" type="text" />
<button class="btn btn-primary" onclick="getInfo()">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path
d="M11 19C15.4183 19 19 15.4183 19 11C19 6.58172 15.4183 3 11 3C6.58172 3 3 6.58172 3 11C3 15.4183 6.58172 19 11 19Z"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
<path d="M21 21L16.65 16.65" stroke="currentColor" stroke-width="2" stroke-linecap="round"
stroke-linejoin="round" />
</svg>
解析视频
</button>
</div>
<div id="info"></div>
</div>
<script>
const apiBase = 'http://localhost:8000/api';
async function getInfo() {
const urlInput = document.getElementById('url');
const url = urlInput.value.trim();
const infoContainer = document.getElementById('info');
// 1. 输入校验
if (!url) {
alert('请输入视频链接');
urlInput.focus();
return;
}
// 2. 显示加载状态
infoContainer.innerHTML = `
<div class="loading">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" class="animate-spin">
<path d="M12 5V19" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M19 12H5" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M5.636 5.636L18.364 18.364" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M18.364 5.636L5.636 18.364" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
正在解析视频信息...
</div>
`;
try {
// 3. 调用接口获取数据
const res = await fetch(`${apiBase}/info?url=${encodeURIComponent(url)}`);
if (!res.ok) throw new Error('解析失败,请检查链接是否有效');
const j = await res.json();
// 4. 渲染视频信息(包含清晰度选择)
infoContainer.innerHTML = `
<h3 class="video-title">${j.title}</h3>
<div class="video-parts">
${j.parts.map(p => `
<div class="part-item">
<span class="part-name">${p.part}</span>
<div style="display: flex; align-items: center; gap: 8px;">
<select class="quality-select" data-bvid="${j.bvid}" data-cid="${p.cid}">
<option value="16">360p</option>
<option value="32">480p</option>
<option value="64">720p</option>
<option value="80" selected>1080p</option>
<option value="116">1080p+</option>
</select>
<button class="btn btn-download" onclick="download('${j.bvid}', ${p.cid}, this.previousElementSibling.value)">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M21 15V19C21 19.5304 20.7893 20.0391 20.4142 20.4142C20.0391 20.7893 19.5304 21 19 21H5C4.46957 21 3.96086 20.7893 3.58579 20.4142C3.21071 20.0391 3 19.5304 3 19V15" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M17 8L12 3L7 8" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M12 3V15" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
下载
</button>
</div>
</div>
`).join('')}
</div>
`;
} catch (err) {
// 5. 错误处理
infoContainer.innerHTML = `<div class="error">${err.message}</div>`;
}
}
function download(bvid, cid, qn) {
// 传递清晰度参数qn
window.open(`${apiBase}/download?bvid=${bvid}&cid=${cid}&qn=${qn}`, '_blank');
}
// 支持回车键触发解析
document.getElementById('url').addEventListener('keydown', (e) => {
if (e.key === 'Enter') getInfo();
});
</script>
</body>
</html>
|
2301_80138456/bilibili-download-web
|
frontend/index.html
|
HTML
|
unknown
| 8,994
|
module.exports = {
presets: [
'@vue/cli-plugin-babel/preset'
]
}
|
2301_79970562/student_union_frontend
|
babel.config.js
|
JavaScript
|
unknown
| 81
|
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta content="IE=edge" http-equiv="X-UA-Compatible">
<meta content="width=device-width,initial-scale=1.0" name="viewport">
<link href="<%= BASE_URL %>favicon.ico" rel="icon">
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
<noscript>
<strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled.
Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
|
2301_79970562/student_union_frontend
|
public/index.html
|
HTML
|
unknown
| 593
|
<template>
<div class="app" v-title title="房屋租赁管理系统"></div>
<div>
<router-view/>
</div>
</template>
<style>
</style>
<script>
export default {
name: "Layout",
}
</script>
|
2301_79970562/student_union_frontend
|
src/App.vue
|
Vue
|
unknown
| 204
|
.wv-lt-refresh {
display: none;
}
.topInfo {
margin: 0 auto;
}
.el-colDiv {
margin: 20px auto;
max-width: 340px;
min-width: 200px;
overflow: hidden;
height: 115px;
border-radius: 5px;
background-color: black;
color: white;
padding-left: 15px;
padding-top: 15px;
position: relative;
}
.el-colDiv:hover {
cursor: pointer;
background-position: right;
}
.nowDiv {
width: 38px;
height: 19px;
position: absolute;
right: 5%;
font-size: 15px;
display: flex;
justify-content: center;
align-items: center;
border-radius: 3px;
}
.digital {
font-size: 25px;
line-height: normal;
margin-left: 2px;
}
.title {
font-size: 18px;
}
.last-span {
font-size: 13px;
}
#tenant {
background-image: linear-gradient(to left, #FFC312, #EE5A24, #FFC312);
background-size: 200%;
transition: 0.5s;
}
#landlord {
background-image: linear-gradient(to left, #C4E538, #009432, #C4E538);
background-size: 200%;
transition: 0.5s;
}
#house {
background-image: linear-gradient(to left, #12CBC4, #0652DD, #12CBC4);
background-size: 200%;
transition: 0.5s;
}
#charts {
background-image: linear-gradient(to left, #FDA7DF, #9980FA, #FDA7DF);
background-size: 200%;
transition: 0.6s;
}
#ssv1-main-text {
background-color: #1398ff;
}
#ssv2-main-text {
background-color: #2e4057;
}
#ssv3-main-text {
background-color: #ffb400;
}
#ssv4-main-text {
background-color: #008789;
}
|
2301_79970562/student_union_frontend
|
src/assets/css/AdminHome.css
|
CSS
|
unknown
| 1,530
|
.login-container {
height: 100%;
position: fixed;
top: 0;
left: 0;
transform: translate(-50%, -50%);
display: flex;
justify-content: center;
align-items: center;
}
@keyframes myanimation {
0% {
background-position: 0% 50%;
}
50% {
background-position: 0% 50%;
}
100% {
background-position: 0% 50%;
}
}
|
2301_79970562/student_union_frontend
|
src/assets/css/Login.css
|
CSS
|
unknown
| 381
|
@import url('https://fonts.googleapis.com/css2?family=Poppins&display=swap');
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Poppins', sans-serif;
}
|
2301_79970562/student_union_frontend
|
src/assets/css/global.css
|
CSS
|
unknown
| 183
|
import request from "@/axios/request";
import { ElMessage } from "element-plus";
export default {
name: "AdminAuditionHouseDisplay",
data() {
return {
loading: true,
Data: {},
isFavorited: false,
tenantId: '',
comments: [], // 存储当前房源的评论列表
userMap: {},
commentCount: 0, // 评论数量
rating: 0, // 评分
colors: ['#99A9BF', '#F7BA1E', '#FF9900'] ,// 评分星星的颜色,2,3,4是颜色分界
// 状态映射
statusMap: {
rented: { text: '已租', type: 'info' },
available: { text: '待租', type: 'success' },
pending: { text: '审核中', type: 'warning' },
rejected: { text: '审核未通过', type: 'danger' }
},
};
},
created() {
const houseId = this.$route.query.houseId;
this.load(houseId);
this.loadComments(houseId);
this.loading = true;
//获取当前登录用户ID(TenantSelfInfo)
const userInfo = JSON.parse(window.sessionStorage.getItem('userInfo') || '{}');
this.tenantId = userInfo.tenantId || ''; // 从sessionStorage中提取tenantId
this.loadFavoriteStatus(houseId,this.tenantId);
},
methods: {
// 房屋详情
async load(houseId) {
this.loading = true;
try{
const res = await request.get(`/house/${houseId}`);
if (res.code === 200) {
// 保留原始状态码,新增 displayStatus 字段用于显示
this.Data = res.data;
this.Data.displayStatus = this.statusMap[this.Data.status]?.text || '未知状态';
}else {
ElMessage.error(res.msg || "加载失败");
this.Data = {};
}
} catch (err){
console.error(err);
ElMessage.error("网络错误,请稍后再试");
} finally {
this.loading = false; // 接口请求完成后关闭loading
}
},
// 评论列表
async loadComments(houseId) {
try {
// 先清空旧数据
this.userMap = {};
this.comments = [];
this.commentCount = 0;
const res = await request.get(`/comment/house/${houseId}`);
// 如果接口调用失败,直接提示并 return
if (res.code !== 200) {
// ElMessage.error(res.msg || '加载评论失败');
return;
}
// 此时 res.code === 200
const list = Array.isArray(res.data) ? res.data : [];
// 只有在确实有评论时才去拉用户名
if (list.length > 0) {
// 并行请求所有用户名
await Promise.all(
list.map(async (comment) => {
try {
const userRes = await request.get(`/tenant/findById/${comment.tenantId}`);
// 强制转成字符串 key,以防类型不一致
this.userMap[String(comment.tenantId)] = (userRes.code === 200 && userRes.data.username) || '匿名用户';
} catch {
this.userMap[String(comment.tenantId)] = '匿名用户';
}
})
);
}
// 最后赋值评论列表
this.comments = list;
this.commentCount = list.length;
} catch (err) {
console.error("加载评论失败:", err);
ElMessage.error("加载评论失败,请稍后重试");
}
},
//时间显示
formatDate(dateStr) {
if (!dateStr) return "";
const date = new Date(dateStr);
return date.toLocaleString("zh-CN", {
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
});
},
async loadFavoriteStatus(houseId, tenantId) {
try {
const res = await request.post(`/favorite/tenantAndHouse` ,{
tenantId: tenantId,
houseId: houseId
});
if (res.code === 200) {
this.isFavorited = true;
}else if (res.code === 404) {
this.isFavorited = false;
}
} catch (err) {
console.error("获取收藏状态失败:", err);
}
},
// 切换收藏/取消收藏
async handleFavorite() {
// 先乐观更新
try {
if (this.isFavorited) {
await request.delete("/favorite/cancel", {
data: {
houseId: this.Data.houseId,
tenantId: this.tenantId
}
});
}else {
await request.post("/favorite/add", {
houseId: this.Data.houseId,
tenantId: this.tenantId
});
}
console.log(this.tenantId);
this.isFavorited = !this.isFavorited;
ElMessage.success(this.isFavorited ? "已收藏" : "已取消收藏");
} catch (err) {
// 回滚
this.isFavorited = !this.isFavorited;
console.error(err);
ElMessage.error("操作失败,请重试");
}
},
// 提交评论
async subComment() {
// 判断用户是否评论过
const hasCommented = this.comments.some(
comment => String(comment.tenantId) === String(this.tenantId)//判断用户名是否已存在
);
if (hasCommented) {
ElMessage.warning('用户仅允许提交一次评论');
this.commentContent = '';
this.rating = 0;
return;
}
try {
// 构建评论数据
const commentData = {
houseId: this.$route.query.houseId,
tenantId: this.tenantId,
content: this.commentContent.trim(),
rating: this.rating
};
// 调用后端接口
const res = await request.post(`/comment/add`, commentData);
if (res.code === 200) {
// 评论成功
ElMessage.success('评论提交成功');
// 清空表单
this.commentContent = '';
this.rating = 0;
// 刷新评论列表
await this.loadComments(this.$route.query.houseId);
} else {
// 评论失败
ElMessage.error(res.msg || '评论提交失败');
}
} catch (err) {
console.error("提交评论错误:", err);
ElMessage.error('网络错误,请稍后再试');
}
},
async subapplication(){
//判断房源的状态
const res = await request.get(`/house/${this.Data.houseId}`);
if (res.code === 200 && res.data.status !== "available") {
ElMessage.warning('该房源已不可申请');
return;
}
try {
//申请数据
const res = await request.post(`/rental/apply`, {
houseId: this.Data.houseId,
tenantId: this.tenantId,
type: "in",
});
if (res.code === 200) {
ElMessage.success('申请提交成功');
} else {
ElMessage.error(res.msg || '申请提交失败');
}
} catch (err) {
console.error("提交申请错误:", err);
ElMessage.error('网络错误,请稍后再试');
}
},
// 状态标签类型获取方法
getStatusTagType(status) {
return this.statusMap[status]?.type || '';
},
// 状态标签文本获取方法
getStatusLabel(status) {
return this.statusMap[status]?.text || '未知状态';
}
},
};
|
2301_79970562/student_union_frontend
|
src/assets/js/AdminAuditionHouseDisplay.js
|
JavaScript
|
unknown
| 8,868
|
import request from "@/axios/request";
import DataCharts from "@/components/DataCharts";
export default {
name: "AdminHome",
components: {
DataCharts
},
data() {
return {
// 所有原始数据
allData: [],
// 当前页数据
tableData: [],
// 当前页码
currentPage: 1,
// 每页条数
pageSize: 5,
currentTab: 'tenant',
loading: false,
showCharts: false,
chartsOptions: []
};
},
computed: {
paginatedData() {
const start = (this.currentPage - 1) * this.pageSize;
const end = start + this.pageSize;
return this.allData.slice(start, end);
}
},
created() {
this.fetchTableData('tenant');
},
methods: {
async fetchTableData(type) {
let url = "";
switch (type) {
case "tenant":
url = "/tenant/findAll";
break;
case "landlord":
url = "/landlord/findAll";
break;
case "house":
url = "/house/findAll";
break;
default:
return;
}
this.loading = true;
this.allData = [];
this.tableData = [];
this.currentTab = type;
this.currentPage = 1;
try {
const res = await request.get(url);
if (res.code === 200) {
this.allData = res.data || [];
this.tableData = this.paginatedData;
this.currentTab = type;
this.currentPage = 1;
} else {
ElMessage.error(res.msg || "获取数据失败");
}
} catch (err) {
ElMessage.error("网络错误,请稍后再试");
console.error(err);
} finally {
this.loading = false;
}
},
handleSizeChange(pageSize) {
this.pageSize = pageSize;
this.tableData = this.paginatedData;
},
handlePageChange(page) {
this.currentPage = page;
this.tableData = this.paginatedData;
},
// 创建图表
async createDataCharts() {
this.currentTab = "charts";
this.showCharts = false;
try {
const [tenantRes, landlordRes, houseRes, applicationRes, commentRes, favoriteRes] = await Promise.all([
request.get("/tenant/findAll"), // 租客
request.get("/landlord/findAll"), // 房东
request.get("/house/findAll"), // 房源
request.get("/rental/findAll"), // 出租申请
request.get("/comment/findAll"), // 评论
request.get("/favorite/findAll") // 收藏
]);
const houses = houseRes.data || [];
const tenants = tenantRes.data || [];
const landlords = landlordRes.data || [];
const applications = applicationRes.data || [];
const comments = commentRes.data || [];
const favorites = favoriteRes.data || [];
// 统计各地区房源数量
const areaStats = {};
houses.forEach(house => {
const area = house.area;
if (area) {
areaStats[area] = (areaStats[area] || 0) + 1;
}
});
this.applicationCount = applications.length;
this.commentCount = comments.length;
this.favoriteCount = favorites.length;
const userChart = this.createUserPieChart(tenants.length, landlords.length);
const priceChart = this.createPriceBarChart(houses);
const areaChart = this.createAreaPieChart(houses);
const statusChart = this.createStatusBarChart(houses);
const statsChart = this.createStatsBarChart();
const mapChart = this.createMapChart(areaStats);
this.chartsOptions = [userChart, priceChart, areaChart, statusChart, statsChart, mapChart];
this.showCharts = true;
} catch (err) {
console.error("图表加载失败", err);
this.$message.error("图表加载失败");
this.chartsOptions = [
this.createUserPieChart(0, 0),
this.createPriceBarChart([]),
this.createAreaPieChart([]),
this.createStatusBarChart([]),
this.createStatsBarChart(),
this.createMapChart({})
];
this.showCharts = true;
}
},
// 用户总数嵌套饼图
createUserPieChart(tenantCount, landlordCount) {
return {
type: 'pie',
width: '600px',
height: '400px',
option: {
title: {
text: '用户总人数分布',
left: 'center'
},
tooltip: {
trigger: 'item',
formatter: '{a} <br/>{b}: {c}人 ({d}%)'
},
series: [
{
name: '用户类型',
type: 'pie',
radius: ['40%', '70%'],
avoidLabelOverlap: false,
label: { show: false },
emphasis: {
label: {
show: true,
fontSize: '20',
fontWeight: 'bold'
}
},
data: [
{ value: tenantCount, name: '租客', itemStyle: { color: '#FFA726' } },
{ value: landlordCount, name: '房东', itemStyle: { color: '#42A5F5' } }
]
},
{
name: '总人数',
type: 'pie',
radius: ['0%', '30%'],
label: { show: false },
data: [{ value: tenantCount + landlordCount, name: '总人数', itemStyle: { color: '#66BB6A' } }],
emphasis: {
label: {
show: true,
position: 'center',
textStyle: {
fontSize: '20',
fontWeight: 'normal'
}
}
}
}
]
}
};
},
// 房源价格柱状图
createPriceBarChart(houses) {
const low = houses.filter(h => h.price >= 1000 && h.price <= 5000).length;
const mid = houses.filter(h => h.price > 5000 && h.price <= 10000).length;
const high = houses.filter(h => h.price > 10000 && h.price <= 100000).length;
console.log(low, mid, high);
return {
type: 'bar',
width: '600px',
height: '400px',
option: {
title: { text: '房源价格区间分布', left: 'center' },
tooltip: {},
xAxis: {
type: 'category',
data: ['低价房源', '中价房源', '高价房源']
},
yAxis: { type: 'value' },
series: [{
name: '数量',
type: 'bar',
data: [low, mid, high],
itemStyle: { color: "#AB47BC" }
}]
}
};
},
// 房屋面积饼图
createAreaPieChart(houses) {
const small = houses.filter(h => h.size <= 50).length;
const medium = houses.filter(h => h.size > 50 && h.size <= 100).length;
const large = houses.filter(h => h.size > 100).length;
return {
type: 'pie',
width: '600px',
height: '400px',
option: {
title: { text: '房屋面积分布', left: 'center' },
tooltip: { trigger: 'item' },
legend: { top: '10%', left: 'right' },
series: [{
name: '面积分布',
type: 'pie',
radius: '60%',
data: [
{ value: small, name: '小面积', itemStyle: { color: '#26A69A' } },
{ value: medium, name: '中面积', itemStyle: { color: '#29B6F6' } },
{ value: large, name: '大面积', itemStyle: { color: '#FF7043' } }
],
emphasis: {
itemStyle: {
shadowBlur: 10,
shadowColor: 'rgba(0, 0, 0, 0.5)'
}
}
}]
}
};
},
// 房源状态柱状图
createStatusBarChart(houses) {
const available = houses.filter(h => h.status === 'available').length;
const rented = houses.filter(h => h.status === 'rented').length;
const pending = houses.filter(h => h.status === 'pending').length;
const rejected = houses.filter(h => h.status === 'rejected').length;
return {
type: 'bar',
width: '600px',
height: '400px',
option: {
title: { text: '房源状态统计', left: 'center' },
tooltip: {},
xAxis: {
type: 'category',
data: ['可租', '已租', '待审核', '已拒绝']
},
yAxis: { type: 'value' },
series: [{
name: '数量',
type: 'bar',
data: [available, rented, pending, rejected],
itemStyle: { color: '#EC407A' }
}]
}
};
},
// 出租申请、评论、收藏统计图
createStatsBarChart() {
return {
type: 'bar',
width: '600px',
height: '400px',
option: {
title: { text: '网站热度指标统计', left: 'center' },
tooltip: {},
xAxis: {
type: 'category',
data: ['出租申请', '评论', '收藏']
},
yAxis: { type: 'value' },
series: [{
name: '数量',
type: 'bar',
data: [this.applicationCount, this.commentCount, this.favoriteCount],
itemStyle: { color: '#26A69A' }
}]
}
};
},
// 地图热力图
createMapChart(areaStats) {
console.log(areaStats);
// const data = Object.entries(areaStats || {}).map(([name, value]) => ({ name, value }));
const data = Object.entries(areaStats).map(([name, value]) => ({ name, value }));
// const rawData = Object.entries( {
// 北京市: 100,
// 天津市: 80,
// 河北省: 60,
// 山西省: 40,
// 内蒙古自治区: 20,
// 辽宁省: 10,
// 吉林省: 5,
// 黑龙江省: 0,
// 上海市: 90,
// 江苏省: 80,
// 浙江省: 70,
// 安徽省: 60,
// 福建省: 50,
// 江西省: 40,
// 山东省: 30,
// 河南省: 20,
// 湖北省: 10,
// 湖南省: 5,
// 广东省: 80,
// 广西壮族自治区: 70,
// 海南省: 60,
// 重庆市: 90,
// 四川省: 50,
// 贵州省: 40,
// 云南省: 30,
// 西藏自治区: 20,
// 陕西省: 10,
// 甘肃省: 5,
// 青海省: 0,
// 宁夏回族自治区: 90,
// 新疆维吾尔自治区: 80,
// 台湾省: 80,
// 香港特别行政区: 70,
// 澳门特别行政区: 60
// } );
// const data = [
// { name: '北京市', value: 100, },
// { name: '天津市', value: 80, },
// { name: '河北省', value: 60, },
// { name: '山西省', value: 40, },
// { name: '内蒙古自治区', value: 20, },
// { name: '辽宁省', value: 10, },
// { name: '吉林省', value: 5, },
// { name: '黑龙江省', value: 0, },
// { name: '上海市', value: 90, },
// { name: '江苏省', value: 80, },
// { name: '浙江省', value: 70, },
// { name: '安徽省', value: 60, },
// { name: '福建省', value: 50, },
// { name: '江西省', value: 40, },
// { name: '山东省', value: 30, },
// { name: '河南省', value: 20, },
// { name: '湖北省', value: 10, },
// { name: '湖南省', value: 5, },
// { name: '广东省', value: 0, },
// { name: '广西壮族自治区', value: 90, },
// { name: '重庆市', value: 70, },
// { name: '四川省', value: 60, },
// { name: '贵州省', value: 50, },
// { name: '云南省', value: 40, },
// { name: '西藏自治区', value: 30, },
// { name: '陕西省', value: 20, },
// { name: '甘肃省', value: 10, },
// { name: '青海省', value: 5, },
// { name: '宁夏回族自治区', value: 0, },
// { name: '新疆维吾尔自治区', value: 90, },
// { name: '台湾省', value: 80, },
// { name: '香港特别行政区', value: 70, },
// { name: '澳门特别行政区', value: 60, },
// { name: '', value: 60, }
// ]
console.log(data);
return {
type: 'map',
width: '100%',
height: '700px',
option: {
title: { text: '各地区房源数量热力图', left: 'center' },
tooltip: { trigger: 'item' },
visualMap: {
show: true,
min: Math.min(...data.map(d => d.value)) || 0,
max: Math.max(...data.map(d => d.value)) || 100,
inRange: {
color: ['lightskyblue', 'yellow', 'orangered']
},
text: ["High", "Low"],
calculable: true
},
geo: {
map: "china",
roam: true,
label: { emphasis: { show: false } },
itemStyle: {
normal: { areaColor: "#f7fbff", borderColor: "#9ec2cf" },
emphasis: { areaColor: "#2a333d" }
}
},
series: [{
name: '房源数量',
type: 'map',
coordinateSystem: 'geo',
geoIndex: 0,
data: data,
}]
}
};
}
},
};
|
2301_79970562/student_union_frontend
|
src/assets/js/AdminHome.js
|
JavaScript
|
unknown
| 17,045
|
import request from "@/axios/request";
import DataCharts from "@/components/DataCharts";
export default {
data() {
return {
adminId: '',
username: '',
password: '',
phone: '',
email: '',
dialogVisible: false,
form: {
adminId: '',
username: '',
password: '',
checkPass: '',
phone: '',
email: ''
},
rules: {
// 验证规则(可根据实际需求扩展)
username: [
{ required: true, message: '请输入用户名', trigger: 'blur' },
{ min: 2, max: 20, message: '长度在2到20个字符之间', trigger: 'blur' }
],
password: [
{ required: true, message: '请输入密码', trigger: 'blur' },
{ min: 6, message: '密码至少6位', trigger: 'blur' }
],
checkPass: [
{ validator: (rule, value, callback) => {
if (value !== this.form.password) {
callback(new Error('两次输入密码不一致'));
} else {
callback();
}
}, trigger: 'blur' }
],
phone: [
{ required: true, message: '请输入手机号', trigger: 'blur' },
{ pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
],
email: [
{ required: true, message: '请输入邮箱地址', trigger: 'blur' },
{ type: 'email', message: '邮箱格式不正确', trigger: ['blur', 'change'] }
]
},
display: { display: 'none' },
disabled: true
};
},
created() {
this.fetchUserInfo();
},
methods: {
async fetchUserInfo() {
let token = JSON.parse(window.sessionStorage.getItem('userInfo'));
const adminId = token.adminId;
const res = await request.get(`/admin/findById/${adminId}`);
if (res.code === 200) {
token=res.data;
} else {
ElMessage.error("获取用户信息失败");
}
console.log(token);
if(!token) {
ElMessage.error("获取用户信息失败");
console.log("获取用户信息失败");
return;
}
this.adminId = token.adminId;
this.username = token.username;
this.password = token.password;
this.phone = token.phone;
this.email = token.email;
console.log(token);
},
Edit() {
this.form.adminId = this.adminId;
this.form.username = this.username;
this.form.password = this.password;
this.form.phone = this.phone;
this.form.email = this.email;
this.dialogVisible = true;
},
cancel() {
this.resetForm();
this.dialogVisible = false;
},
resetForm() {
this.form.phone = this.phone;
this.dialogVisible = true;
},
save() {
console.log('提交数据:', this.form);
request.put('/admin/updateById', this.form)
.then(response => {
const code = response.code;
if (code === 200) {
alert('更新成功');
this.fetchUserInfo();
} else {
alert(response.msg || '更新失败,请重试');
}
})
.catch(err => {
console.error('请求出错:', err);
alert('更新失败,请重试');
});
this.resetForm();
this.dialogVisible = false;
},
EditPass() {
this.disabled = false;
// this.display.display = 'block';
},
resetForm() {
this.form.username = this.username;
this.form.password = this.password;
this.form.checkPass = '';
this.form.phone = this.phone;
this.form.email = this.email;
this.disabled = true;
this.display.display = 'none';
if (this.$refs.formRef && this.$refs.formRef.resetFields) {
this.$refs.formRef.resetFields();
}
}
}
};
|
2301_79970562/student_union_frontend
|
src/assets/js/AdminSelfInfo.js
|
JavaScript
|
unknown
| 3,871
|
import request from "@/axios/request";
import { ElMessage } from "element-plus";
export default {
name: "AllHouses",
data() {
return {
loading: true,
search: "",
allData: [], // 存储所有房源数据
displayData: [], // 存储当前显示的房源数据
originalData: [], // 备份原始数据用于重置搜索
total: 0,
// 用户信息
userInfo: {
tenantId: null,
username: "",
phone: "",
email: ""
},
// 状态映射
statusMap: {
rented: { text: '已租', type: 'info' },
available: { text: '待租', type: 'success' },
pending: { text: '审核中', type: 'warning' },
rejected: { text: '审核未通过', type: 'danger' }
}
};
},
created() {
this.loadMyInfo();
this.load();
},
methods: {
async load() {
this.loading = true;
try{
const res = await request.get("/house/findAll");
if (res.code === 200) {
// 保留原始状态码,新增 displayStatus 字段用于显示
this.allData = (res.data || []).map(item => ({
...item,
displayStatus: this.statusMap[item.status]?.text || '未知状态'
}));
this.total = this.allData.length;
}
if (res.code === 200) {
this.allData = res.data || [];
this.originalData = [...this.allData]; // 备份原始数据
this.displayData = [...this.allData]; // 初始化显示数据
this.total = this.displayData.length;
} else {
ElMessage.error(res.msg || "加载失败");
this.displayData = [];
this.total = 0;
}
} catch (err) {
console.error(err);
ElMessage.error("网络错误,请稍后再试");
this.displayData = [];
this.total = 0;
} finally {
this.loading = false;
}
},
loadMyInfo() {
const userInfo = JSON.parse(window.sessionStorage.getItem('userInfo'));
if (!userInfo) {
ElMessage.error("获取用户信息失败");
console.log("获取用户信息失败");
return;
}
// 根据实际情况获取用户信息字段
this.userInfo = {
tenantId: userInfo.tenantId || null,
username: userInfo.username || "",
phone: userInfo.phone || "",
email: userInfo.email || ""
};
},
SignOut() {
sessionStorage.clear();
ElMessage({
message: '用户退出登录',
type: 'success',
});
this.$router.replace({ path: '/Login' });
},
// 搜索房源
async SearchHouse() {
const keyword = this.search.trim();
if (!keyword) {
this.ResetSearch(); // 如果关键词为空,重置搜索
return;
}
this.loading = true;
try {
const res1 = await request.get(`/house/title/${encodeURIComponent(keyword)}`);
const res2 = await request.get(`/house/area/${encodeURIComponent(keyword)}`);
let res = 200;
let mergedData = [];
if(res1.code === 200 && res2.code === 200)
{
res=200;
mergedData = [...res1.data, ...res2.data];
}else if(res1.code === 200 && res2.code !== 200){
res=200;
mergedData = [...res1.data];
}else if(res1.code !== 200 && res2.code === 200){
res=200;
mergedData = [...res2.data];
}
// 统一处理API响应结构
if (res === 200) {
this.displayData = mergedData || [];
this.total = this.displayData.length;
} else {
ElMessage.error(res.msg || "搜索失败");
this.displayData = [];
this.total = 0;
}
} catch (err) {
console.error(err);
ElMessage.error("网络错误,请稍后再试");
this.displayData = [];
this.total = 0;
} finally {
this.loading = false;
}
},
// 重置搜索
ResetSearch() {
this.search = "";
this.displayData = [...this.originalData]; // 恢复原始数据
this.total = this.displayData.length;
},
// 状态标签类型获取方法
getStatusTagType(status) {
return this.statusMap[status]?.type || '';
},
// 状态标签文本获取方法
getStatusLabel(status) {
return this.statusMap[status]?.text || '未知状态';
}
}
}
|
2301_79970562/student_union_frontend
|
src/assets/js/AllHouses.js
|
JavaScript
|
unknown
| 5,482
|
import request from "@/axios/request";
const {ElMessage} = require("element-plus");
export default {
name: "ApplicationAudition",
data() {
return {
loading: true,
search: "",
landlordId: null,
username: "",
password: "",
phone: "",
email: "",
currentPage: 1,
pageSize: 10,
total: 0,
house_total: 0,
tenant_total: 0,
allHouseData: [],
tableHouseData: [],
allTenantData: [],
tableTenantData: [],
allData: [], // 存储全量数据
tableData: [], // 当前页数据
// allData: [{
// houseId: 1,
// title: "学院十一峯",
// description: "学院十一峯位于温州市鹿城区滨江街道会展路与学院路交汇处,由金地集团与新希望地产联合开发,2021年竣工交付。项目总户数1276户,包含11栋板塔结合建筑,绿化率30%,容积率3.13,物业费4.7元/㎡·月(含能耗费)。小区定位改善型住宅,主力户型为143-189㎡的四居室,南北通透设计,精装修交付。",
// price: "5000",
// address: "温州市鹿城区滨江街道会展路与学院路交汇处",
// area: "浙江省",
// size: 140,
// rooms: 3,
// floor: 3,
// landlordId: 1,
// status: "待审核",
// imageUrl: "https://img2.baidu.com/it/u=668963934,1194070255&fm=253&fmt=auto&app=138&f=JPEG?w=661&h=500"
// }]
};
},
computed: {
paginatedData() {
const start = (this.currentPage - 1) * this.pageSize;
const end = start + this.pageSize;
return this.allData.slice(start, end);
},
paginatedHouseData() {
const start = (this.currentPage - 1) * this.pageSize;
const end = start + this.pageSize;
return this.allHouseData.slice(start, end);
},
paginatedTenantData() {
const start = (this.currentPage - 1) * this.pageSize;
const end = start + this.pageSize;
return this.allTenantData.slice(start, end);
},
},
created() {
this.loadMyInfo();
this.load();
this.loading = true;
setTimeout(() => {
this.loading = false;
}, 1000);
},
methods: {
async load() {
try{
let token = JSON.parse(window.sessionStorage.getItem('userInfo'));
const landlordId = token.landlordId;
// 获取所有房源申请
const res = await request.get(`/rental/landlord/${landlordId}`);
if (res.code === 200) {
this.allData = res.data || [];
this.allData = this.allData.filter(item => item.status === "pending");
this.total = this.allData.length;
this.tableData = this.paginatedData;
} else {
ElMessage.error(res.msg || "加载失败");
this.allData = [];
this.tableData = [];
this.total = 0;
}
// 获取所有房屋信息
const res_house = await request.get("/house/findAll");
if (res_house.code === 200) {
this.allHouseData = res_house.data || [];
this.house_total = this.allHouseData.length;
this.tableHouseData = this.paginatedHouseData;
} else {
ElMessage.error(res_house.msg || "加载失败");
this.allHouseData = [];
this.tableHouseData = [];
this.house_total = 0;
}
// 获取所有租客信息
const tenant_house = await request.get("/tenant/findAll");
if (tenant_house.code === 200) {
this.allTenantData = tenant_house.data || [];
this.tenant_total = this.allTenantData.length;
this.tableTenantData = this.paginatedTenantData;
} else {
ElMessage.error(tenant_house.msg || "加载失败");
this.allTenantData = [];
this.tableTenantData = [];
this.tenant_total = 0;
}
this.loading = false;
} catch (err){
console.error(err);
ElMessage.error("网络错误,请稍后再试");
this.allData = [];
this.tableData = [];
this.total = 0;
this.allHouseData = [];
this.tableHouseData = [];
this.house_total = 0;
this.allTenantData = [];
this.tableTenantData = [];
this.tenant_total = 0;
this.loading = false;
}
},
loadMyInfo() {
const token = JSON.parse(window.sessionStorage.getItem('userInfo'));
if(!token) {
ElMessage.error("获取用户信息失败");
console.log("获取用户信息失败");
return;
}
this.landlordId = token.landlordId;
this.username = token.username;
this.password = token.password;
this.phone = token.phone;
this.email = token.email;
},
async filterData() {
let token = JSON.parse(window.sessionStorage.getItem('userInfo'));
const landlordId = token.landlordId;
const res = await request.get(`/rental/landlord/${landlordId}`);
if (res.code === 200) {
this.allData = res.data || [];
this.total = this.allData.length;
this.tableData = this.paginatedData;
}
let data = this.allData;
if (this.search) {
const id = parseInt(this.search);
data = data.filter(item => item.houseId === id);
} else {
this.load();
}
this.allData = data;
this.total = data.length;
this.tableData = this.paginatedData;
},
reset() {
this.search = "";
this.currentPage = 1;
this.load();
},
async handleConfirm(row) {
try {
const house = await request.get(`/house/${row.houseId}`);
const type = row.type;
const status = house.data.status;
const applicationId = row.applicationId;
if (status === "available" && type === "in") {
const res = await request.put(`/rental/judge?rentalApplicationId=${applicationId}&status=approved`);
if (res.code === 200) {
ElMessage.success("成功提交审核结果");
this.load();
} else {
ElMessage.error(res.msg || "审核失败");
}
}else if (type === "out") {
const res = await request.put(`/rental/judge?rentalApplicationId=${applicationId}&status=approved`);
if (res.code === 200) {
ElMessage.success("成功提交审核结果");
this.load();
} else {
ElMessage.error(res.msg || "审核失败");
}
}else{
ElMessage.error("该房屋已被出租");
}
} catch (err) {
console.error(err);
ElMessage.error("网络错误,请稍后再试");
}
},
async handleReject(applicationId) {
try {
const res = await request.put(`/rental/judge?rentalApplicationId=${applicationId}&status=rejected`);
if (res.code === 200) {
ElMessage.success("成功提交审核结果");
this.load();
} else {
ElMessage.error(res.msg || "审核失败");
}
} catch (err) {
console.error(err);
ElMessage.error("网络错误,请稍后再试");
}
this.load();
},
SignOut() {
sessionStorage.clear()
ElMessage({
message: '用户退出登录',
type: 'success',
});
this.$router.replace({path: '/Login'});
},
handleSizeChange(pageSize) {
this.pageSize = pageSize;
this.tableData = this.paginatedData;
},
handleCurrentChange(pageNum) {
this.currentPage = pageNum;
this.tableData = this.paginatedData;
},
getTitle(houseId) {
const house = this.allHouseData.find(item => item.houseId === houseId);
if (!house){
return "未知名称";
}
return house.title;
},
getTenantUsername(tenantId) {
const tenant = this.allTenantData.find(item => item.tenantId === tenantId);
if (!tenant){
return "未知用户";
}
return tenant.username;
},
getTenantPhone(tenantId) {
const tenant = this.allTenantData.find(item => item.tenantId === tenantId);
if (!tenant){
return "未知电话号码";
}
return tenant.phone;
},
getTenantEmail(tenantId) {
const tenant = this.allTenantData.find(item => item.tenantId === tenantId);
if (!tenant){
return "未知邮箱";
}
return tenant.email;
},
formatTime(isoTime) {
if (!isoTime) return "-";
const date = new Date(isoTime);
// 手动格式化避免浏览器差异
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hour = String(date.getHours()).padStart(2, '0');
const minute = String(date.getMinutes()).padStart(2, '0');
const second = String(date.getSeconds()).padStart(2, '0');
return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
},
},
};
|
2301_79970562/student_union_frontend
|
src/assets/js/ApplicationAudition.js
|
JavaScript
|
unknown
| 10,814
|
import request from "@/axios/request";
const {ElMessage} = require("element-plus");
export default {
name: "CommentManagement",
data() {
return {
search: "",
currentPage: 1,
pageSize: 10,
total: 0,
allData: [], // 存储全量数据
tableData: [], // 当前页数据
isAllSelected: false, // 是否全选
selectedComments: [] // 当前页已选中的 commentId 列表
};
},
computed: {
paginatedData() {
const start = (this.currentPage - 1) * this.pageSize;
const end = start + this.pageSize;
return this.allData.slice(start, end);
}
},
created() {
this.load();
this.loading = true;
setTimeout(() => {
this.loading = false;
}, 1000);
},
methods: {
async load() {
try{
const res = await request.get("/comment/findAll");
if (res.code === 200) {
this.allData = res.data || [];
this.total = this.allData.length;
this.tableData = this.paginatedData;
} else {
ElMessage.error(res.msg || "加载失败");
this.allData = [];
this.tableData = [];
this.total = 0;
}
this.loading = false;
} catch (err){
console.error(err);
ElMessage.error("网络错误,请稍后再试");
this.allData = [];
this.tableData = [];
this.total = 0;
this.loading = false;
}
},
async filterData() {
const res = await request.get("/comment/findAll");
if (res.code === 200) {
this.allData = res.data || [];
this.total = this.allData.length;
this.tableData = this.paginatedData;
}
let data = this.allData;
if (this.search) {
const id = parseInt(this.search);
data = data.filter(item => item.tenantId === id);
}
this.allData = data;
this.total = data.length;
this.tableData = this.paginatedData;
},
reset() {
this.search = "";
this.currentPage = 1;
this.load();
},
async handleDelete(commentId) {
//删除
request.delete(`/comment/delete/${commentId}`).then((res) => {
if (res.code === 200) {
ElMessage({
message: "删除成功",
type: "success",
});
this.load();
} else {
ElMessage({
message: res.msg,
type: "error",
});
}
});
},
handleSizeChange(pageSize) {
this.pageSize = pageSize;
this.tableData = this.paginatedData;
},
handleCurrentChange(pageNum) {
this.currentPage = pageNum;
this.tableData = this.paginatedData;
},
toggleSelectAll(checked) {
if (checked) {
this.selectedComments = this.tableData.map(item => item.commentId);
} else {
this.selectedComments = [];
}
},
// 确认批量删除
batchDeleteConfirm() {
if (this.selectedComments.length === 0) {
ElMessage.warning("请至少选择一条评论");
return;
}
this.$confirm('确定删除当前页所有评论吗?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
this.batchDelete();
}).catch(() => {
this.$message.info('已取消删除');
});
},
// 批量删除数据
async batchDelete() {
if (!this.selectedComments.length) {
ElMessage.warning("没有可删除的数据");
return;
}
try {
// 并行删除所有选中的评论
const deletePromises = this.selectedComments.map(commentId => {
return request.delete(`/comment/delete/${commentId}`);
});
const results = await Promise.all(deletePromises);
// 检查是否有失败的请求
const failed = results.some(res => res.code !== "200");
if (!failed) {
ElMessage.success("批量删除成功");
} else {
ElMessage.warning("部分评论删除失败");
}
// 刷新数据
this.selectedComments = [];
this.isAllSelected = false;
this.load();
} catch (err) {
console.error(err);
ElMessage.error("网络错误,请稍后再试");
}
}
},
};
|
2301_79970562/student_union_frontend
|
src/assets/js/CommentManagement.js
|
JavaScript
|
unknown
| 5,345
|
import request from "@/axios/request";
import { ElMessage } from "element-plus";
export default {
name: "FavoriteHouseDisplay",
data() {
return {
loading: true,
Data: {},
isFavorited: false,
tenantId: '',
comments: [], // 存储当前房源的评论列表
userMap: {},
commentCount: 0, // 评论数量
rating: 0, // 评分
colors: ['#99A9BF', '#F7BA1E', '#FF9900'], // 评分星星的颜色,2,3,4是颜色分界
// 状态映射
statusMap: {
rented: { text: '已租', type: 'info' },
available: { text: '待租', type: 'success' },
pending: { text: '审核中', type: 'warning' },
rejected: { text: '审核未通过', type: 'danger' }
},
};
},
created() {
const houseId = this.$route.query.houseId;
this.load(houseId);
this.loadComments(houseId);
this.loading = true;
//获取当前登录用户ID(TenantSelfInfo)
const userInfo = JSON.parse(window.sessionStorage.getItem('userInfo') || '{}');
this.tenantId = userInfo.tenantId || ''; // 从sessionStorage中提取tenantId
this.loadFavoriteStatus(houseId,this.tenantId);
},
methods: {
// 房屋详情
async load(houseId) {
this.loading = true;
try{
const res = await request.get(`/house/${houseId}`);
if (res.code === 200) {
// 保留原始状态码,新增 displayStatus 字段用于显示
this.Data = res.data;
this.Data.displayStatus = this.statusMap[this.Data.status]?.text || '未知状态';
} else {
ElMessage.error(res.msg || "加载失败");
this.Data = {};
}
} catch (err){
console.error(err);
ElMessage.error("网络错误,请稍后再试");
} finally {
this.loading = false; // 接口请求完成后关闭loading
}
},
// 评论列表
async loadComments(houseId) {
try {
// 先清空旧数据
this.userMap = {};
this.comments = [];
this.commentCount = 0;
const res = await request.get(`/comment/house/${houseId}`);
// 如果接口调用失败,直接提示并 return
if (res.code !== 200) {
// ElMessage.error(res.msg || '加载评论失败');
return;
}
// 此时 res.code === 200
const list = Array.isArray(res.data) ? res.data : [];
// 只有在确实有评论时才去拉用户名
if (list.length > 0) {
// 并行请求所有用户名
await Promise.all(
list.map(async (comment) => {
try {
const userRes = await request.get(`/tenant/findById/${comment.tenantId}`);
// 强制转成字符串 key,以防类型不一致
this.userMap[String(comment.tenantId)] = (userRes.code === 200 && userRes.data.username) || '匿名用户';
} catch {
this.userMap[String(comment.tenantId)] = '匿名用户';
}
})
);
}
// 最后赋值评论列表
this.comments = list;
this.commentCount = list.length;
} catch (err) {
console.error("加载评论失败:", err);
ElMessage.error("加载评论失败,请稍后重试");
}
},
//时间显示
formatDate(dateStr) {
if (!dateStr) return "";
const date = new Date(dateStr);
return date.toLocaleString("zh-CN", {
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
hour12: false // 强制24小时制
});
},
async loadFavoriteStatus(houseId, tenantId) {
try {
const res = await request.post(`/favorite/tenantAndHouse` ,{
tenantId: tenantId,
houseId: houseId
});
if (res.code === 200) {
this.isFavorited = true;
}else if (res.code === 404) {
this.isFavorited = false;
}
} catch (err) {
console.error("获取收藏状态失败:", err);
}
},
// 切换收藏/取消收藏
async handleFavorite() {
// 先乐观更新
try {
if (this.isFavorited) {
await request.delete("/favorite/cancel", {
data: {
houseId: this.Data.houseId,
tenantId: this.tenantId
}
});
}else {
await request.post("/favorite/add", {
houseId: this.Data.houseId,
tenantId: this.tenantId
});
}
console.log(this.tenantId);
this.isFavorited = !this.isFavorited;
ElMessage.success(this.isFavorited ? "已收藏" : "已取消收藏");
} catch (err) {
// 回滚
this.isFavorited = !this.isFavorited;
console.error(err);
ElMessage.error("操作失败,请重试");
}
},
// 提交评论
async subComment() {
// 判断用户是否评论过
const hasCommented = this.comments.some(
comment => String(comment.tenantId) === String(this.tenantId)//判断用户名是否已存在
);
if (hasCommented) {
ElMessage.warning('用户仅允许提交一次评论');
this.commentContent = '';
this.rating = 0;
return;
}
try {
// 构建评论数据
const commentData = {
houseId: this.$route.query.houseId,
tenantId: this.tenantId,
content: this.commentContent.trim(),
rating: this.rating
};
// 调用后端接口
const res = await request.post(`/comment/add`, commentData);
if (res.code === 200) {
// 评论成功
ElMessage.success('评论提交成功');
// 清空表单
this.commentContent = '';
this.rating = 0;
// 刷新评论列表
await this.loadComments(this.$route.query.houseId);
} else {
// 评论失败
ElMessage.error(res.msg || '评论提交失败');
}
} catch (err) {
console.error("提交评论错误:", err);
ElMessage.error('网络错误,请稍后再试');
}
},
async subapplication(){
//判断房源的状态
const res = await request.get(`/house/${this.Data.houseId}`);
if (res.code === 200 && res.data.status !== "available") {
ElMessage.warning('该房源已不可申请');
return;
}
try {
//申请数据
const res = await request.post(`/rental/apply`, {
houseId: this.Data.houseId,
tenantId: this.tenantId,
type: "in",
});
if (res.code === 200) {
ElMessage.success('申请提交成功');
} else {
ElMessage.error(res.msg || '申请提交失败');
}
} catch (err) {
console.error("提交申请错误:", err);
ElMessage.error('网络错误,请稍后再试');
}
},
// 状态标签类型获取方法
getStatusTagType(status) {
return this.statusMap[status]?.type || '';
},
// 状态标签文本获取方法
getStatusLabel(status) {
return this.statusMap[status]?.text || '未知状态';
}
},
};
|
2301_79970562/student_union_frontend
|
src/assets/js/FavoriteHouseDisplay.js
|
JavaScript
|
unknown
| 8,915
|
import request from "@/axios/request";
import { ElMessage } from "element-plus";
export default {
name: "HomeDisplay",
data() {
return {
loading: true,
Data: {},
isFavorited: false,
tenantId: '',
comments: [], // 存储当前房源的评论列表
userMap: {},
commentCount: 0, // 评论数量
rating: 0, // 评分
colors: ['#99A9BF', '#F7BA1E', '#FF9900'] ,// 评分星星的颜色,2,3,4是颜色分界
// 状态映射
statusMap: {
rented: { text: '已租', type: 'info' },
available: { text: '待租', type: 'success' },
pending: { text: '审核中', type: 'warning' },
rejected: { text: '审核未通过', type: 'danger' }
},
};
},
created() {
const houseId = this.$route.query.houseId;
this.load(houseId);
this.loadComments(houseId);
this.loading = true;
//获取当前登录用户ID(TenantSelfInfo)
const userInfo = JSON.parse(window.sessionStorage.getItem('userInfo') || '{}');
this.tenantId = userInfo.tenantId || ''; // 从sessionStorage中提取tenantId
this.loadFavoriteStatus(houseId,this.tenantId);
},
methods: {
// 房屋详情
async load(houseId) {
this.loading = true;
try{
const res = await request.get(`/house/${houseId}`);
if (res.code === 200) {
// 保留原始状态码,新增 displayStatus 字段用于显示
this.Data = res.data;
this.Data.displayStatus = this.statusMap[this.Data.status]?.text || '未知状态';
}else {
ElMessage.error(res.msg || "加载失败");
this.Data = {};
}
} catch (err){
console.error(err);
ElMessage.error("网络错误,请稍后再试");
} finally {
this.loading = false; // 接口请求完成后关闭loading
}
},
// 评论列表
async loadComments(houseId) {
try {
// 先清空旧数据
this.userMap = {};
this.comments = [];
this.commentCount = 0;
const res = await request.get(`/comment/house/${houseId}`);
// 如果接口调用失败,直接提示并 return
if (res.code !== 200) {
// ElMessage.error(res.msg || '加载评论失败');
return;
}
// 此时 res.code === 200
const list = Array.isArray(res.data) ? res.data : [];
// 只有在确实有评论时才去拉用户名
if (list.length > 0) {
// 并行请求所有用户名
await Promise.all(
list.map(async (comment) => {
try {
const userRes = await request.get(`/tenant/findById/${comment.tenantId}`);
// 强制转成字符串 key,以防类型不一致
this.userMap[String(comment.tenantId)] = (userRes.code === 200 && userRes.data.username) || '匿名用户';
} catch {
this.userMap[String(comment.tenantId)] = '匿名用户';
}
})
);
}
// 最后赋值评论列表
this.comments = list;
this.commentCount = list.length;
} catch (err) {
console.error("加载评论失败:", err);
ElMessage.error("加载评论失败,请稍后重试");
}
},
//时间显示
formatDate(dateStr) {
if (!dateStr) return "";
const date = new Date(dateStr);
return date.toLocaleString("zh-CN", {
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
});
},
async loadFavoriteStatus(houseId, tenantId) {
try {
const res = await request.post(`/favorite/tenantAndHouse` ,{
tenantId: tenantId,
houseId: houseId
});
if (res.code === 200) {
this.isFavorited = true;
}else if (res.code === 404) {
this.isFavorited = false;
}
} catch (err) {
console.error("获取收藏状态失败:", err);
}
},
// 切换收藏/取消收藏
async handleFavorite() {
// 先乐观更新
try {
if (this.isFavorited) {
await request.delete("/favorite/cancel", {
data: {
houseId: this.Data.houseId,
tenantId: this.tenantId
}
});
}else {
await request.post("/favorite/add", {
houseId: this.Data.houseId,
tenantId: this.tenantId
});
}
console.log(this.tenantId);
this.isFavorited = !this.isFavorited;
ElMessage.success(this.isFavorited ? "已收藏" : "已取消收藏");
} catch (err) {
// 回滚
this.isFavorited = !this.isFavorited;
console.error(err);
ElMessage.error("操作失败,请重试");
}
},
// 提交评论
async subComment() {
// 判断用户是否评论过
const hasCommented = this.comments.some(
comment => String(comment.tenantId) === String(this.tenantId)//判断用户名是否已存在
);
if (hasCommented) {
ElMessage.warning('用户仅允许提交一次评论');
this.commentContent = '';
this.rating = 0;
return;
}
try {
// 构建评论数据
const commentData = {
houseId: this.$route.query.houseId,
tenantId: this.tenantId,
content: this.commentContent.trim(),
rating: this.rating
};
// 调用后端接口
const res = await request.post(`/comment/add`, commentData);
if (res.code === 200) {
// 评论成功
ElMessage.success('评论提交成功');
// 清空表单
this.commentContent = '';
this.rating = 0;
// 刷新评论列表
await this.loadComments(this.$route.query.houseId);
} else {
// 评论失败
ElMessage.error(res.msg || '评论提交失败');
}
} catch (err) {
console.error("提交评论错误:", err);
ElMessage.error('网络错误,请稍后再试');
}
},
async subapplication(){
//判断房源的状态
const res = await request.get(`/house/${this.Data.houseId}`);
if (res.code === 200 && res.data.status !== "available") {
ElMessage.warning('该房源已不可申请');
return;
}
try {
//申请数据
const res = await request.post(`/rental/apply`, {
houseId: this.Data.houseId,
tenantId: this.tenantId,
type: "in",
});
if (res.code === 200) {
ElMessage.success('申请提交成功');
} else {
ElMessage.error(res.msg || '申请提交失败');
}
} catch (err) {
console.error("提交申请错误:", err);
ElMessage.error('网络错误,请稍后再试');
}
},
// 状态标签类型获取方法
getStatusTagType(status) {
return this.statusMap[status]?.type || '';
},
// 状态标签文本获取方法
getStatusLabel(status) {
return this.statusMap[status]?.text || '未知状态';
}
},
};
|
2301_79970562/student_union_frontend
|
src/assets/js/HomeDisplay.js
|
JavaScript
|
unknown
| 8,854
|
import request from "@/axios/request";
const {ElMessage} = require("element-plus");
export default {
name: "HouseAudition",
data() {
return {
search: "",
currentPage: 1,
pageSize: 10,
total: 0,
allData: [], // 存储全量数据
tableData: [] // 当前页数据
};
},
computed: {
paginatedData() {
const start = (this.currentPage - 1) * this.pageSize;
const end = start + this.pageSize;
return this.allData.slice(start, end);
}
},
created() {
this.load();
this.loading = true;
setTimeout(() => {
this.loading = false;
}, 1000);
},
methods: {
async load() {
try{
const res = await request.get("/house/status?status=pending");
if (res.code === 200) {
this.allData = res.data || [];
this.total = this.allData.length;
this.tableData = this.paginatedData;
} else {
ElMessage.error(res.msg || "加载失败");
this.allData = [];
this.tableData = [];
this.total = 0;
}
this.loading = false;
} catch (err){
console.error(err);
ElMessage.error("网络错误,请稍后再试");
this.allData = [];
this.tableData = [];
this.total = 0;
this.loading = false;
}
},
async filterData() {
const res = await request.get("/house/status?status=pending");
if (res.code === 200) {
this.allData = res.data || [];
this.total = this.allData.length;
this.tableData = this.paginatedData;
}
let data = this.allData;
if (this.search) {
const id = parseInt(this.search);
data = data.filter(item => item.landlordId === id);
} else {
this.load();
}
this.allData = data;
this.total = data.length;
this.tableData = this.paginatedData;
},
reset() {
this.search = "";
this.currentPage = 1;
this.load();
},
async handleConfirm(houseId) {
try {
const res = await request.put(`/house/statu?houseId=${houseId}&status=available`);
if (res.code === 200) {
ElMessage.success("成功提交审核结果");
this.load();
} else {
ElMessage.error(res.msg || "审核失败");
}
} catch (err) {
console.error(err);
ElMessage.error("网络错误,请稍后再试");
}
},
async handleReject(houseId) {
try {
const res = await request.put(`/house/statu?houseId=${houseId}&status=rejected`);
if (res.code === 200) {
ElMessage.success("成功提交审核结果");
this.load();
} else {
ElMessage.error(res.msg || "审核失败");
}
} catch (err) {
console.error(err);
ElMessage.error("网络错误,请稍后再试");
}
},
handleSizeChange(pageSize) {
this.pageSize = pageSize;
this.tableData = this.paginatedData;
},
handleCurrentChange(pageNum) {
this.currentPage = pageNum;
this.tableData = this.paginatedData;
},
},
};
|
2301_79970562/student_union_frontend
|
src/assets/js/HouseAudition.js
|
JavaScript
|
unknown
| 3,854
|
import request from "@/axios/request";
const {ElMessage} = require("element-plus");
export default {
name: "HouseDelete",
data() {
return {
search: "",
currentPage: 1,
pageSize: 10,
total: 0,
allData: [], // 存储全量数据
tableData: [], // 当前页数据
// 状态映射
statusMap: {
rented: { text: '已租', type: 'info' },
available: { text: '待租', type: 'success' },
pending: { text: '审核中', type: 'warning' },
rejected: { text: '审核未通过', type: 'danger' }
}
};
},
computed: {
paginatedData() {
const start = (this.currentPage - 1) * this.pageSize;
const end = start + this.pageSize;
return this.allData.slice(start, end);
}
},
created() {
this.load();
this.loading = true;
setTimeout(() => {
this.loading = false;
}, 1000);
},
methods: {
async load() {
try{
const res = await request.get("/house/findAll");
if (res.code === 200) {
this.allData = res.data || [];
this.total = this.allData.length;
this.tableData = this.paginatedData;
} else {
ElMessage.error(res.msg || "加载失败");
this.allData = [];
this.tableData = [];
this.total = 0;
}
this.loading = false;
} catch (err){
console.error(err);
ElMessage.error("网络错误,请稍后再试");
this.allData = [];
this.tableData = [];
this.total = 0;
this.loading = false;
}
},
async filterData() {
const res = await request.get("/house/findAll");
if (res.code === 200) {
this.allData = res.data || [];
this.total = this.allData.length;
this.tableData = this.paginatedData;
}
let data = this.allData;
if (this.search) {
const id = parseInt(this.search);
data = data.filter(item => item.houseId === id);
} else {
this.load();
}
this.allData = data;
this.total = data.length;
this.tableData = this.paginatedData;
},
reset() {
this.search = "";
this.currentPage = 1;
this.load();
},
async handleDelete(row) {
if(row.status !== 'rented'){
//删除
request.delete(`/house/delete/${row.houseId}`).then((res) => {
if (res.code === 200) {
ElMessage({
message: "删除成功",
type: "success",
});
this.load();
} else {
ElMessage({
message: res.msg,
type: "error",
});
}
});
}else{
ElMessage({
message: "该房屋已被租用,无法删除",
type: "error",
});
}
},
handleSizeChange(pageSize) {
this.pageSize = pageSize;
this.tableData = this.paginatedData;
},
handleCurrentChange(pageNum) {
this.currentPage = pageNum;
this.tableData = this.paginatedData;
},
// 状态标签类型获取方法
getStatusTagType(status) {
return this.statusMap[status]?.type || '';
},
// 状态标签文本获取方法
getStatusLabel(status) {
return this.statusMap[status]?.text || '未知状态';
}
},
};
|
2301_79970562/student_union_frontend
|
src/assets/js/HouseDelete.js
|
JavaScript
|
unknown
| 4,189
|
import request from "@/axios/request";
import { ElMessage } from "element-plus";
export default {
name: "HouseDisplay",
data() {
return {
loading: true,
Data: {},
isFavorited: false,
tenantId: '',
comments: [], // 存储当前房源的评论列表
userMap: {},
commentCount: 0, // 评论数量
rating: 0, // 评分
colors: ['#99A9BF', '#F7BA1E', '#FF9900'] ,// 评分星星的颜色,2,3,4是颜色分界
// 状态映射
statusMap: {
rented: { text: '已租', type: 'info' },
available: { text: '待租', type: 'success' },
pending: { text: '审核中', type: 'warning' },
rejected: { text: '审核未通过', type: 'danger' }
},
};
},
created() {
const houseId = this.$route.query.houseId;
this.load(houseId);
this.loadComments(houseId);
this.loading = true;
//获取当前登录用户ID(TenantSelfInfo)
const userInfo = JSON.parse(window.sessionStorage.getItem('userInfo') || '{}');
this.tenantId = userInfo.tenantId || ''; // 从sessionStorage中提取tenantId
this.loadFavoriteStatus(houseId,this.tenantId);
},
methods: {
// 房屋详情
async load(houseId) {
this.loading = true;
try{
const res = await request.get(`/house/${houseId}`);
if (res.code === 200) {
// 保留原始状态码,新增 displayStatus 字段用于显示
this.Data = res.data;
this.Data.displayStatus = this.statusMap[this.Data.status]?.text || '未知状态';
}else {
ElMessage.error(res.msg || "加载失败");
this.Data = {};
}
} catch (err){
console.error(err);
ElMessage.error("网络错误,请稍后再试");
} finally {
this.loading = false; // 接口请求完成后关闭loading
}
},
// 评论列表
async loadComments(houseId) {
try {
// 先清空旧数据
this.userMap = {};
this.comments = [];
this.commentCount = 0;
const res = await request.get(`/comment/house/${houseId}`);
// 如果接口调用失败,直接提示并 return
if (res.code !== 200) {
// ElMessage.error(res.msg || '加载评论失败');
return;
}
// 此时 res.code === 200
const list = Array.isArray(res.data) ? res.data : [];
// 只有在确实有评论时才去拉用户名
if (list.length > 0) {
// 并行请求所有用户名
await Promise.all(
list.map(async (comment) => {
try {
const userRes = await request.get(`/tenant/findById/${comment.tenantId}`);
// 强制转成字符串 key,以防类型不一致
this.userMap[String(comment.tenantId)] = (userRes.code === 200 && userRes.data.username) || '匿名用户';
} catch {
this.userMap[String(comment.tenantId)] = '匿名用户';
}
})
);
}
// 最后赋值评论列表
this.comments = list;
this.commentCount = list.length;
} catch (err) {
console.error("加载评论失败:", err);
ElMessage.error("加载评论失败,请稍后重试");
}
},
//时间显示
formatDate(dateStr) {
if (!dateStr) return "";
const date = new Date(dateStr);
return date.toLocaleString("zh-CN", {
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
});
},
async loadFavoriteStatus(houseId, tenantId) {
try {
const res = await request.post(`/favorite/tenantAndHouse` ,{
tenantId: tenantId,
houseId: houseId
});
if (res.code === 200) {
this.isFavorited = true;
}else if (res.code === 404) {
this.isFavorited = false;
}
} catch (err) {
console.error("获取收藏状态失败:", err);
}
},
// 切换收藏/取消收藏
async handleFavorite() {
// 先乐观更新
try {
if (this.isFavorited) {
await request.delete("/favorite/cancel", {
data: {
houseId: this.Data.houseId,
tenantId: this.tenantId
}
});
}else {
await request.post("/favorite/add", {
houseId: this.Data.houseId,
tenantId: this.tenantId
});
}
console.log(this.tenantId);
this.isFavorited = !this.isFavorited;
ElMessage.success(this.isFavorited ? "已收藏" : "已取消收藏");
} catch (err) {
// 回滚
this.isFavorited = !this.isFavorited;
console.error(err);
ElMessage.error("操作失败,请重试");
}
},
// 提交评论
async subComment() {
// 判断用户是否评论过
const hasCommented = this.comments.some(
comment => String(comment.tenantId) === String(this.tenantId)//判断用户名是否已存在
);
if (hasCommented) {
ElMessage.warning('用户仅允许提交一次评论');
this.commentContent = '';
this.rating = 0;
return;
}
try {
// 构建评论数据
const commentData = {
houseId: this.$route.query.houseId,
tenantId: this.tenantId,
content: this.commentContent.trim(),
rating: this.rating
};
// 调用后端接口
const res = await request.post(`/comment/add`, commentData);
if (res.code === 200) {
// 评论成功
ElMessage.success('评论提交成功');
// 清空表单
this.commentContent = '';
this.rating = 0;
// 刷新评论列表
await this.loadComments(this.$route.query.houseId);
} else {
// 评论失败
ElMessage.error(res.msg || '评论提交失败');
}
} catch (err) {
console.error("提交评论错误:", err);
ElMessage.error('网络错误,请稍后再试');
}
},
async subapplication(){
//判断房源的状态
const res = await request.get(`/house/${this.Data.houseId}`);
if (res.code === 200 && res.data.status !== "available") {
ElMessage.warning('该房源已不可申请');
return;
}
try {
//申请数据
const res = await request.post(`/rental/apply`, {
houseId: this.Data.houseId,
tenantId: this.tenantId,
type: "in",
});
if (res.code === 200) {
ElMessage.success('申请提交成功');
} else {
ElMessage.error(res.msg || '申请提交失败');
}
} catch (err) {
console.error("提交申请错误:", err);
ElMessage.error('网络错误,请稍后再试');
}
},
// 状态标签类型获取方法
getStatusTagType(status) {
return this.statusMap[status]?.type || '';
},
// 状态标签文本获取方法
getStatusLabel(status) {
return this.statusMap[status]?.text || '未知状态';
}
},
};
|
2301_79970562/student_union_frontend
|
src/assets/js/HouseDisplay.js
|
JavaScript
|
unknown
| 8,855
|
import request from "@/axios/request";
const {ElMessage} = require("element-plus");
export default {
name: "LandlordHome",
data() {
return {
loading: true,
landlordId: null,
username: "",
password: "",
phone: "",
email: "",
// landlordId: 1,
// username: "FelicityZ",
// password: "123456",
// phone: "19853228572",
// email: "1833808950@qq.com",
images: [
{ src: require('@/assets/landlord_banner1.png'), alt: 'pic1' },
{ src: require('@/assets/landlord_banner2.png'), alt: 'pic2' },
{ src: require('@/assets/landlord_banner4.png'), alt: 'pic3' },
{ src: require('@/assets/landlord_banner3.png'), alt: 'pic4' }
],
total: 0,
allData: [],
// firstSixData: [],
firstSixData: [{
houseId: 1,
title: "学院十一峯",
description: "学院十一峯位于温州市鹿城区滨江街道会展路与学院路交汇处,由金地集团与新希望地产联合开发,2021年竣工交付。项目总户数1276户,包含11栋板塔结合建筑,绿化率30%,容积率3.13,物业费4.7元/㎡·月(含能耗费)。小区定位改善型住宅,主力户型为143-189㎡的四居室,南北通透设计,精装修交付。",
price: "5000",
address: "温州市鹿城区滨江街道会展路与学院路交汇处",
area: "浙江省",
size: 140,
rooms: 3,
floor: 3,
landlordId: 1,
status: "待审核",
imageUrl: "https://img2.baidu.com/it/u=668963934,1194070255&fm=253&fmt=auto&app=138&f=JPEG?w=661&h=500"
},{
houseId: 1,
title: "学院十一峯",
description: "学院十一峯位于温州市鹿城区滨江街道会展路与学院路交汇处,由金地集团与新希望地产联合开发,2021年竣工交付。项目总户数1276户,包含11栋板塔结合建筑,绿化率30%,容积率3.13,物业费4.7元/㎡·月(含能耗费)。小区定位改善型住宅,主力户型为143-189㎡的四居室,南北通透设计,精装修交付。",
price: "5000",
address: "温州市鹿城区滨江街道会展路与学院路交汇处",
area: "浙江省",
size: 140,
rooms: 3,
floor: 3,
landlordId: 1,
status: "待审核",
imageUrl: "https://img2.baidu.com/it/u=668963934,1194070255&fm=253&fmt=auto&app=138&f=JPEG?w=661&h=500"
}],
statusMap: {
rented: { text: '已租', type: 'info' },
available: { text: '待租', type: 'success' },
pending: { text: '审核中', type: 'warning' },
rejected: { text: '审核未通过', type: 'danger' }
}
};
},
computed: {
paginatedData() {
const start = 0;
const end = 6;
return this.allData.slice(start, end);
}
},
created() {
this.loadMyInfo();
this.load();
this.loading = true;
setTimeout(() => {
this.loading = false;
}, 1000);
},
methods: {
async load() {
try{
const res = await request.get("/house/findAll");
if (res.code === 200) {
this.allData = res.data || [];
this.total = this.allData.length;
this.firstSixData = this.paginatedData;
} else {
ElMessage.error(res.msg || "加载失败");
this.allData = [];
this.firstSixData = [];
this.total = 0;
}
this.loading = false;
} catch (err){
console.error(err);
ElMessage.error("网络错误,请稍后再试");
this.allData = [];
// this.firstSixData = [];
this.total = 2;
this.loading = false;
}
},
loadMyInfo() {
const token = JSON.parse(window.sessionStorage.getItem('userInfo'));
if(!token) {
ElMessage.error("获取用户信息失败");
console.log("获取用户信息失败");
return;
}
this.landlordId = token.landlordId;
this.username = token.username;
this.password = token.password;
this.phone = token.phone;
this.email = token.email;
},
SignOut() {
sessionStorage.clear()
ElMessage({
message: '用户退出登录',
type: 'success',
});
this.$router.replace({path: '/Login'});
},
// 状态标签类型获取方法
getStatusTagType(status) {
return this.statusMap[status]?.type || '';
},
// 状态标签文本获取方法
getStatusLabel(status) {
return this.statusMap[status]?.text || '未知状态';
}
},
};
|
2301_79970562/student_union_frontend
|
src/assets/js/LandlordHome.js
|
JavaScript
|
unknown
| 5,453
|
import request from "@/axios/request";
import request2 from "@/axios/request2";
const {ElMessage} = require("element-plus");
export default {
name: "LandlordHouse",
data() {
return {
loading: true,
dialogVisible1: false,
dialogVisible2: false,
landlordId: null,
username: "",
password: "",
phone: "",
email: "",
total: 0,
houseId: null,
landlordId: null,
title: "",
address: "",
description: "",
price: null,
area: "",
size: null,
roomCount: null,
floor: null,
imageUrl: "",
fileList1: [],
fileList2: [],
status: "",
form1: {
houseId: null,
landlordId: null,
title: "",
address: "",
description: "",
price: null,
area: "",
size: null,
roomCount: null,
floor: null,
imageUrl: "",
status: ""
},
form2: {
title: "",
address: "",
description: "",
price: null,
area: "",
size: null,
roomCount: null,
floor: null,
imageUrl: "",
landlordId: null,
fileList: ""
},
allData: [],
// allData: [{
// houseId: 1,
// title: "学院十一峯",
// description: "学院十一峯位于温州市鹿城区滨江街道会展路与学院路交汇处,由金地集团与新希望地产联合开发,2021年竣工交付。项目总户数1276户,包含11栋板塔结合建筑,绿化率30%,容积率3.13,物业费4.7元/㎡·月(含能耗费)。小区定位改善型住宅,主力户型为143-189㎡的四居室,南北通透设计,精装修交付。",
// price: 5000,
// address: "温州市鹿城区滨江街道会展路与学院路交汇处",
// area: "浙江省",
// size: 140,
// roomCount: 3,
// floor: 3,
// landlordId: 1,
// status: "pending",
// imageUrl: "https://img2.baidu.com/it/u=668963934,1194070255&fm=253&fmt=auto&app=138&f=JPEG?w=661&h=500"
// },
// {
// houseId: 1,
// title: "学院十一峯",
// description: "学院十一峯位于温州市鹿城区滨江街道会展路与学院路交汇处,由金地集团与新希望地产联合开发,2021年竣工交付。项目总户数1276户,包含11栋板塔结合建筑,绿化率30%,容积率3.13,物业费4.7元/㎡·月(含能耗费)。小区定位改善型住宅,主力户型为143-189㎡的四居室,南北通透设计,精装修交付。",
// price: 5000,
// address: "温州市鹿城区滨江街道会展路与学院路交汇处",
// area: "浙江省",
// size: 140,
// roomCount: 3,
// floor: 3,
// landlordId: 1,
// status: "rented",
// imageUrl: "https://img2.baidu.com/it/u=668963934,1194070255&fm=253&fmt=auto&app=138&f=JPEG?w=661&h=500"
// }],
display: { display: 'none' },
disabled: false,
available: true,
rented: true,
pending: true,
rejected: true,
filteredData: [],
activeIndex: '/LandlordHouse',
// fileList: [],
// file_flag: 0,
};
},
watch: {
available: {
handler() {
this.filterData();
}
},
rented: {
handler() {
this.filterData();
}
},
pending: {
handler() {
this.filterData();
}
},
rejected: {
handler() {
this.filterData();
}
}
},
created() {
this.fetchUserInfo();
this.load();
this.loading = true;
setTimeout(() => {
this.loading = false;
}, 1000);
this.$nextTick(() => {
this.filterData();
});
},
methods: {
async load() {
try{
let token = JSON.parse(window.sessionStorage.getItem('userInfo'));
const landlordId = token.landlordId;
const res = await request.get(`/house/landlord/${landlordId}`);
if (res.code === 200) {
this.allData = res.data || [];
this.filteredData = this.allData;
this.filterData();
this.total = this.allData.length;
} else {
ElMessage.error(res.msg || "加载失败");
this.allData = [];
this.total = 0;
}
this.loading = false;
} catch (err){
console.error(err);
ElMessage.error("网络错误,请稍后再试");
this.allData = [];
this.total = 0;
this.loading = false;
}
},
async fetchUserInfo() {
let token = JSON.parse(window.sessionStorage.getItem('userInfo'));
const landlordId = token.landlordId;
const res = await request.get(`/landlord/findById/${landlordId}`);
if (res.code === 200) {
token=res.data;
} else {
ElMessage.error("获取用户信息失败");
}
console.log(token);
if(!token) {
ElMessage.error("获取用户信息失败");
console.log("获取用户信息失败");
return;
}
this.landlordId = token.landlordId;
this.username = token.username;
this.password = token.password;
this.phone = token.phone;
this.email = token.email;
console.log(token);
},
filterData() {
this.filteredData = this.allData.filter(item => {
if (item.status === 'available' && this.available) return true;
if (item.status === 'rented' && this.rented) return true;
if (item.status === 'pending' && this.pending) return true;
if (item.status === 'rejected' && this.rejected) return true;
return false;
});
this.load();
},
SignOut() {
sessionStorage.clear()
ElMessage({
message: '用户退出登录',
type: 'success',
});
this.$router.replace({path: '/Login'});
},
// 获取标签类型
getStatusTagType(status) {
switch (status) {
case 'pending': return 'warning';
case 'available': return 'success';
case 'rejected': return 'danger';
case 'rented': return 'info';
default: return '';
}
},
// 获取状态文本
getStatusLabel(status) {
switch (status) {
case 'pending': return '待审核';
case 'available': return '上线中';
case 'rejected': return '被拒绝';
case 'rented': return '已出租';
default: return '未知状态';
}
},
handleEdit(row) {
if (row.status !== 'pending') {
ElMessage.error("已上线的房屋不能修改");
return;
}else{
this.form1.houseId = row.houseId;
this.form1.landlordId = row.landlordId;
this.form1.title = row.title,
this.form1.description = row.description,
this.form1.price = row.price,
this.form1.address = row.address,
this.form1.area = row.area,
this.form1.size = row.size,
this.form1.roomCount = row.roomCount,
this.form1.floor = row.floor,
this.form1.status = "pending",
this.form1.imageUrl = row.imageUrl,
this.houseId = row.houseId;
this.landlordId = row.landlordId;
this.title = row.title,
this.description = row.description,
this.price = row.price,
this.address = row.address,
this.area = row.area,
this.size = row.size,
this.roomCount = row.roomCount,
this.floor = row.floor,
this.status = row.status,
this.imageUrl = row.imageUrl,
this.fileList1 = [{
name: 'current-image',
url: row.imageUrl
}];
this.dialogVisible1 = true;
}
},
async handleDelete(row) {
if (row.status === 'rented') {
ElMessage.error("已出租的房屋记录不能被删除");
return;
}else{
//删除
request.delete(`/house/delete/${row.houseId}`).then((res) => {
if (res.code === 200) {
ElMessage({
message: "删除成功",
type: "success",
});
this.load();
} else {
ElMessage({
message: res.msg,
type: "error",
});
}
});
}
},
cancel1() {
this.resetForm1();
this.dialogVisible1 = false;
},
cancel2() {
this.resetForm2();
this.dialogVisible2 = false;
},
save1() {
request.put('/house/update', this.form1)
.then(response => {
const code = response.code;
if (code === 200) {
alert('更新成功');
this.fetchUserInfo();
this.load();
} else {
alert(response.msg || '更新失败,请重试');
}
})
.catch(err => {
console.error('请求出错:', err);
alert('更新失败,请重试');
});
console.log('提交数据:', this.form1);
this.resetForm1();
this.dialogVisible1 = false;
},
async save2() {
let token = JSON.parse(window.sessionStorage.getItem('userInfo'));
const landlordId = token.landlordId;
this.form2.landlordId = landlordId;
if (this.form2.fileList) {
if (this.selectedFile) {
const formData = new FormData();
formData.append('file', this.selectedFile);
try {
const uploadResponse = await request2.post('/house/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
});
if (uploadResponse.code !== 200) {
this.$message.error('文件上传失败: ' + (uploadResponse.msg || '未知错误'));
return;
}
} catch (error) {
console.error('文件上传错误:', error);
this.$message.error('文件上传失败');
return;
}
}
}
request.post('/house/add', this.form2)
.then(response => {
const code = response.code;
if (code === 200) {
this.$message.success('添加成功');
this.fetchUserInfo();
this.load();
} else {
this.$message.error(response.msg || '添加失败,请重试');
}
})
.catch(err => {
console.error('请求出错:', err);
this.$message.error('添加失败,请重试');
});
console.log('提交数据:', JSON.parse(JSON.stringify(this.form2)));
this.resetForm2();
this.dialogVisible2 = false;
},
resetForm1() {
this.form1.houseId = this.houseId;
this.form1.landlordId = this.landlordId;
this.form1.title = this.title,
this.form1.description = this.description,
this.form1.price = this.price,
this.form1.address = this.address,
this.form1.area = this.area,
this.form1.size = this.size,
this.form1.roomCount = this.roomCount,
this.form1.floor = this.floor,
this.form1.status = this.status,
this.form1.imageUrl = this.imageUrl,
this.disabled = true;
this.display.display = 'none';
if (this.$refs.formRef1 && this.$refs.formRef1.resetFields) {
this.$refs.formRef1.resetFields();
}
},
resetForm2() {
this.form2.title = "",
this.form2.description = "",
this.form2.price = null,
this.form2.address = "",
this.form2.area = "",
this.form2.size = null,
this.form2.roomCount = null,
this.form2.floor = null,
this.form2.imageUrl = "",
this.form2.fileList = "";
this.disabled = true;
this.display.display = 'none';
if (this.$refs.formRef2 && this.$refs.formRef2.resetFields) {
this.$refs.formRef2.resetFields();
}
this.fileList2 = [];
if (this.$refs.fileUploadRef) {
const fileInput = this.$refs.fileUploadRef.$el.querySelector('input[type="file"]');
if (fileInput) {
fileInput.value = '';
}
}
this.selectedFile = null;
},
add() {
this.dialogVisible2 = true;
this.$nextTick(() => {
// this.$refs.formRef2.resetFields();
this.disabled = false;
// this.form2 = {};
});
},
handleImageChange1(file) {
const selectedFile = file.raw;
// 限制图片格式
const validTypes = ['image/jpeg', 'image/png', 'image/gif'];
if (!validTypes.includes(selectedFile.type)) {
this.$message.error('只能上传 JPG、PNG 或 GIF 格式的图片');
return;
}
// 限制图片大小
const maxSize = 200 * 1024 * 1024;
if (selectedFile.size > maxSize) {
this.$message.error('图片大小不能超过 200MB');
return;
}
// 使用 FileReader 读取图片
const reader = new FileReader();
reader.onload = (e) => {
this.form1.imageUrl = e.target.result;
};
reader.readAsDataURL(selectedFile);
this.fileList1 = [file];
},
handleImageChange2(file) {
const selectedFile = file.raw;
const validTypes = ['image/jpeg', 'image/png', 'image/gif'];
if (!validTypes.includes(selectedFile.type)) {
this.$message.error('只能上传 JPG、PNG 或 GIF 格式的图片');
return;
}
const maxSize = 200 * 1024 * 1024;
if (selectedFile.size > maxSize) {
this.$message.error('图片大小不能超过 200MB');
return;
}
const reader = new FileReader();
reader.onload = (e) => {
this.form2.imageUrl = e.target.result;
};
reader.readAsDataURL(selectedFile);
this.fileList2 = [file];
},
handleRemove1() {
this.fileList1 = [];
this.form1.imageUrl = '';
this.$message.success('图片已删除');
},
handleRemove2() {
this.fileList2 = [];
this.form2.imageUrl = '';
this.$message.success('图片已删除');
},
// 文件处理
handleFileChange(file, fileList) {
const selectedFile = file.raw;
// 验证文件类型
const validTypes = [
'application/msword',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/pdf'
];
if (!validTypes.includes(selectedFile.type)) {
this.$message.error('只能上传 doc/docx/pdf 格式的文件');
return false;
}
// 验证文件大小(限制大小10MB)
const maxSize = 10 * 1024 * 1024;
if (selectedFile.size > maxSize) {
this.$message.error('文件大小不能超过 10MB');
return false;
}
const blobUrl = URL.createObjectURL(selectedFile);
this.form2.fileList = blobUrl;
this.selectedFile = selectedFile;
return true;
},
handleFileRemove() {
this.form2.fileList = "";
this.$message.success('文件已删除');
}
},
};
|
2301_79970562/student_union_frontend
|
src/assets/js/LandlordHouse.js
|
JavaScript
|
unknown
| 18,433
|
import request from "@/axios/request";
const {ElMessage} = require("element-plus");
export default {
name: "LandlordInfo",
data() {
// 手机号验证
const checkPhone = (rule, value, callback) => {
const phoneReg = /^1[3|4|5|6|7|8][0-9]{9}$/;
if (!value) {
return callback(new Error("电话号码不能为空"));
}
setTimeout(() => {
if (!Number.isInteger(+value)) {
callback(new Error("请输入数字值"));
} else {
if (phoneReg.test(value)) {
callback();
} else {
callback(new Error("电话号码格式不正确"));
}
}
}, 100);
};
// 邮箱验证
const checkEmail = (rule, value, callback) => {
const emailReg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
if (!value) {
return callback(new Error("邮箱不能为空"));
}
setTimeout(() => {
if (emailReg.test(value)) {
callback();
} else {
callback(new Error("邮箱格式不正确"));
}
}, 100);
};
const checkPass = (rule, value, callback) => {
if (!this.editJudge) {
if (value == "") {
callback(new Error("请再次输入密码"));
} else if (value !== this.form.password) {
callback(new Error("两次输入密码不一致!"));
} else {
callback();
}
} else {
callback();
}
};
return {
showpassword: true,
judgeAddOrEdit: true,
loading: true,
editJudge: true,
disabled: false,
judge: false,
dialogVisible: false,
search: "",
currentPage: 1,
pageSize: 10,
total: 0,
allData: [], // 存储全量数据
tableData: [], // 当前页数据
form: {
landlordId: null,
username: "",
password: "",
phone: "",
email: "",
},
rules: {
username: [
{required: true, message: "请输入用户名", trigger: "blur"},
],
password: [
{required: true, message: "请输入密码", trigger: "blur"},
{
min: 6,
max: 32,
message: "长度在 6 到 16 个字符",
trigger: "blur",
},
],
phone: [{required: true, message: "请输入电话号码", validator: checkPhone, trigger: "blur"}],
email: [{type: "email", message: "请输入邮箱地址", validator: checkEmail, trigger: "blur"}],
checkPass: [{validator: checkPass, trigger: "blur"}],
},
editDisplay: {
display: "block",
},
display: {
display: "none",
},
};
},
computed: {
paginatedData() {
const start = (this.currentPage - 1) * this.pageSize;
const end = start + this.pageSize;
return this.allData.slice(start, end);
}
},
created() {
this.load();
this.loading = true;
setTimeout(() => {
this.loading = false;
}, 1000);
},
methods: {
async load() {
try{
const res = await request.get("/landlord/findAll");
if (res.code === 200) {
this.allData = res.data || [];
this.total = this.allData.length;
this.tableData = this.paginatedData;
} else {
ElMessage.error(res.msg || "加载失败");
this.allData = [];
this.tableData = [];
this.total = 0;
}
this.loading = false;
} catch (err){
console.error(err);
ElMessage.error("网络错误,请稍后再试");
this.allData = [];
this.tableData = [];
this.total = 0;
this.loading = false;
}
},
async filterData() {
const res = await request.get("/landlord/findAll");
if (res.code === 200) {
this.allData = res.data || [];
this.total = this.allData.length;
this.tableData = this.paginatedData;
}
let data = this.allData;
if (this.search) {
const id = parseInt(this.search);
data = data.filter(item => item.landlordId === id);
} else {
this.load();
}
this.allData = data;
this.total = data.length;
this.tableData = this.paginatedData;
},
reset() {
this.search = "";
this.currentPage = 1;
this.load();
},
add() {
this.dialogVisible = true;
this.$refs.form.resetFields();
this.judgeAddOrEdit = false;
this.editDisplay = {display: "none"};
this.disabled = false;
this.form = {
landlordId: null,
username: "",
password: "",
phone: "",
email: "",
};
this.judge = false;
},
save() {
this.$refs.form.validate((valid) => {
if (valid) {
if (this.judgeAddOrEdit === false) {
//新增
const { username, password, phone, email } = this.form;
request.post("/landlord/register", { username, password, phone, email }).then((res) => {
if (res.code === 200) {
ElMessage.success("新增成功");
this.dialogVisible = false;
this.load();
} else {
ElMessage.error(res.msg || "新增失败");
}
});
} else {
//修改
request.put("/landlord/updateById", this.form).then((res) => {
if (res.code === 200) {
ElMessage.success("修改成功");
this.dialogVisible = false;
this.load(); // 重新加载全量数据
} else {
ElMessage.error(res.msg || "修改失败");
}
});
}
}
});
},
cancel() {
this.$refs.form.resetFields();
this.display = {display: "none"};
this.editJudge = true;
this.disabled = true;
this.showpassword = true;
this.dialogVisible = false;
},
handleEdit(row) {
this.dialogVisible = true;
// this.$refs.form.resetFields();
this.form = {
landlordId: row.landlordId || null,
username: row.username || '',
password: row.password || '',
phone: row.phone || '',
email: row.email || '',
};
this.judgeAddOrEdit = true;
this.showpassword = true;
this.display = {display: "flex"};
this.disabled = false;
},
async handleDelete(landlordId) {
console.log(landlordId);
//删除
request.delete(`/landlord/delete/${landlordId}`).then((res) => {
if (res.code === 200) {
ElMessage({
message: "删除成功",
type: "success",
});
this.load();
} else {
ElMessage({
message: res.msg,
type: "error",
});
}
});
},
handleSizeChange(pageSize) {
this.pageSize = pageSize;
this.tableData = this.paginatedData;
},
handleCurrentChange(pageNum) {
this.currentPage = pageNum;
this.tableData = this.paginatedData;
},
},
};
|
2301_79970562/student_union_frontend
|
src/assets/js/LandlordInfo.js
|
JavaScript
|
unknown
| 9,050
|
import request from "@/axios/request";
const {ElMessage} = require("element-plus");
export default {
name: "LandlordTransactionRecord",
data() {
return {
loading: true,
landlordId: null,
username: "",
password: "",
phone: "",
email: "",
currentPage: 1,
pageSize: 10,
total: 0,
tenant_total: 0,
transaction_total: 0,
allTransactionData: [],
tableTransactionData: [],
allTenantData: [],
tableTenantData: [],
allData: [], // 存储全量数据
tableData: [], // 当前页数据
// allData: [{
// houseId: 1,
// title: "学院十一峯",
// description: "学院十一峯位于温州市鹿城区滨江街道会展路与学院路交汇处,由金地集团与新希望地产联合开发,2021年竣工交付。项目总户数1276户,包含11栋板塔结合建筑,绿化率30%,容积率3.13,物业费4.7元/㎡·月(含能耗费)。小区定位改善型住宅,主力户型为143-189㎡的四居室,南北通透设计,精装修交付。",
// price: "5000",
// address: "温州市鹿城区滨江街道会展路与学院路交汇处",
// area: "浙江省",
// size: 140,
// rooms: 3,
// floor: 3,
// landlordId: 1,
// status: "待审核",
// imageUrl: "https://img2.baidu.com/it/u=668963934,1194070255&fm=253&fmt=auto&app=138&f=JPEG?w=661&h=500"
// }]
};
},
computed: {
paginatedData() {
const start = (this.currentPage - 1) * this.pageSize;
const end = start + this.pageSize;
return this.allData.slice(start, end);
},
paginatedTenantData() {
const start = (this.currentPage - 1) * this.pageSize;
const end = start + this.pageSize;
return this.allTenantData.slice(start, end);
},
paginatedTransactionData() {
const start = (this.currentPage - 1) * this.pageSize;
const end = start + this.pageSize;
return this.allTransactionData.slice(start, end);
}
},
created() {
this.loadMyInfo();
this.load();
this.loading = true;
setTimeout(() => {
this.loading = false;
}, 1000);
},
methods: {
async load() {
try{
// 获取所有房屋信息
const res = await request.get("/house/findAll");
if (res.code === 200) {
this.allData = res.data || [];
this.total = this.allData.length;
this.tableData = this.paginatedData;
} else {
ElMessage.error(res.msg || "加载失败");
this.allData = [];
this.tableData = [];
this.total = 0;
}
// 获取所有租户信息
const res_tenant = await request.get("/tenant/findAll");
if (res_tenant.code === 200) {
this.allTenantData = res_tenant.data || [];
this.tenant_total = this.allTenantData.length;
this.tableTenantData = this.paginatedTenantData;
} else {
ElMessage.error(res_tenant.msg || "加载失败");
this.allTenantData = [];
this.tableTenantData = [];
this.tenant_total = 0;
}
const token = JSON.parse(window.sessionStorage.getItem('userInfo'));
this.landlord = token.landlordId;
// 获取所有交易信息
const res_transaction = await request.get(`/record/landlord/${this.landlordId}`);
if (res_transaction.code === 200) {
this.allTransactionData = res_transaction.data || [];
this.transaction_total = this.allTransactionData.length;
this.tableTransactionData = this.paginatedTransactionData;
} else {
ElMessage.error(res_transaction.msg || "加载失败");
this.allTransactionData = [];
this.tableTransactionData = [];
this.transaction_total = 0;
}
this.loading = false;
} catch (err){
console.error(err);
ElMessage.error("网络错误,请稍后再试");
this.allData = [];
this.tableData = [];
this.total = 0;
this.allTenantData = [];
this.tableTenantData = [];
this.tenant_total = 0;
this.allTransactionData = [];
this.tableTransactionData = [];
this.transaction_total = 0;
this.loading = false;
}
},
loadMyInfo() {
const token = JSON.parse(window.sessionStorage.getItem('userInfo'));
if(!token) {
ElMessage.error("获取用户信息失败");
console.log("获取用户信息失败");
return;
}
this.landlordId = token.landlordId;
this.username = token.username;
this.password = token.password;
this.phone = token.phone;
this.email = token.email;
},
SignOut() {
sessionStorage.clear()
ElMessage({
message: '用户退出登录',
type: 'success',
});
this.$router.replace({path: '/Login'});
},
handleSizeChange(pageSize) {
this.pageSize = pageSize;
this.tableData = this.paginatedData;
},
handleCurrentChange(pageNum) {
this.currentPage = pageNum;
this.tableData = this.paginatedData;
},
getTitle(houseId) {
const house = this.allData.find(item => item.houseId === houseId);
if (house.title === ""){
return "未知名称";
}
return house.title;
},
getTenantUsername(tenantId) {
const tenant = this.allTenantData.find(item => item.tenantId === tenantId);
if (tenant.username === ""){
return "未知用户";
}
return tenant.username;
},
getTenantPhone(tenantId) {
const tenant = this.allTenantData.find(item => item.tenantId === tenantId);
if (tenant.phone === ""){
return "未知电话号码";
}
return tenant.phone;
},
getTenantEmail(tenantId) {
const tenant = this.allTenantData.find(item => item.tenantId === tenantId);
if (tenant.email === ""){
return "未知邮箱";
}
return tenant.email;
},
//时间显示
formatTime(isoTime) {
if (!isoTime) return "-";
const date = new Date(isoTime);
// 手动格式化避免浏览器差异
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hour = String(date.getHours()).padStart(2, '0');
const minute = String(date.getMinutes()).padStart(2, '0');
const second = String(date.getSeconds()).padStart(2, '0');
return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
},
},
};
|
2301_79970562/student_union_frontend
|
src/assets/js/LandlordTransactionRecord.js
|
JavaScript
|
unknown
| 7,903
|
// src/views/Login.js
import request from "@/axios/request";
import { ElMessage } from "element-plus";
export default {
name: "Login",
data() {
return {
identity: "",
form: {
username: "",
password: "",
identity: "",
},
rules: {
username: [
{ required: true, message: "请输入用户名", trigger: "blur" },
],
password: [{ required: true, message: "请输入密码", trigger: "blur" }],
identity: [{ required: true, message: "请选择身份", trigger: "blur" }],
},
};
},
computed: {
disabled() {
const { username, password, identity } = this.form;
return Boolean(username && password && identity);
},
},
methods: {
// 原有的登录方法
login() {
this.$refs.form.validate((valid) => {
if (valid) {
this.identity = this.form.identity;
request.post("/" + this.identity + "/login", this.form).then((res) => {
if (res.code === 200) {
ElMessage({
message: "登录成功",
type: "success",
});
window.sessionStorage.setItem("userInfo", JSON.stringify(res.data));
window.sessionStorage.setItem("identity", JSON.stringify(this.form.identity));
this.$router.push("/" + this.form.identity + "Home");
} else {
ElMessage({
message: res.msg,
type: "error",
});
}
});
}
});
},
// 新增的跳转方法
goToFaceRecognition() {
// 使用 window.location.href 进行完整的页面跳转
window.location.href = 'http://localhost:8085/3.html';
},
},
};
|
2301_79970562/student_union_frontend
|
src/assets/js/Login.js
|
JavaScript
|
unknown
| 1,774
|
import request from "@/axios/request";
const {ElMessage} = require("element-plus");
export default {
name: "Login",
data() {
return {
identity: "",
form: {
username: "",
password: "",
identity: "",
},
rules: {
username: [
{required: true, message: "请输入用户名", trigger: "blur"},
],
password: [{required: true, message: "请输入密码", trigger: "blur"}],
identity: [{required: true, message: "请选择身份", trigger: "blur"}],
},
};
},
computed: {
disabled() {
const {username, password, identity} = this.form;
return Boolean(username && password && identity);
},
},
methods: {
login() {
this.$refs.form.validate((valid) => {
if (valid) {
this.identity = this.form.identity;
request.post("/" + this.identity + "/login", this.form).then((res) => {
if (res.code === 200) {
ElMessage({
message: "登录成功",
type: "success",
});
window.sessionStorage.setItem("userInfo", JSON.stringify(res.data));
window.sessionStorage.setItem("identity", JSON.stringify(this.form.identity));
this.$router.push("/"+this.form.identity+"Home");
} else {
ElMessage({
message: res.msg,
type: "error",
});
}
});
}
});
},
},
};
|
2301_79970562/student_union_frontend
|
src/assets/js/Login1.js
|
JavaScript
|
unknown
| 1,924
|
import request from "@/axios/request";
const { ElMessage } = require("element-plus");
export default {
name: "Register",
data() {
return {
form: {
username: "",
password: "",
phone: "",
email: "",
identity: ""
},
rules: {
username: [
{ required: true, message: "请输入用户名", trigger: "blur" }
],
password: [
{ required: true, message: "请输入密码", trigger: "blur" }
],
phone: [
{ required: true, message: "请输入电话号码", trigger: "blur" },
{ pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号", trigger: "blur" }
],
email: [
{ required: true, message: "请输入邮箱地址", trigger: "blur" },
{ type: "email", message: "请输入正确的邮箱格式", trigger: ["blur", "change"] }
],
identity: [
{ required: true, message: "请选择身份", trigger: "change" }
]
}
};
},
computed: {
disabled() {
const { username, password, phone, email, identity } = this.form;
return Boolean(username && password && phone && email && identity);
}
},
methods: {
register() {
this.$refs.form.validate(async valid => {
if (valid) {
if (this.form.identity === 'admin') {
const allowedPhone1 = '19853228572';
const allowedPhone2 = '13501793363';
const allowedPhone3 = '18169836217';
const allowedPhone4 = '19863753121';
if (this.form.phone !== allowedPhone1
&& this.form.phone !== allowedPhone2
&& this.form.phone !== allowedPhone3
&& this.form.phone !== allowedPhone4
) {
try {
await this.$confirm(
'非团队成员,没有管理员注册权限',
'提示',
{
confirmButtonText: '确认',
type: 'error',
closeOnClickModal: false,
closeOnPressEscape: false,
lockScroll: true
}
);
} catch (err) {}
}
}
const urlMap = {
tenant: "/tenant/register",
landlord: "/landlord/register",
admin: "/admin/register"
};
const url = urlMap[this.form.identity];
if (!url) {
ElMessage.error("未知的身份类型");
return;
}
const { username, password, phone, email } = this.form;
request.post(url, { username, password, phone, email }).then(res => {
if (res.code === 200) {
ElMessage({
message: "注册并登录成功",
type: "success",
});
window.sessionStorage.setItem("userInfo", JSON.stringify(res.data));
window.sessionStorage.setItem("identity", JSON.stringify(this.form.identity));
this.$router.push("/"+this.form.identity+"Home");
} else {
ElMessage({
message: res.msg,
type: "error",
});
}
}).catch(err => {
ElMessage.error("网络错误,请稍后再试");
console.error(err);
});
}
});
}
}
};
|
2301_79970562/student_union_frontend
|
src/assets/js/Register.js
|
JavaScript
|
unknown
| 3,780
|
import request from "@/axios/request";
import { ElMessage } from "element-plus";
export default {
name: "SelectHouse",
data() {
return {
loading: true,
search: "",
allData: [], // 存储所有房源数据
displayData: [], // 存储当前显示的房源数据
originalData: [], // 备份原始数据用于重置搜索
total: 0,
// 用户信息
userInfo: {
tenantId: null,
username: "",
phone: "",
email: ""
},
// 状态映射
statusMap: {
rented: { text: '已租', type: 'info' },
available: { text: '待租', type: 'success' },
pending: { text: '审核中', type: 'warning' },
rejected: { text: '审核未通过', type: 'danger' }
}
};
},
created() {
this.loadMyInfo();
this.load();
},
methods: {
async load() {
this.loading = true;
try{
const res = await request.get("/house/findAll");
if (res.code === 200) {
// 保留原始状态码,新增 displayStatus 字段用于显示
this.allData = (res.data || []).map(item => ({
...item,
displayStatus: this.statusMap[item.status]?.text || '未知状态'
}));
this.total = this.allData.length;
}
if (res.code === 200) {
this.allData = res.data || [];
this.originalData = [...this.allData]; // 备份原始数据
this.displayData = [...this.allData]; // 初始化显示数据
this.total = this.displayData.length;
} else {
ElMessage.error(res.msg || "加载失败");
this.displayData = [];
this.total = 0;
}
} catch (err) {
console.error(err);
ElMessage.error("网络错误,请稍后再试");
this.displayData = [];
this.total = 0;
} finally {
this.loading = false;
}
},
loadMyInfo() {
const userInfo = JSON.parse(window.sessionStorage.getItem('userInfo'));
if (!userInfo) {
ElMessage.error("获取用户信息失败");
console.log("获取用户信息失败");
return;
}
// 根据实际情况获取用户信息字段
this.userInfo = {
tenantId: userInfo.tenantId || null,
username: userInfo.username || "",
phone: userInfo.phone || "",
email: userInfo.email || ""
};
},
SignOut() {
sessionStorage.clear();
ElMessage({
message: '用户退出登录',
type: 'success',
});
this.$router.replace({ path: '/Login' });
},
// 搜索房源
async SearchHouse() {
const keyword = this.search.trim();
if (!keyword) {
this.ResetSearch(); // 如果关键词为空,重置搜索
return;
}
this.loading = true;
try {
const res1 = await request.get(`/house/title/${encodeURIComponent(keyword)}`);
const res2 = await request.get(`/house/area/${encodeURIComponent(keyword)}`);
let res = 200;
let mergedData = [];
if(res1.code === 200 && res2.code === 200)
{
res=200;
mergedData = [...res1.data, ...res2.data];
}else if(res1.code === 200 && res2.code !== 200){
res=200;
mergedData = [...res1.data];
}else if(res1.code !== 200 && res2.code === 200){
res=200;
mergedData = [...res2.data];
}
// 统一处理API响应结构
if (res === 200) {
this.displayData = mergedData || [];
this.total = this.displayData.length;
} else {
ElMessage.error(res.msg || "搜索失败");
this.displayData = [];
this.total = 0;
}
} catch (err) {
console.error(err);
ElMessage.error("网络错误,请稍后再试");
this.displayData = [];
this.total = 0;
} finally {
this.loading = false;
}
},
// 重置搜索
ResetSearch() {
this.search = "";
this.displayData = [...this.originalData]; // 恢复原始数据
this.total = this.displayData.length;
},
// 状态标签类型获取方法
getStatusTagType(status) {
return this.statusMap[status]?.type || '';
},
// 状态标签文本获取方法
getStatusLabel(status) {
return this.statusMap[status]?.text || '未知状态';
}
}
}
|
2301_79970562/student_union_frontend
|
src/assets/js/SelectHouse.js
|
JavaScript
|
unknown
| 5,484
|
import request from "@/axios/request";
const { ElMessage } = require("element-plus");
export default {
name: "TenantApplication",
data() {
return {
loading: true,
// 租户信息
tenantId: "",
username: "", // 新增:存储用户名
// 申请数据
total: 0,
allData: [], // 接口返回的所有申请数据
filteredData: [], // 筛选后的数据
// 状态筛选开关(修复:变量名统一)
pending: true,
approved: true,
rejected: true,
// 房源信息映射
houseMap: new Map() // 格式: Map(houseId => { title, address, ... })
};
},
watch: {
pending: { handler() { this.filterData(); } },
approved: { handler() { this.filterData(); } },
rejected: { handler() { this.filterData(); } }
},
created() {
this.loading = true;
// 获取租户ID和用户名
const userInfo = JSON.parse(window.sessionStorage.getItem('userInfo') || '{}');
this.tenantId = userInfo.tenantId || '';
this.username = userInfo.username || '用户'; // 新增:从session获取用户名
// 修复:页面加载时主动加载数据
this.initData();
},
methods: {
// 初始化数据
async initData() {
// 先加载申请记录,再加载房源信息
await this.loadApplications();
await this.loadHouseMap();
this.loading = false;
},
async loadApplications() {
try {
const res = await request.get(`/rental/tenant/${this.tenantId}`);
if (res.code === 200) {
this.allData = res.data || [];
this.total = this.allData.length;
// 格式化申请时间
this.allData.forEach(item => {
item.formattedTime = this.formatTime(item.applicationTime);
});
// 空数据提示
if (this.total === 0) {
ElMessage.info("当前没有申请记录");
} else {
ElMessage.success(`加载成功,共${this.total}条申请`);
}
this.filterData(); // 筛选数据
} else {
ElMessage.error(res.msg || "加载申请失败");
this.allData = [];
this.total = 0;
}
} catch (err) {
console.error("加载申请出错:", err);
ElMessage.error("网络错误,请稍后重试");
this.allData = [];
this.total = 0;
}
},
//申请的房源信息
async loadHouseMap() {
try {
// 提取所有申请记录中的houseId
const houseIds = [...new Set(this.allData.map(item => item.houseId).filter(Boolean))];
if (houseIds.length === 0) {
console.log("没有需要加载的房源ID");
return;
}
// 查询房源信息
for (const houseId of houseIds) {
try {
const res = await request.get(`/house/${houseId}`);
if (res.code === 200 && res.data) {
this.houseMap.set(houseId, res.data);
} else {
console.warn(`房源ID: ${houseId} 查询失败,原因:${res.msg || '未知错误'}`);
}
} catch (err) {
console.error(`加载房源ID: ${houseId} 时出错:`, err);
}
}
console.log(`共加载 ${this.houseMap.size}/${houseIds.length} 个房源信息`);
} catch (err) {
ElMessage.warning("房源信息加载失败,部分详情可能无法显示");
}
},
// 筛选申请列表
filterData() {
this.filteredData = this.allData.filter(item => {
if (item.status === "pending" && this.pending) return true;
if (item.status === "approved" && this.approved) return true;
if (item.status === "rejected" && this.rejected) return true;
return false;
});
},
//时间显示
formatTime(isoTime) {
if (!isoTime) return "-";
const date = new Date(isoTime);
// 手动格式化避免浏览器差异
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hour = String(date.getHours()).padStart(2, '0');
const minute = String(date.getMinutes()).padStart(2, '0');
const second = String(date.getSeconds()).padStart(2, '0');
return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
},
//申请类型
getTypeLabel(type) {
const typeMap = {
"in": "入住申请",
"out": "退房申请",
};
return typeMap[type] || "未知类型";
},
//退出登录
SignOut() {
sessionStorage.clear();
ElMessage.success("已退出登录");
this.$router.replace("/Login");
},
//状态标签样式
getStatusTagType(status) {
switch (status) {
case "pending": return "warning";
case "approved": return "success";
case "rejected": return "danger";
default: return "info";
}
},
//状态文本
getStatusLabel(status) {
switch (status) {
case "pending": return "待审核";
case "approved": return "已通过";
case "rejected": return "已拒绝";
default: return "未知状态";
}
},
//加快审批(无功能,起到一个造型上的作用)
async handleSpeedUp(row) {
try {
ElMessage.warning("已加速审批");
} catch (err) {
console.error("加快审批出错:", err);
ElMessage.error("操作失败,请稍后重试");
}
},
//删除beijujuede申请
async handleDelete(row) {
if (row.status !== "rejected") {
ElMessage.warning("仅已拒绝的申请可删除");
return;
}
try {
const res = await request.delete(`/rental/delete/${row.applicationId}`);
if (res.code === 200) {
ElMessage.success("申请已删除");
this.loadApplications(); // 重新加载
} else {
ElMessage.error(res.msg || "删除失败");
}
} catch (err) {
console.error("删除申请出错:", err);
ElMessage.error("网络错误");
}
},
//退房申请
async handleCheckOut(row) {
// 校验:仅已通过的入住申请可提交退房
if (row.status !== "approved" || row.type !== "in") {
ElMessage.warning("仅已通过的入住申请可提交退房");
return;
}
try {
// 申请数据
const requestData = {
tenantId: this.tenantId,
houseId: row.houseId,
type: "out"
};
const res = await request.post("/rental/apply", requestData);
if (res.code === 200) {
ElMessage.success("退房申请已提交");
this.loadApplications(); // 重新加载申请列表
}
else if (res.code === 404) {
ElMessage.warning(res.msg || "未找到对应的租房申请,无法提交退房");
} else {
ElMessage.error(res.msg || "申请失败,请稍后重试");
}
} catch (err) {
ElMessage.error("网络错误");
}
}
}
};
|
2301_79970562/student_union_frontend
|
src/assets/js/TenantApplication.js
|
JavaScript
|
unknown
| 7,273
|
import request from "@/axios/request";
import { ElMessage } from "element-plus";
export default {
name: "TenantApplicationHouseDisplay",
data() {
return {
loading: true,
Data: {},
isFavorited: false,
tenantId: '',
comments: [], // 存储当前房源的评论列表
userMap: {},
commentCount: 0, // 评论数量
rating: 0, // 评分
colors: ['#99A9BF', '#F7BA1E', '#FF9900'], // 评分星星的颜色,2,3,4是颜色分界
// 状态映射
statusMap: {
rented: { text: '已租', type: 'info' },
available: { text: '待租', type: 'success' },
pending: { text: '审核中', type: 'warning' },
rejected: { text: '审核未通过', type: 'danger' }
},
};
},
created() {
const houseId = this.$route.query.houseId;
this.load(houseId);
this.loadComments(houseId);
this.loading = true;
//获取当前登录用户ID(TenantSelfInfo)
const userInfo = JSON.parse(window.sessionStorage.getItem('userInfo') || '{}');
this.tenantId = userInfo.tenantId || ''; // 从sessionStorage中提取tenantId
this.loadFavoriteStatus(houseId,this.tenantId);
},
methods: {
// 房屋详情
async load(houseId) {
this.loading = true;
try{
const res = await request.get(`/house/${houseId}`);
if (res.code === 200) {
// 保留原始状态码,新增 displayStatus 字段用于显示
this.Data = res.data;
this.Data.displayStatus = this.statusMap[this.Data.status]?.text || '未知状态';
} else {
ElMessage.error(res.msg || "加载失败");
this.Data = {};
}
} catch (err){
console.error(err);
ElMessage.error("网络错误,请稍后再试");
} finally {
this.loading = false; // 接口请求完成后关闭loading
}
},
// 评论列表
async loadComments(houseId) {
try {
// 先清空旧数据
this.userMap = {};
this.comments = [];
this.commentCount = 0;
const res = await request.get(`/comment/house/${houseId}`);
// 如果接口调用失败,直接提示并 return
if (res.code !== 200) {
// ElMessage.error(res.msg || '加载评论失败');
return;
}
// 此时 res.code === 200
const list = Array.isArray(res.data) ? res.data : [];
// 只有在确实有评论时才去拉用户名
if (list.length > 0) {
// 并行请求所有用户名
await Promise.all(
list.map(async (comment) => {
try {
const userRes = await request.get(`/tenant/findById/${comment.tenantId}`);
// 强制转成字符串 key,以防类型不一致
this.userMap[String(comment.tenantId)] = (userRes.code === 200 && userRes.data.username) || '匿名用户';
} catch {
this.userMap[String(comment.tenantId)] = '匿名用户';
}
})
);
}
// 最后赋值评论列表
this.comments = list;
this.commentCount = list.length;
} catch (err) {
console.error("加载评论失败:", err);
ElMessage.error("加载评论失败,请稍后重试");
}
},
//时间显示
formatDate(dateStr) {
if (!dateStr) return "";
const date = new Date(dateStr);
return date.toLocaleString("zh-CN", {
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
});
},
async loadFavoriteStatus(houseId, tenantId) {
try {
const res = await request.post(`/favorite/tenantAndHouse` ,{
tenantId: tenantId,
houseId: houseId
});
if (res.code === 200) {
this.isFavorited = true;
}else if (res.code === 404) {
this.isFavorited = false;
}
} catch (err) {
console.error("获取收藏状态失败:", err);
}
},
// 切换收藏/取消收藏
async handleFavorite() {
// 先乐观更新
try {
if (this.isFavorited) {
await request.delete("/favorite/cancel", {
data: {
houseId: this.Data.houseId,
tenantId: this.tenantId
}
});
}else {
await request.post("/favorite/add", {
houseId: this.Data.houseId,
tenantId: this.tenantId
});
}
console.log(this.tenantId);
this.isFavorited = !this.isFavorited;
ElMessage.success(this.isFavorited ? "已收藏" : "已取消收藏");
} catch (err) {
// 回滚
this.isFavorited = !this.isFavorited;
console.error(err);
ElMessage.error("操作失败,请重试");
}
},
// 提交评论
async subComment() {
// 判断用户是否评论过
const hasCommented = this.comments.some(
comment => String(comment.tenantId) === String(this.tenantId)//判断用户名是否已存在
);
if (hasCommented) {
ElMessage.warning('用户仅允许提交一次评论');
this.commentContent = '';
this.rating = 0;
return;
}
try {
// 构建评论数据
const commentData = {
houseId: this.$route.query.houseId,
tenantId: this.tenantId,
content: this.commentContent.trim(),
rating: this.rating
};
// 调用后端接口
const res = await request.post(`/comment/add`, commentData);
if (res.code === 200) {
// 评论成功
ElMessage.success('评论提交成功');
// 清空表单
this.commentContent = '';
this.rating = 0;
// 刷新评论列表
await this.loadComments(this.$route.query.houseId);
} else {
// 评论失败
ElMessage.error(res.msg || '评论提交失败');
}
} catch (err) {
console.error("提交评论错误:", err);
ElMessage.error('网络错误,请稍后再试');
}
},
async subapplication(){
//判断房源的状态
const res = await request.get(`/house/${this.Data.houseId}`);
if (res.code === 200 && res.data.status !== "available") {
ElMessage.warning('该房源已不可申请');
return;
}
try {
//申请数据
const res = await request.post(`/rental/apply`, {
houseId: this.Data.houseId,
tenantId: this.tenantId,
type: "in",
});
if (res.code === 200) {
ElMessage.success('申请提交成功');
} else {
ElMessage.error(res.msg || '申请提交失败');
}
} catch (err) {
console.error("提交申请错误:", err);
ElMessage.error('网络错误,请稍后再试');
}
},
// 状态标签类型获取方法
getStatusTagType(status) {
return this.statusMap[status]?.type || '';
},
// 状态标签文本获取方法
getStatusLabel(status) {
return this.statusMap[status]?.text || '未知状态';
}
},
};
|
2301_79970562/student_union_frontend
|
src/assets/js/TenantApplicationHouseDisplay.js
|
JavaScript
|
unknown
| 8,872
|
import request from "@/axios/request";
const {ElMessage} = require("element-plus");
export default {
name: "TenantFavorite",
data() {
return {
loading: true,
search: "",
allData: [], // 存储所有房源数据
displayData: [], // 存储当前显示的房源数据
originalData: [], // 备份原始数据用于重置搜索
total: 0,
username: "",
// 用户信息
userInfo: {
tenantId: null,
username: "",
phone: "",
email: ""
},
// 状态映射
statusMap: {
rented: { text: '已租', type: 'info' },
available: { text: '待租', type: 'success' },
pending: { text: '审核中', type: 'warning' },
rejected: { text: '审核未通过', type: 'danger' }
},
};
},
created() {
this.loadMyInfo();
this.load();
this.loading = true;
setTimeout(() => {
this.loading = false;
}, 1000);
},
methods: {
async load() {
this.loading = true;
try {
let token = JSON.parse(window.sessionStorage.getItem('userInfo'));
let tenantId = token.tenantId;
let favoriteId = await request.get(`/favorite/tenant/${tenantId}`);
let data = [];
if (favoriteId.code === 200) {
// 保留原始状态码,新增 displayStatus 字段用于显示
this.allData = (favoriteId.data || []).map(item => ({
...item,
displayStatus: this.statusMap[item.status]?.text || '未知状态'
}));
this.total = this.allData.length;
}
if (favoriteId.code === 200) {
for (let i = 0; i < favoriteId.data.length; i++) {
let houseId = favoriteId.data[i].houseId;
let house = await request.get(`/house/${houseId}`);
data.push(house.data);
}
this.allData = data || [];
this.originalData = [...this.allData]; // 备份原始数据
this.displayData = [...this.allData]; // 初始化显示数据
this.total = this.displayData.length;
}
else if( favoriteId.code === 404) {
ElMessage.warning("您还没有收藏房源");}
else {
ElMessage.error(favoriteId.msg || "加载失败");
this.displayData = [];
this.total = 0;
}
} catch (err) {
console.error(err);
ElMessage.error("网络错误,请稍后再试");
this.displayData = [];
this.total = 0;
} finally {
this.loading = false;
}
this.username = token.username;
},
loadMyInfo() {
const userInfo = JSON.parse(window.sessionStorage.getItem('userInfo'));
if (!userInfo) {
ElMessage.error("获取用户信息失败");
console.log("获取用户信息失败");
return;
}
// 根据实际情况获取用户信息字段
this.userInfo = {
tenantId: userInfo.tenantId || null,
username: userInfo.username || "",
phone: userInfo.phone || "",
email: userInfo.email || ""
};
this.username = userInfo.username;
},
SignOut() {
sessionStorage.clear()
ElMessage({
message: '用户退出登录',
type: 'success',
});
this.$router.replace({path: '/Login'});
},
// 状态标签类型获取方法
getStatusTagType(status) {
return this.statusMap[status]?.type || '';
},
// 状态标签文本获取方法
getStatusLabel(status) {
return this.statusMap[status]?.text || '未知状态';
}
},
};
|
2301_79970562/student_union_frontend
|
src/assets/js/TenantFavorite.js
|
JavaScript
|
unknown
| 4,371
|
import request from "@/axios/request";
const {ElMessage} = require("element-plus");
export default {
name: "TenantHome",
data() {
return {
loading: true,
landlordId: null,
username: "",
password: "",
phone: "",
email: "",
images: [
{ src: require('@/assets/landlord_banner1.png'), alt: 'pic1' },
{ src: require('@/assets/landlord_banner2.png'), alt: 'pic2' },
{ src: require('@/assets/landlord_banner4.png'), alt: 'pic3' },
{ src: require('@/assets/landlord_banner3.png'), alt: 'pic4' }
],
total: 0,
allData: [],
firstSixData: [],
// 状态映射
statusMap: {
rented: { text: '已租', type: 'info' },
available: { text: '待租', type: 'success' },
pending: { text: '审核中', type: 'warning' },
rejected: { text: '审核未通过', type: 'danger' }
}
};
},
computed: {
paginatedData() {
const start = 0;
const end = 6;
return this.allData.slice(start, end);
}
},
created() {
this.loadMyInfo();
this.load();
this.loading = true;
setTimeout(() => {
this.loading = false;
}, 1000);
},
methods: {
async load() {
try{
const res = await request.get("/house/findAll");
if (res.code === 200) {
// 保留原始状态码,新增 displayStatus 字段用于显示
this.allData = (res.data || []).map(item => ({
...item,
displayStatus: this.statusMap[item.status]?.text || '未知状态'
}));
this.total = this.allData.length;
this.firstSixData = this.paginatedData;
} else {
ElMessage.error(res.msg || "加载失败");
this.allData = [];
this.firstSixData = [];
this.total = 0;
}
this.loading = false;
} catch (err){
console.error(err);
ElMessage.error("网络错误,请稍后再试");
this.allData = [];
this.firstSixData = [];
this.total = 0;
this.loading = false;
}
},
loadMyInfo() {
const token = JSON.parse(window.sessionStorage.getItem('userInfo'));
if(!token) {
ElMessage.error("获取用户信息失败");
console.log("获取用户信息失败");
return;
}
this.TenantId = token.TenantId;
this.username = token.username;
this.password = token.password;
this.phone = token.phone;
this.email = token.email;
},
SignOut() {
sessionStorage.clear()
ElMessage({
message: '用户退出登录',
type: 'success',
});
this.$router.replace({path: '/Login'});
},
// 状态标签类型获取方法
getStatusTagType(status) {
return this.statusMap[status]?.type || '';
},
// 状态标签文本获取方法
getStatusLabel(status) {
return this.statusMap[status]?.text || '未知状态';
}
},
};
|
2301_79970562/student_union_frontend
|
src/assets/js/TenantHome.js
|
JavaScript
|
unknown
| 3,623
|
import request from "@/axios/request";
const {ElMessage} = require("element-plus");
export default {
name: "TenantInfo",
data() {
// 手机号验证
const checkPhone = (rule, value, callback) => {
const phoneReg = /^1[3|4|5|6|7|8][0-9]{9}$/;
if (!value) {
return callback(new Error("电话号码不能为空"));
}
setTimeout(() => {
if (!Number.isInteger(+value)) {
callback(new Error("请输入数字值"));
} else {
if (phoneReg.test(value)) {
callback();
} else {
callback(new Error("电话号码格式不正确"));
}
}
}, 100);
};
// 邮箱验证
const checkEmail = (rule, value, callback) => {
const emailReg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
if (!value) {
return callback(new Error("邮箱不能为空"));
}
setTimeout(() => {
if (emailReg.test(value)) {
callback();
} else {
callback(new Error("邮箱格式不正确"));
}
}, 100);
};
const checkPass = (rule, value, callback) => {
if (!this.editJudge) {
if (value == "") {
callback(new Error("请再次输入密码"));
} else if (value !== this.form.password) {
callback(new Error("两次输入密码不一致!"));
} else {
callback();
}
} else {
callback();
}
};
return {
showpassword: true,
judgeAddOrEdit: true,
loading: true,
editJudge: true,
disabled: false,
judge: false,
dialogVisible: false,
search: "",
former_search: "",
currentPage: 1,
pageSize: 10,
total: 0,
allData: [], // 存储全量数据
tableData: [], // 当前页数据
form: {
tenantId: null,
username: "",
password: "",
phone: "",
email: "",
},
rules: {
username: [
{required: true, message: "请输入用户名", trigger: "blur"},
],
password: [
{required: true, message: "请输入密码", trigger: "blur"},
{
min: 6,
max: 32,
message: "长度在 6 到 16 个字符",
trigger: "blur",
},
],
phone: [{required: true, message: "请输入电话号码", validator: checkPhone, trigger: "blur"}],
email: [{type: "email", message: "请输入邮箱地址", validator: checkEmail, trigger: "blur"}],
checkPass: [{validator: checkPass, trigger: "blur"}],
},
editDisplay: {
display: "block",
},
display: {
display: "none",
},
};
},
computed: {
paginatedData() {
const start = (this.currentPage - 1) * this.pageSize;
const end = start + this.pageSize;
return this.allData.slice(start, end);
}
},
created() {
this.load();
this.loading = true;
setTimeout(() => {
this.loading = false;
}, 1000);
},
methods: {
async load() {
try{
const res = await request.get("/tenant/findAll");
if (res.code === 200) {
this.allData = res.data || [];
this.total = this.allData.length;
this.tableData = this.paginatedData;
} else {
ElMessage.error(res.msg || "加载失败");
this.allData = [];
this.tableData = [];
this.total = 0;
}
this.loading = false;
} catch (err){
console.error(err);
ElMessage.error("网络错误,请稍后再试");
this.allData = [];
this.tableData = [];
this.total = 0;
this.loading = false;
}
},
async filterData() {
const res = await request.get("/tenant/findAll");
if (res.code === 200) {
this.allData = res.data || [];
this.total = this.allData.length;
this.tableData = this.paginatedData;
}
let data = this.allData;
if (this.search) {
const id = parseInt(this.search);
data = data.filter(item => item.tenantId === id);
} else {
this.load();
}
this.allData = data;
this.total = data.length;
this.tableData = this.paginatedData;
},
reset() {
this.search = "";
this.currentPage = 1;
this.load();
},
add() {
this.dialogVisible = true;
this.$refs.form.resetFields();
this.judgeAddOrEdit = false;
this.editDisplay = {display: "none"};
this.disabled = false;
this.form = {
tenantId: null,
username: "",
password: "",
phone: "",
email: "",
};
this.judge = false;
},
save() {
this.$refs.form.validate((valid) => {
if (valid) {
if (this.judgeAddOrEdit === false) {
//新增
const { username, password, phone, email } = this.form;
request.post("/tenant/register", { username, password, phone, email }).then((res) => {
if (res.code === 200) {
ElMessage.success("新增成功");
this.dialogVisible = false;
this.load();
} else {
ElMessage.error(res.msg || "新增失败");
}
});
} else {
//修改
request.put("/tenant/updateById", this.form).then((res) => {
if (res.code === 200) {
ElMessage.success("修改成功");
this.dialogVisible = false;
this.load(); // 重新加载全量数据
} else {
ElMessage.error(res.msg || "修改失败");
}
});
}
}
});
},
cancel() {
this.$refs.form.resetFields();
this.display = {display: "none"};
this.editJudge = true;
this.disabled = true;
this.showpassword = true;
this.dialogVisible = false;
},
handleEdit(row) {
this.dialogVisible = true;
// this.$refs.form.resetFields();
this.form = {
tenantId: row.tenantId || null,
username: row.username || '',
password: row.password || '',
phone: row.phone || '',
email: row.email || '',
};
this.judgeAddOrEdit = true;
this.showpassword = true;
this.display = {display: "flex"};
this.disabled = false;
},
async handleDelete(tenantId) {
console.log(tenantId);
//删除
request.delete(`/tenant/delete/${tenantId}`).then((res) => {
if (res.code === 200) {
ElMessage({
message: "删除成功",
type: "success",
});
this.load();
} else {
ElMessage({
message: res.msg,
type: "error",
});
}
});
},
handleSizeChange(pageSize) {
this.pageSize = pageSize;
this.tableData = this.paginatedData;
},
handleCurrentChange(pageNum) {
this.currentPage = pageNum;
this.tableData = this.paginatedData;
},
},
};
|
2301_79970562/student_union_frontend
|
src/assets/js/TenantInfo.js
|
JavaScript
|
unknown
| 9,053
|
import request from "@/axios/request";
const { ElMessage } = require("element-plus");
export default {
name: "TenantRecord",
data() {
return {
loading: true,
tenantId: null,
username: "",
password: "",
phone: "",
email: "",
currentPage: 1,
pageSize: 10,
total: 0,
tenant_total: 0,
transaction_total: 0,
allTransactionData: [],
tableTransactionData: [],
allLandlordData: [],
tableLandlordData: [],
allData: [], // 存储全量数据
tableData: [], // 当前页数据
// allData: [{
// houseId: 1,
// title: "学院十一峯",
// description: "学院十一峯位于温州市鹿城区滨江街道会展路与学院路交汇处,由金地集团与新希望地产联合开发,2021年竣工交付。项目总户数1276户,包含11栋板塔结合建筑,绿化率30%,容积率3.13,物业费4.7元/㎡·月(含能耗费)。小区定位改善型住宅,主力户型为143-189㎡的四居室,南北通透设计,精装修交付。",
// price: "5000",
// address: "温州市鹿城区滨江街道会展路与学院路交汇处",
// area: "浙江省",
// size: 140,
// rooms: 3,
// floor: 3,
// landlordId: 1,
// status: "待审核",
// imageUrl: "https://img2.baidu.com/it/u=668963934,1194070255&fm=253&fmt=auto&app=138&f=JPEG?w=661&h=500"
// }]
};
},
computed: {
paginatedData() {
const start = (this.currentPage - 1) * this.pageSize;
const end = start + this.pageSize;
return this.allData.slice(start, end);
},
paginatedLandlordData() {
const start = (this.currentPage - 1) * this.pageSize;
const end = start + this.pageSize;
return this.allLandlordData.slice(start, end);
},
paginatedTransactionData() {
const start = (this.currentPage - 1) * this.pageSize;
const end = start + this.pageSize;
return this.allTransactionData.slice(start, end);
}
},
created() {
this.loadMyInfo();
this.load();
this.loading = true;
setTimeout(() => {
this.loading = false;
}, 1000);
},
methods: {
async load() {
try{
// 获取所有房屋信息
const res = await request.get("/house/findAll");
if (res.code === 200) {
this.allData = res.data || [];
this.total = this.allData.length;
this.tableData = this.paginatedData;
} else {
ElMessage.error(res.msg || "加载失败");
this.allData = [];
this.tableData = [];
this.total = 0;
}
// 获取所有租户信息
const res_landlord = await request.get("/landlord/findAll");
if (res_landlord.code === 200) {
this.allLandlordData = res_landlord.data || [];
this.landlord_total = this.allLandlordData.length;
this.tableLandlordData = this.paginatedLandlordData;
} else {
ElMessage.error(res_landlord.msg || "加载失败");
this.allLandlordData = [];
this.tableLandlordData = [];
this.landlord_total = 0;
}
const token = JSON.parse(window.sessionStorage.getItem('userInfo'));
this.tenantId = token.tenantId;
// 获取所有交易信息
const res_transaction = await request.get(`/record/tenant/${this.tenantId}`);
if (res_transaction.code === 200) {
this.allTransactionData = res_transaction.data || [];
this.transaction_total = this.allTransactionData.length;
this.tableTransactionData = this.paginatedTransactionData;
} else {
ElMessage.error(res_transaction.msg || "加载失败");
this.allTransactionData = [];
this.tableTransactionData = [];
this.transaction_total = 0;
}
console.log(this.allTransactionData);
this.loading = false;
} catch (err){
console.error(err);
ElMessage.error("网络错误,请稍后再试");
this.allData = [];
this.tableData = [];
this.total = 0;
this.allTenentData = [];
this.tableLandlordData = [];
this.tenant_total = 0;
this.allTransactionData = [];
this.tableTransactionData = [];
this.transaction_total = 0;
this.loading = false;
}
},
loadMyInfo() {
const token = JSON.parse(window.sessionStorage.getItem('userInfo'));
if(!token) {
ElMessage.error("获取用户信息失败");
console.log("获取用户信息失败");
return;
}
this.tenantId = token.tenantId;
this.username = token.username;
this.password = token.password;
this.phone = token.phone;
this.email = token.email;
},
SignOut() {
sessionStorage.clear()
ElMessage({
message: '用户退出登录',
type: 'success',
});
this.$router.replace({path: '/Login'});
},
handleSizeChange(pageSize) {
this.pageSize = pageSize;
this.tableData = this.paginatedData;
},
handleCurrentChange(pageNum) {
this.currentPage = pageNum;
this.tableData = this.paginatedData;
},
getTitle(houseId) {
const house = this.allData.find(item => item.houseId === houseId);
if (house.title === ""){
return "未知名称";
}
return house.title;
},
getLandlordId(houseId) {
const house = this.allData.find(item => item.houseId === houseId);
const landlordId = house.landlordId;
return landlordId;
},
getLandlordUsername(houseId) {
const house = this.allData.find(item => item.houseId === houseId);
const landlordId = house.landlordId;
const landlord = this.allLandlordData.find(item => item.landlordId === landlordId);
if (!landlord){
return "未知用户";
}
return landlord.username;
},
getLandlordPhone(houseId) {
const house = this.allData.find(item => item.houseId === houseId);
const landlordId = house.landlordId;
const landlord = this.allLandlordData.find(item => item.landlordId === landlordId);
if (!landlord){
return "未知电话号码";
}
return landlord.phone;
},
getLandlordEmail(houseId) {
const house = this.allData.find(item => item.houseId === houseId);
const landlordId = house.landlordId;
const landlord = this.allLandlordData.find(item => item.landlordId === landlordId);
if (!landlord){
return "未知邮箱";
}
return landlord.email;
},
//时间显示
formatTime(isoTime) {
if (!isoTime) return "-";
const date = new Date(isoTime);
// 手动格式化避免浏览器差异
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hour = String(date.getHours()).padStart(2, '0');
const minute = String(date.getMinutes()).padStart(2, '0');
const second = String(date.getSeconds()).padStart(2, '0');
return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
},
},
};
|
2301_79970562/student_union_frontend
|
src/assets/js/TenantRecord.js
|
JavaScript
|
unknown
| 8,953
|
import axios from 'axios'
const request = axios.create({
// baseURL: 'http://43.143.83.203:8089/main',
baseURL: 'http://localhost:8089/main',
timeout: 30000
})
let token = '';
axios.interceptors.request.use(function (config) {
let user = JSON.parse(window.sessionStorage.getItem('access-user'));
if (user) {
token = user.token;
}
config.headers.common['token'] = token;
return config;
}, function (error) {
console.info("error: ");
console.info(error);
return Promise.reject(error);
});
request.interceptors.response.use(
response => {
let res = response.data;
if (response.config.responseType === 'blob') {
return res
}
if (typeof res === 'string') {
res = res ? JSON.parse(res) : res
}
return res;
},
error => {
console.log('err' + error)
return Promise.reject(error)
}
)
export default request;
|
2301_79970562/student_union_frontend
|
src/axios/request.js
|
JavaScript
|
unknown
| 958
|
import axios from 'axios'
const request = axios.create({
baseURL: 'http://localhost:8081/',
timeout: 30000
})
let token = '';
axios.interceptors.request.use(function (config) {
let user = JSON.parse(window.sessionStorage.getItem('access-user'));
if (user) {
token = user.token;
}
config.headers.common['token'] = token;
return config;
}, function (error) {
console.info("error: ");
console.info(error);
return Promise.reject(error);
});
request.interceptors.response.use(
response => {
let res = response.data;
if (response.config.responseType === 'blob') {
return res
}
if (typeof res === 'string') {
res = res ? JSON.parse(res) : res
}
return res;
},
error => {
console.log('err' + error)
return Promise.reject(error)
}
)
export default request;
|
2301_79970562/student_union_frontend
|
src/axios/request2.js
|
JavaScript
|
unknown
| 904
|
import axios from 'axios'
const request = axios.create({
baseURL: 'http://localhost:8082/',
timeout: 30000
})
let token = '';
axios.interceptors.request.use(function (config) {
let user = JSON.parse(window.sessionStorage.getItem('access-user'));
if (user) {
token = user.token;
}
config.headers.common['token'] = token;
return config;
}, function (error) {
console.info("error: ");
console.info(error);
return Promise.reject(error);
});
request.interceptors.response.use(
response => {
let res = response.data;
if (response.config.responseType === 'blob') {
return res
}
if (typeof res === 'string') {
res = res ? JSON.parse(res) : res
}
return res;
},
error => {
console.log('err' + error)
return Promise.reject(error)
}
)
export default request;
|
2301_79970562/student_union_frontend
|
src/axios/request3.js
|
JavaScript
|
unknown
| 904
|
import axios from 'axios'
const request = axios.create({
baseURL: 'http://localhost:8083/',
timeout: 30000
})
let token = '';
axios.interceptors.request.use(function (config) {
let user = JSON.parse(window.sessionStorage.getItem('access-user'));
if (user) {
token = user.token;
}
config.headers.common['token'] = token;
return config;
}, function (error) {
console.info("error: ");
console.info(error);
return Promise.reject(error);
});
request.interceptors.response.use(
response => {
let res = response.data;
if (response.config.responseType === 'blob') {
return res
}
if (typeof res === 'string') {
res = res ? JSON.parse(res) : res
}
return res;
},
error => {
console.log('err' + error)
return Promise.reject(error)
}
)
export default request;
|
2301_79970562/student_union_frontend
|
src/axios/request4.js
|
JavaScript
|
unknown
| 904
|
<template>
<el-menu
:default-active="this.$route.path"
router
style="width: 200px; height:100%; min-height: calc(100vh - 40px)"
unique-opened>
<div style="display: flex;align-items: center;justify-content: center;padding: 11px 0;">
<img alt="" src="@/assets/logo.png" style="width: 60px;">
</div>
<el-menu-item index="/adminHome">
<el-icon>
<home-filled/>
</el-icon>
<span>首页</span>
</el-menu-item>
<el-sub-menu index="user">
<template #title>
<el-icon>
<user/>
</el-icon>
<span>用户信息管理</span>
</template>
<el-menu-item index="/tenantInfo">
<el-icon>
<avatar/>
</el-icon>
租客信息
</el-menu-item>
<el-menu-item index="/landlordInfo">
<el-icon>
<avatar/>
</el-icon>
房东信息
</el-menu-item>
</el-sub-menu>
<el-sub-menu index="house">
<template #title>
<el-icon>
<house/>
</el-icon>
<span>房源信息管理</span>
</template>
<el-menu-item index="/houseAudition">
<svg class="icon" data-v-042ca774="" style="height: 18px; margin-right: 11px;"
viewBox="0 0 1024 1024"
xmlns="http://www.w3.org/2000/svg">
<path
d="M512 160c320 0 512 352 512 352S832 864 512 864 0 512 0 512s192-352 512-352zm0 64c-225.28 0-384.128 208.064-436.8 288 52.608 79.872 211.456 288 436.8 288 225.28 0 384.128-208.064 436.8-288-52.608-79.872-211.456-288-436.8-288zm0 64a224 224 0 110 448 224 224 0 010-448zm0 64a160.192 160.192 0 00-160 160c0 88.192 71.744 160 160 160s160-71.808 160-160-71.744-160-160-160z"
fill="currentColor"></path>
</svg>
<span>房源审核</span>
</el-menu-item>
<el-menu-item index="/houseDelete">
<template #title>
<el-icon>
<delete/>
</el-icon>
<span>房源删除</span>
</template>
</el-menu-item>
</el-sub-menu>
<el-menu-item index="/commentManagement">
<el-icon>
<comment/>
</el-icon>
<span>评论管理</span>
</el-menu-item>
<el-menu-item index="/adminSelfInfo">
<el-icon>
<setting/>
</el-icon>
<span>个人信息</span>
</el-menu-item>
</el-menu>
</template>
<script></script>
<style scoped>
.icon {
margin-right: 6px;
}
.el-sub-menu .el-menu-item {
height: 50px;
line-height: 50px;
padding: 0 45px;
min-width: 199px;
}
</style>
|
2301_79970562/student_union_frontend
|
src/components/AdminAside.vue
|
Vue
|
unknown
| 2,579
|
<template>
<div style="line-height: 50px;display: flex">
<div style="width: 200px;margin-left: 10px; font-weight: bold; color: dodgerblue">
房屋租赁管理系统
</div>
<span style="margin-left: -50px; font-size: 15px; font-weight: bold; color: dodgerblue">
您好!管理员 {{ name }}
</span>
<Clock style="font-size: 20px; position: absolute;left: 50%;overflow: hidden;"/>
<div style="flex: 1"></div>
<div class="right-info">
<el-button @click="SignOut" style="margin-right: 10px;">
<el-icon :size="18" style="margin-right: 5px;">
<avatar />
</el-icon>
退出登录
</el-button>
</div>
</div>
</template>
<script>
import request from "@/axios/request";
import Clock from "@/components/Clock";
const {ElMessage} = require("element-plus");
export default {
name: "AdminHeader",
components: {
Clock
},
data() {
return {
name: '',
}
},
created() {
const user = JSON.parse(sessionStorage.getItem("userInfo"));
if (user && user.username) {
this.name = user.username;
}
},
methods: {
SignOut() {
sessionStorage.clear()
ElMessage({
message: '用户退出登录',
type: 'success',
});
this.$router.replace({path: '/Login'});
},
},
}
</script>
<style scoped>
.right-info {
width: 120px;
display: flex;
align-items: center;
justify-content: center;
margin-right: 1.5%;
}
.right-info:hover {
cursor: pointer;
}
</style>
|
2301_79970562/student_union_frontend
|
src/components/AdminHeader.vue
|
Vue
|
unknown
| 1,539
|
<template>
<el-container>
<span>{{ dateFormat(date) }}</span>
</el-container>
</template>
<script>
//创建一个函数来增加月日时小于10在前面加0
const padaDate = function (value) {
return value < 10 ? '0' + value : value;
};
export default {
name: 'clock',
data() {
return {
// 当前时间
date: new Date()
}
},
// 挂载时间
mounted() {
//获取当前日期
let that = this;
this.timer = setInterval(function () {
that.date = new Date().toLocaleString();
});
},
methods: {
//当前日期格式化
dateFormat() {
const date = new Date();
const year = date.getFullYear();
const month = date.getMonth() + 1 < 10 ?
'0' + (date.getMonth() + 1) : date.getMonth() + 1;
const day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
const hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
const minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
const seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds
}
}
}
</script>
|
2301_79970562/student_union_frontend
|
src/components/Clock.vue
|
Vue
|
unknown
| 1,239
|
<template>
<div class="charts-container">
<div v-for="(chart, index) in charts" :key="index" :style="{ width: chart.width || '600px', height: chart.height || '400px' }" class="chart-item">
<div :id="'echarts-dom-' + index" class="echart-dom"></div>
</div>
</div>
</template>
<script>
import * as echarts from "echarts";
import china from 'echarts/map/json/china.json';
echarts.registerMap('china', china);
require("echarts/theme/macarons");
export default {
name: "DataCharts",
props: {
charts: {
type: Array,
required: true
}
},
data() {
return {
instances: []
};
},
mounted() {
this.$nextTick(() => {
this.renderCharts();
});
},
methods: {
renderCharts() {
this.instances.forEach(instance => instance.dispose());
this.instances = [];
this.charts.forEach((chart, index) => {
const dom = document.getElementById(`echarts-dom-${index}`);
if (!dom) return;
const chartInstance = echarts.init(dom, null);
chartInstance.setOption(chart.option);
this.instances.push(chartInstance);
window.addEventListener("resize", () => {
chartInstance.resize();
});
});
}
},
beforeUnmount() {
this.instances.forEach(instance => instance.dispose());
}
};
</script>
<style scoped>
.charts-container {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 20px;
}
.chart-item {
flex: 1;
min-width: 500px;
max-width: 800px;
}
.echart-dom {
width: 100%;
height: 100%;
}
</style>
|
2301_79970562/student_union_frontend
|
src/components/DataCharts.vue
|
Vue
|
unknown
| 1,578
|
import {createApp} from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import './assets/css/global.css'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import * as ELIcons from '@element-plus/icons-vue'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
const app = createApp(App)
.use(ElementPlus, {
locale: zhCn
})
for (let iconName in ELIcons) {
app.component(iconName, ELIcons[iconName])
}
app.use(router)
app.use(store)
app.mount('#app')
|
2301_79970562/student_union_frontend
|
src/main.js
|
JavaScript
|
unknown
| 540
|
import Layout from '../layout/Layout.vue'
import {createRouter, createWebHistory} from "vue-router";
export const constantRoutes = [
{path: '/', redirect: '/Enter' },
{path: '/Enter', name: 'Enter', component: () => import("@/views/Enter")},
{path: '/Login', name: 'Login', component: () => import("@/views/Login")},
{path: '/Register', name: 'Register', component: () => import("@/views/Register")},
{
path: '/Layout', name: 'Layout', component: Layout, children: [
// 管理员平台
{path: '/adminHome', name: 'AdminHome', component: () => import("@/views/AdminHome")},
{path: '/adminSelfInfo', name: 'AdminSelfInfo', component: () => import("@/views/AdminSelfInfo")},
{path: '/tenantInfo', name: 'TenantInfo', component: () => import("@/views/TenantInfo")},
{path: '/landlordInfo', name: 'LandlordInfo', component: () => import("@/views/LandlordInfo")},
{path: '/houseAudition', name: 'HouseAudition', component: () => import("@/views/HouseAudition")},
{path: '/houseDelete', name: 'HouseDelete', component: () => import("@/views/HouseDelete")},
{path: '/commentManagement', name: 'CommentManagement', component: () => import("@/views/CommentManagement")},
{path: '/adminAuditionHouseDisplay', name: 'AdminAuditionHouseDisplay', component: () => import("@/views/AdminAuditionHouseDisplay")},
]
},
// 租客首页
{path: '/tenantHome', name: 'TenantHome', component: () => import("@/views/TenantHome")},
{path: '/tenantSelfInfo', name: 'TenantSelfInfo', component: () => import("@/views/TenantSelfInfo")},
{path: '/TenantFavorite',name: 'TenantFavorite', component: () => import("@/views/TenantFavorite")},
{path: '/SelectHouse', name: 'SelectHouse', component: () => import("@/views/SelectHouse")},
{path: '/houseDisplay', name: 'HouseDisplay', component: () => import("@/views/HouseDisplay")},
{path: '/tenantApplication', name: 'TenantApplication', component: () => import("@/views/TenantApplication")},
{path: '/favoriteHouseDisplay', name: 'FavoriteHouseDisplay', component: () => import("@/views/FavoriteHouseDisplay")},
{path: '/tenantApplicationHouseDisplay', name: 'TenantApplicationHouseDisplay', component: () => import("@/views/TenantApplicationHouseDisplay")},
{path: '/tenantRecord', name: 'TenantRecord', component: () => import("@/views/TenantRecord")},
{path: '/homeDisplay', name: 'HomeDisplay', component: () => import("@/views/HomeDisplay")},
{path: '/vectorDatabase', name: 'VectorDatabase', component: () => import("@/views/VectorDatabase")},
{path: '/personalAssistant', name: 'PersonalAssistant', component: () => import("@/views/PersonalAssistant")},
{path: '/graphRAGAssistant', name: 'GraphRAGAssistant', component: () => import("@/views/GraphRAGAssistant")},
// 房东首页
{path: '/landlordHome', name: 'LandlordHome', component: () => import("@/views/LandlordHome")},
{path: '/landlordHouse', name: 'LandlordHouse', component: () => import("@/views/LandlordHouse")},
{path: '/landlordSelfInfo', name: 'LandlordSelfInfo', component: () => import("@/views/LandlordSelfInfo")},
{path: '/landlordTransactionRecord', name: 'LandlordTransactionRecord', component: () => import("@/views/LandlordTransactionRecord")},
{path: '/applicationAudition', name: 'ApplicationAudition', component: () => import("@/views/ApplicationAudition")},
{path: '/allHouses', name: 'AllHouses', component: () => import("@/views/AllHouses")},
{path: '/landlordHouseDisplay', name: 'LandlordHouseDisplay', component: () => import("@/views/LandlordHouseDisplay")},
{path: '/myHouseDisplay', name: 'MyHouseDisplay', component: () => import("@/views/MyHouseDisplay")},
{path: '/landlordHomeDisplay', name: 'LandlordHomeDisplay', component: () => import("@/views/LandlordHomeDisplay")},
]
const router = createRouter({
routes: constantRoutes,
history: createWebHistory(process.env.BASE_URL)
})
// router.beforeEach((to, from, next) => {
// const token = window.sessionStorage.getItem('userInfo');
// if (!token) {
// return next('/Login')
// }
// if (to.path === '/Login') {
// return next();
// }
// if (to.path === '/Enter') {
// return next();
// }
// if (to.path === '/Register') {
// return next();
// }
// if (to.path === '/adminHome') {
// return next();
// }
// if (to.path === '/tenantHome') {
// return next();
// }
// if (to.path === '/landlordHome') {
// return next();
// }
// if (to.path === '/tenantInfo') {
// return next();
// }
// if (to.path === '/landlordInfo') {
// return next();
// }
// if (to.path === '/houseAudition') {
// return next();
// }
// if (to.path === '/houseDisplay') {
// return next();
// }
// if (to.path === '/houseDelete') {
// return next();
// }
// if (to.path === '/' && token) {
// if(window.sessionStorage.getItem('identity') === 'admin'){
// return next('/adminHome')
// }else if(window.sessionStorage.getItem('identity') === 'tenant'){
// return next('/tenantHome')
// }else if(window.sessionStorage.getItem('identity') === 'landlord'){
// return next('/landlordHome')
// }
// }
// next()
// })
export default router
|
2301_79970562/student_union_frontend
|
src/router/index.js
|
JavaScript
|
unknown
| 5,542
|
import {createStore} from 'vuex'
export default createStore({
state: {
isLogin: false,
identity: ''
},
mutations: {
login(state) {
state.isLogin = true
}
},
actions: {},
modules: {}
})
|
2301_79970562/student_union_frontend
|
src/store/index.js
|
JavaScript
|
unknown
| 254
|
<template>
<div>
<!-- <el-breadcrumb separator-icon="ArrowRight" style="margin: 16px">
<el-breadcrumb-item :to="{ path: '/AdminHome' }">首页</el-breadcrumb-item>
<el-breadcrumb-item :to="{ path: '/houseAudition' }">房源信息管理</el-breadcrumb-item>
<el-breadcrumb-item>房源信息展示</el-breadcrumb-item>
<router-link to="/houseAudition" style="position: relative; right: -72%;">
<el-button type="primary" style="width: 55px; height: 33px; font-size: 14px; font-family: 'Segoe UI'; border-radius: 10px;">返回</el-button>
</router-link>
</el-breadcrumb> -->
<el-card style="margin: 15px; min-height: calc(100vh - 111px)">
<div class="common-layout">
<el-container>
<el-header>
<h1 style="font-size: 26px; font-weight: bold; text-align: center; ">{{ Data.title }}</h1>
<el-tag
:type="getStatusTagType(Data.status)"
size="large" style="position: relative; left: 94%; top: -57%; font-weight: bold; font-size: 14px;">
{{ getStatusLabel(Data.status) }}
</el-tag>
</el-header>
<el-container>
<el-aside width="500px">
<el-image :src="Data.imageUrl" fit="fill" style="width: 100%; height: 100%; border-radius: 10px;"></el-image>
</el-aside>
<el-main>
<el-col :gutter="20" style="margin-top: -20px;">
<el-row :span="8"><p><strong>住房名称:</strong>{{ Data.title }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>住房编号:</strong>{{ Data.houseId }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>房东编号:</strong>{{ Data.landlordId }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>所在地区:</strong>{{ Data.area }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>地址:</strong>{{ Data.address }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>住房描述:</strong>{{ Data.description }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>住房面积:</strong>{{ Data.size }} 平方米</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>户型:</strong>{{ Data.roomCount }} 居室</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>楼层:</strong>{{ Data.floor }} 层</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>租金:</strong>{{ Data.price }} 元/月</p></el-row>
</el-col>
</el-main>
</el-container>
<!-- 评论区 -->
<el-main style="margin-top: 20px;">
<div style="display: flex; align-items: center; margin-bottom: 15px;">
<h2 style="font-size: 20px; font-weight: bold;">用户评论 ({{ commentCount }})</h2>
<div class="line" style="margin-left: 1.5%; flex: 1; height: 1px; background-color: #eee;"></div>
</div>
<!-- 评论列表(评论数>0时显示) -->
<div v-if="comments.length > 0">
<div
v-for="comment in comments"
:key="comment.id"
style="margin-bottom: 15px; padding: 15px; border: 1px solid #ebeef5; border-radius: 4px;"
>
<!-- 评论头部:用户信息+评分+时间 -->
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
<div>
<span style="font-weight: 600; color: #303133;">{{ userMap[comment.tenantId] || '匿名用户' }}</span>
<el-rate
v-model="comment.rating"
disabled
:colors="['#99A9BF', '#F7BA1E', '#FF9900']"
style="margin-left: 10px;"
/>
</div>
<span style="font-size: 12px; color: #909399;">{{ formatDate(comment.commentTime) }}</span>
</div>
<!-- 评论内容 -->
<div style="color: #606266; line-height: 1.6;">{{ comment.content }}</div>
</div>
</div>
<!-- 暂无评论(评论数=0时显示) -->
<div v-else style="text-align: center; padding: 50px 0; color: #909399;">
暂无评论
</div>
</el-main>
</el-container>
</div>
</el-card>
</div>
</template>
<script src="@/assets/js/AdminAuditionHouseDisplay.js"></script>
|
2301_79970562/student_union_frontend
|
src/views/AdminAuditionHouseDisplay.vue
|
Vue
|
unknown
| 4,764
|
<template>
<el-card style="margin: 15px; min-height: calc(100vh - 80px)">
<h2 style="color: black; font-size: 20px; font-family: '微软雅黑'; position: relative; top: 0px; right: 0px;">快速统计:</h2>
<div>
<el-row :gutter="20" class="topInfo">
<el-col :span="6" @click="fetchTableData('tenant')">
<div id="tenant" class="el-colDiv">
<div id="ssv1-main-text" class="nowDiv">实时</div>
<span class="title">租客统计</span><br/>
<span class="digital">{{ this.Tenant }}</span><br/>
<span class="last-span">查询在库租客信息</span>
</div>
</el-col>
<el-col :span="6" @click="fetchTableData('landlord')">
<div id="landlord" class="el-colDiv">
<div id="ssv2-main-text" class="nowDiv">实时</div>
<span class="title">房东统计</span><br/>
<span class="digital">{{ this.Landlord }}</span><br/>
<span class="last-span">查询在库房东信息</span>
</div>
</el-col>
<el-col :span="6" @click="fetchTableData('house')">
<div id="house" class="el-colDiv">
<div id="ssv3-main-text" class="nowDiv">实时</div>
<span class="title">房源统计</span><br/>
<span class="digital">{{ this.House }}</span><br/>
<span class="last-span">监控房源信息</span>
</div>
</el-col>
<el-col :span="6" @click="createDataCharts()">
<div id="charts" class="el-colDiv">
<div id="ssv4-main-text" class="nowDiv">实时</div>
<span class="title">统计图表</span><br/>
<span class="digital">{{ this.House }}</span><br/>
<span class="last-span">可视化显示统计数据</span>
</div>
</el-col>
</el-row>
<div v-if="currentTab !== 'charts'" style="margin-top: 0px;">
<h3 v-if="currentTab === 'tenant'">租客列表</h3>
<h3 v-if="currentTab === 'landlord'">房东列表</h3>
<h3 v-if="currentTab === 'house'">房源列表</h3>
<el-table :data="tableData" border stripe v-loading="loading" style="width: 100%; margin-top: 15px;">
<el-table-column prop="username" label="用户名" v-if="currentTab !== 'house'"></el-table-column>
<el-table-column prop="phone" label="电话号码" v-if="currentTab !== 'house'"></el-table-column>
<el-table-column prop="email" label="邮箱" v-if="currentTab !== 'house'"></el-table-column>
<el-table-column prop="title" label="房屋名称" v-if="currentTab === 'house'"></el-table-column>
<el-table-column prop="description" label="房屋描述" v-if="currentTab === 'house'"></el-table-column>
<el-table-column prop="price" label="价格" v-if="currentTab === 'house'"></el-table-column>
<el-table-column prop="address" label="地址" v-if="currentTab === 'house'"></el-table-column>
<el-table-column prop="area" label="所在区域" v-if="currentTab === 'house'"></el-table-column>
<el-table-column prop="size" label="面积" v-if="currentTab === 'house'"></el-table-column>
<el-table-column prop="roomCount" label="房间号" v-if="currentTab === 'house'"></el-table-column>
<el-table-column prop="floor" label="楼层" v-if="currentTab === 'house'"></el-table-column>
<el-table-column prop="status" label="出租状态" v-if="currentTab === 'house'"></el-table-column>
</el-table>
<el-pagination
layout="total, sizes, prev, pager, next, jumper"
:total="allData.length"
:page-size="pageSize"
:page-sizes="[5,10,15]"
v-model="currentPage"
@size-change="handleSizeChange"
@current-change="handlePageChange"
style="margin-top: 20px; text-align: center;"/>
</div>
<el-row :gutter="20" style="margin-top: 0px;">
<h3 v-if="currentTab === 'charts'" style="position: relative; left: 10px;">图表统计</h3>
<el-col :span="24">
<data-charts :charts="chartsOptions" v-if="showCharts" v-loading="loading"/>
</el-col>
</el-row>
</div>
</el-card>
</template>
<script src="@/assets/js/AdminHome.js"></script>
<style scoped>@import '../assets/css/AdminHome.css';</style>
|
2301_79970562/student_union_frontend
|
src/views/AdminHome.vue
|
Vue
|
unknown
| 5,091
|
<template>
<div>
<!-- 面包屑导航 -->
<el-breadcrumb separator-icon="ArrowRight" style="margin: 10px">
<el-breadcrumb-item :to="{ path: '/AdminHome' }">首页</el-breadcrumb-item>
<el-breadcrumb-item>个人信息</el-breadcrumb-item>
</el-breadcrumb>
<!-- 卡片容器 -->
<el-card id="personal-info-card" style="margin: 15px; min-height: calc(100vh - 111px);">
<div style="display: flex; justify-content: center;">
<div style="width: 600px; margin-left: 30px; position: relative">
<!-- 用户信息展示 -->
<div style="margin: 20px 0;">
<h3 class="personal-info-title" style="margin-bottom: 30px; color: #333;font-size: 30px;">👤 个人信息</h3>
<div style="display: flex; flex-wrap: wrap; gap: 20px;">
<!-- 管理员ID -->
<el-card shadow="hover" style="width: calc(50% - 10px); padding: 15px; background-color: #f9f9f9; border: 1px solid #ebebeb; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1), 0 6px 20px rgba(0, 0, 0, 0.1); transition: all 0.3s ease; user-select: none;">
<div style="display: flex; align-items: center;">
<i class="el-icon-user" style="margin-right: 10px; color: #409EFF;"></i>
<div style="position: relative; flex: 1;">
<strong>管理员ID</strong>
<span style="margin-left: 10px; display: block;">{{ adminId }}</span>
<el-icon style="position: absolute; right: 0; top: 0;">
<User />
</el-icon>
</div>
</div>
</el-card>
<!-- 用户名 -->
<el-card shadow="hover" style="width: calc(50% - 10px); padding: 15px; background-color: #f9f9f9; border: 1px solid #ebebeb; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1), 0 6px 20px rgba(0, 0, 0, 0.1); transition: all 0.3s ease; user-select: none;">
<div style="display: flex; align-items: center;">
<i class="el-icon-document" style="margin-right: 10px; color: #409EFF;"></i>
<div style="position: relative; flex: 1;">
<strong>用户名</strong>
<span style="margin-left: 10px; display: block;">{{ username }}</span>
<el-icon style="position: absolute; right: 0; top: 0;">
<UserFilled />
</el-icon>
</div>
</div>
</el-card>
<!-- 手机号 -->
<el-card shadow="hover" style="width: calc(50% - 10px); padding: 15px; background-color: #f9f9f9; border: 1px solid #ebebeb; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1), 0 6px 20px rgba(0, 0, 0, 0.1); transition: all 0.3s ease; user-select: none;">
<div style="display: flex; align-items: center;">
<i class="el-icon-phone" style="margin-right: 10px; color: #409EFF;"></i>
<div style="position: relative; flex: 1;">
<strong>手机号</strong>
<span style="margin-left: 10px; display: block;">{{ phone }}</span>
<el-icon style="position: absolute; right: 0; top: 0;">
<Iphone />
</el-icon>
</div>
</div>
</el-card>
<!-- 邮箱 -->
<el-card shadow="hover" style="width: calc(50% - 10px); padding: 15px; background-color: #f9f9f9; border: 1px solid #ebebeb; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1), 0 6px 20px rgba(0, 0, 0, 0.1); transition: all 0.3s ease; user-select: none;">
<div style="display: flex; align-items: center;">
<i class="el-icon-message" style="margin-right: 10px; color: #409EFF;"></i>
<div style="position: relative; flex: 1;">
<strong>邮箱</strong>
<span style="margin-left: 10px; display: block;">{{ email }}</span>
<el-icon style="position: absolute; right: 0; top: 0;">
<Message />
</el-icon>
</div>
</div>
</el-card>
</div>
</div>
<!-- 修改按钮 -->
<el-tooltip content="修改信息" placement="bottom">
<el-button
icon="Edit"
size="large"
type="primary"
style="
margin-top: 30px;
width: 80px;
transition: transform 0.2s ease;
"
@click="Edit"
@mouseenter.native="e => e.target.style.transform = 'scale(1.1)'"
@mouseleave.native="e => e.target.style.transform = 'scale(1)'"
>
</el-button>
</el-tooltip>
</div>
</div>
</el-card>
<!-- 修改信息弹窗 -->
<el-dialog v-model="dialogVisible" title="操作" width="30%" @close="resetForm">
<el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
<el-form-item label="管理员ID" prop="adminId">
<el-input v-model="form.adminId" disabled style="width: 80%"></el-input>
</el-form-item>
<el-form-item label="用户名" prop="username">
<el-input v-model="form.username" style="width: 80%"></el-input>
</el-form-item>
<el-form-item label="密码" prop="password">
<el-input v-model="form.password" :disabled="disabled" show-password style="width: 80%"></el-input>
<el-tooltip content="修改密码" placement="right">
<el-icon size="large" style="margin-left: 5px; cursor: pointer" @click="EditPass">
<edit />
</el-icon>
</el-tooltip>
</el-form-item>
<el-form-item label="确认密码" prop="checkPass" :style="display">
<el-input v-model="form.checkPass" show-password style="width: 80%"></el-input>
</el-form-item>
<el-form-item label="手机号" prop="phone">
<el-input v-model.number="form.phone" style="width: 80%"></el-input>
</el-form-item>
<el-form-item label="邮箱地址" prop="email">
<el-input v-model="form.email" style="width: 80%"></el-input>
</el-form-item>
</el-form>
<template #footer>
<span class="dialog-footer">
<el-button @click="cancel">取 消</el-button>
<el-button type="primary" @click="save">确 定</el-button>
</span>
</template>
</el-dialog>
</div>
</template>
<script src="@/assets/js/AdminSelfInfo.js">
</script>
<style scoped>
.el-card:hover {
transform: translateY(-5px);
box-shadow: 0 10px 15px rgba(0, 0, 0, 0.2), 0 6px 20px rgba(0, 0, 0, 0.2);
border-color: rgba(0, 0, 0, 0.2);
}
.personal-info-title {
font-size: 30px;
}
.dialog-footer button {
margin-left: 10px;
}
</style>
|
2301_79970562/student_union_frontend
|
src/views/AdminSelfInfo.vue
|
Vue
|
unknown
| 6,998
|
<template>
<div class="common-layout">
<el-container>
<!-- 头部 -->
<el-header style="background-color: #1b4989; color: white; display: flex; align-items: center; justify-content: space-between; padding: 0 20px;">
<!-- 面包屑导航 -->
<el-breadcrumb separator-icon="ArrowRight" style="margin: 10px">
<el-breadcrumb-item :to="{ path: '/LandlordHome' }" style="color: white;">首页</el-breadcrumb-item>
<el-breadcrumb-item style="color: white;">查看房源</el-breadcrumb-item>
</el-breadcrumb>
<!-- 搜索功能 -->
<div style="display: flex; align-items: right; gap: 10px;">
<el-input v-model="search" placeholder="请输入搜索内容" style="width: 300px;"/>
<el-button @click="SearchHouse" type="primary" plain icon="Search">搜索</el-button>
<el-button @click="ResetSearch" type="info" plain icon="Refresh">重置</el-button>
</div>
<el-button @click="SignOut" type="info" size="medium" plain icon="Avatar">退出登录</el-button>
</el-header>
<!-- 主要内容 -->
<el-main>
<div style="display: flex; font-weight: bold; font-family: Microsoft YaHei; font-size: 20px; margin-top: 0%;">
房源列表
<div class="line" style="margin-left: 1.5%; margin-top: 1%;"></div>
</div>
<div style="display: flex; flex-wrap: wrap; gap: 20px;">
<div v-if="displayData.length === 0" style="position: relative; left: 47.5%; margin-top: 8%;">
暂无数据
</div>
<!-- 将v-for移到el-card上,确保每个数据项都有独立的卡片 -->
<el-card
v-else
v-for="item in displayData"
:key="item.houseId"
shadow="hover"
style="margin-top: 2%; margin-left: 5%; width: calc(90% - 10px); padding: 15px; background-color: #f9f9f9; border: 1px solid #ebebeb; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1), 0 6px 20px rgba(0, 0, 0, 0.1); transition: all 0.3s ease;"
>
<div class="common-layout">
<el-container>
<el-aside width="200px">
<el-image :src="item.imageUrl" fit="fill" style="width: 100%; height: 100%"></el-image>
</el-aside>
<el-container>
<el-header style="position: relative; padding-right: 80px;">
<router-link
:to="{ name: 'LandlordHouseDisplay', query: { houseId: item.houseId } }"
style="font-family: Microsoft YaHei; display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;"
>
{{ item.title }}:{{ item.address }}
</router-link>
<el-tag
:type="getStatusTagType(item.status)"
effect="dark"
size="medium"
style="width: auto; height: 30px; position: absolute; right: 0; top: 20%; transform: translateY(-40%); font-weight: bolder ; font-size: 14.5px; white-space: nowrap;"
>
{{ getStatusLabel(item.status) }}
</el-tag>
</el-header>
<el-main style="margin-top: -5%;">
{{ item.description }}
</el-main>
</el-container>
</el-container>
</div>
</el-card>
</div>
</el-main>
</el-container>
</div>
</template>
<script src="@/assets/js/AllHouses.js"></script>
<!--注意######样式的优先级受Element plus影响,部分 Element 组件内部使用了自己定义的颜色值,而不是继承父级,需要显示设置####-->
<style scoped>
@import '../assets/css/AdminHome.css';
:deep(.el-breadcrumb__item .el-breadcrumb__inner)
{
color
: white !important;
}
.el-card:hover {
transform: translateY(-5px);
box-shadow: 0 10px 15px rgba(0, 0, 0, 0.2), 0 6px 20px rgba(0, 0, 0, 0.2);
border-color: rgba(0, 0, 0, 0.2);
}
</style>
|
2301_79970562/student_union_frontend
|
src/views/AllHouses.vue
|
Vue
|
unknown
| 4,193
|
<template>
<div class="background">
<div class="common-layout">
<el-container>
<el-header class="header_background">
<div style="position: absolute; top: 0.1%; left: 2%;">
<img alt="" src="@/assets/logo1.png" style="width: 40px;">
</div>
<div style="position: absolute; top: 1.5%; left: 38%;">
<span style="font-size: 15px; font-weight: bold; color: whitesmoke">
您好,房东 {{ username }} !欢迎进入房屋租赁平台!
</span>
</div>
<div class="right-info">
<el-button @click="SignOut" style="margin-right: 10px;">
<el-icon :size="18" style="margin-right: 5px;">
<avatar />
</el-icon>
退出登录
</el-button>
</div>
</el-header>
<el-header class="sub_header_background">
<el-menu
:default-active="activeIndex"
router
class="el-menu-demo"
mode="horizontal"
background-color="#545c64"
text-color="whitesmoke"
active-text-color="white"
style="height: 102%;"
unique-opened
>
<el-menu-item index="/LandlordHome">首页</el-menu-item>
<el-menu-item index="/LandlordHouse">我的房源</el-menu-item>
<el-sub-menu index="transaction">
<template #title>交易管理</template>
<el-menu-item index="/ApplicationAudition">租客申请审核</el-menu-item>
<el-menu-item index="/LandlordTransactionRecord">交易记录</el-menu-item>
</el-sub-menu>
<el-menu-item index="/LandlordSelfInfo">个人信息</el-menu-item>
</el-menu>
</el-header>
<el-main>
<div style="display: flex; font-weight: bold; font-family: Microsoft YaHei; font-size: 20px; margin-top: 0%;">
待审批租购申请
<div class="line" style="margin-left: 1.5%; margin-top: 1%;"></div>
</div>
<div style="margin: 20px 0">
<el-input v-model="search"
@input="filterData"
clearable
placeholder="请输入房源ID号"
prefix-icon="Search"
style="width: 20%"/>
<el-button icon="Search" style="margin-left: 5px" type="primary" @click="filterData"></el-button>
<el-button icon="refresh-left" style="margin-left: 10px" type="default" @click="reset"></el-button>
</div>
<div style="display: flex; flex-wrap: wrap; gap: 20px;">
<el-card shadow="hover" style="margin-top: 2%; width: calc(100% - 10px); padding: 15px; background-color: #f9f9f9; border: 1px solid #ebebeb; box-shadow: 0 10px 15px rgba(0, 0, 0, 0.2), 0 6px 20px rgba(0, 0, 0, 0.2); transition: all 0.3s ease; ">
<el-table v-loading="loading" :data="tableData" border max-height="705" style="width: 100%">
<el-table-column label="申请编号" prop="applicationId"/>
<el-table-column label="房屋编号" prop="houseId"/>
<el-table-column label="房屋名称" prop="houseId" :formatter="(row) => getHouseTitle(row.houseId)"/>
<el-table-column label="租客编号" prop="tenantId"/>
<el-table-column label="租客用户名" prop="tenantId" :formatter="(row) => getTenantUsername(row.tenantId)"/>
<el-table-column label="租客电话号码" prop="tenantId" :formatter="(row) => getTenantPhone(row.tenantId)"/>
<el-table-column label="租客邮箱" prop="tenantId" :formatter="(row) => getTenantEmail(row.tenantId)"/>
<el-table-column label="申请时间" prop="applicationTime" :formatter="(row) => formatTime(row.applicationTime)"/>
<el-table-column label="申请类型" prop="type">
<template #default="scope">
<el-tag :type="scope.row.type === 'in' ? 'primary' : 'danger'" size="small">
{{ scope.row.type === 'in' ? '入租' : '退租' }}
</el-tag>
</template>
</el-table-column>
<el-table-column label="操作">
<template #default="scope">
<el-space direction="vertical" alignment="center" style="margin-left: 23%; margin-top: 10%">
<el-button icon="CircleCheck" type="primary" @click="handleConfirm(scope.row)">通过申请</el-button>
<el-popconfirm title="确认拒绝该租户的租房请求?" @confirm="handleReject(scope.row)">
<template #reference>
<el-button icon="Delete" type="danger">拒绝申请</el-button>
</template>
</el-popconfirm>
</el-space>
</template>
</el-table-column>
</el-table>
</el-card>
<div style="margin: 30px 0;">
<el-pagination
v-model:currentPage="currentPage"
:page-size="pageSize"
:page-sizes="[5, 10, 15]"
:total="total"
layout="total, sizes, prev, pager, next, jumper"
@size-change="handleSizeChange"
@current-change="handleCurrentChange"></el-pagination>
</div>
</div>
</el-main>
</el-container>
</div>
</div>
</template>
<script src="@/assets/js/ApplicationAudition.js"></script>
<style scoped>
.background {
background-color: whitesmoke;
height: 100vh;
}
.header_background {
background-color: #1b4989;
height: 6vh;
}
.sub_header_background {
background-color: #545c64;
height: 7vh;
}
.right-info {
width: 100px;
position: absolute;
right: 2%;
top: 0.7%
}
.right-info:hover {
cursor: pointer;
}
.el-carousel__item h3 {
color: #475669;
opacity: 0.75;
line-height: 200px;
margin: 0;
text-align: center;
}
.el-carousel__item:nth-child(2n) {
background-color: #99a9bf;
}
.el-carousel__item:nth-child(2n + 1) {
background-color: #d3dce6;
}
.line{
background: url(https://www.upc.edu.cn/ximages/tit1.png) center repeat-x;
height: 0.4rem;
flex: 1;
background-size: auto;
margin: 0.16rem;
}
</style>
|
2301_79970562/student_union_frontend
|
src/views/ApplicationAudition.vue
|
Vue
|
unknown
| 7,464
|
<template>
<div>
<el-breadcrumb separator-icon="ArrowRight" style="margin: 16px">
<el-breadcrumb-item :to="{ path: '/adminHome' }">首页</el-breadcrumb-item>
<el-breadcrumb-item>评论管理</el-breadcrumb-item>
</el-breadcrumb>
<el-card style="margin: 15px; min-height: calc(100vh - 111px)">
<div style="color: black; font-size: 20px;font-weight: bolder; text-align: center;">评论列表</div>
<div>
<div style="margin: 40px 0;">
<div style="margin: 10px 0">
<el-input v-model="search"
@input="filterData"
clearable
placeholder="请输入租客ID号"
prefix-icon="Search"
style="width: 20%"/>
<el-button icon="Search" style="margin-left: 5px" type="primary" @click="filterData"></el-button>
<el-button icon="refresh-left" style="margin-left: 10px" type="default" @click="reset"></el-button>
<!-- 全选按钮及批量删除按钮 -->
<el-checkbox v-model="isAllSelected" @change="toggleSelectAll" style="margin-left: 20px; border: 1.5px solid #ccc; padding: 5px; border-radius: 4px;">全选</el-checkbox>
<el-button icon="Delete" style="margin-left: 20px" type="danger" @click="batchDeleteConfirm">批量删除</el-button>
</div>
</div>
<!--表格-->
<el-table v-loading="loading" :data="tableData" border max-height="705" style="width: 100%">
<el-table-column label="租客ID" prop="tenantId" min-width="10px"/>
<el-table-column label="房源ID" prop="houseId" min-width="10px"/>
<el-table-column label="租客评论" prop="content"/>
<el-table-column label="操作" width="130px">
<template #default="scope">
<el-popconfirm title="确认删除?" @confirm="handleDelete(scope.row.commentId)">
<template #reference>
<el-button icon="Delete" type="danger">删除</el-button>
</template>
</el-popconfirm>
</template>
</el-table-column>
</el-table>
<!--分页-->
<div style="margin: 40px 0">
<el-pagination
v-model:currentPage="currentPage"
:page-size="pageSize"
:page-sizes="[5, 10, 15]"
:total="total"
layout="total, sizes, prev, pager, next, jumper"
@size-change="handleSizeChange"
@current-change="handleCurrentChange"></el-pagination>
</div>
</div>
</el-card>
</div>
</template>
<script src="@/assets/js/CommentManagement.js"></script>
|
2301_79970562/student_union_frontend
|
src/views/CommentManagement.vue
|
Vue
|
unknown
| 2,723
|
<template>
<div class="enter-container">
<div style="margin-right: 150px; min-width: 300px">
<img alt="" src="../../public/入口图片.png" style="width: 650px; position: absolute; top: 20%; right: 46%;"/>
</div>
<div style="color: black; font-size: 74px; font-family: '幼圆';font-weight: bold; position: absolute; top: 27%; right: 1%;">房屋租赁管理系统</div>
<router-link to="/Login" style="position: absolute; bottom: 15%; right: 10%;">
<el-button type="primary" style="width: 110px; height: 50px; font-size: 17px; font-family: 'Segoe UI'; border-radius: 10px;">进入网站</el-button>
</router-link>
</div>
<div class="footer">
©Copyright 2025 UPC, Edu.
</div>
</template>
<script>
export default {
name: 'Enter'
};
</script>
<style scoped>
.enter-container {
position: fixed;
height: 100%;
width: 100%;
top: 0;
left: 0;
background: linear-gradient(
135deg,
hsl(170, 80%, 70%),
hsl(190, 80%, 70%),
hsl(250, 80%, 70%),
hsl(320, 80%, 70%),
hsl(320, 80%, 70%),
hsl(250, 80%, 70%),
hsl(190, 80%, 70%),
hsl(190, 80%, 70%),
hsl(170, 80%, 70%)
);
background-size: 600%;
animation: animation 15s linear infinite;
}
@keyframes animation {
0% {
background-position: 0 0;
}
100% {
background-position: 100% 100%;
}
}
.footer {
left: 0;
bottom: 0;
color: #fff;
width: 100%;
position: absolute;
text-align: center;
line-height: 30px;
padding-bottom: 10px;
text-shadow: #000 0.1em 0.1em 0.1em;
font-size: 14px;
}
.footer a,
.footer span {
color: #fff;
}
</style>
|
2301_79970562/student_union_frontend
|
src/views/Enter.vue
|
Vue
|
unknown
| 1,751
|
<template>
<div>
<el-breadcrumb separator-icon="ArrowRight" style="margin: 16px">
<el-breadcrumb-item :to="{ path: '/tenantHome' }">首页</el-breadcrumb-item>
<el-breadcrumb-item :to="{ path: '/TenantFavorite' }">我的收藏</el-breadcrumb-item>
<el-breadcrumb-item>房源信息展示</el-breadcrumb-item>
<router-link to="/TenantFavorite" style="position: relative; right: -72%;">
<el-button type="primary" style="width: 55px; height: 33px; font-size: 14px; font-family: 'Segoe UI'; border-radius: 10px;">返回</el-button>
</router-link>
</el-breadcrumb>
<el-card style="margin: 15px; min-height: calc(100vh - 111px)">
<div class="common-layout">
<el-container>
<el-header>
<h1 style="font-size: 26px; font-weight: bold; text-align: center; ">{{ Data.title }}</h1>
<el-tag
:type="getStatusTagType(Data.status)"
size="large" style="position: relative; left: 94%; top: -57%; font-weight: bold; font-size: 14px;">
{{ getStatusLabel(Data.status) }}
</el-tag>
</el-header>
<el-container>
<el-aside width="500px">
<el-image :src="Data.imageUrl" fit="fill" style="width: 100%; height: 100%; border-radius: 10px;"></el-image>
</el-aside>
<el-main>
<el-col :gutter="20" style="margin-top: -20px;">
<el-row :span="8"><p><strong>住房名称:</strong>{{ Data.title }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>住房编号:</strong>{{ Data.houseId }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>房东编号:</strong>{{ Data.landlordId }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>所在地区:</strong>{{ Data.area }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>地址:</strong>{{ Data.address }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>住房描述:</strong>{{ Data.description }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>住房面积:</strong>{{ Data.size }} 平方米</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>户型:</strong>{{ Data.roomCount }} 居室</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>楼层:</strong>{{ Data.floor }} 层</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>租金:</strong>{{ Data.price }} 元/月</p></el-row>
<el-row style="display: flex; justify-content: flex-end; margin-top: 5px;">
<el-button
:icon="isFavorited ? 'StarFilled' : 'Star'"
circle
:type="isFavorited ? 'warning' : 'default'"
size="large"
@click="handleFavorite"
/>
</el-row>
<div style="display: flex; justify-content: flex-end; margin-top: 15px;">
<button style="padding: 8px 16px; background-color: #409EFF; color: white; border: none; border-radius: 4px; font-size: 14px; cursor: pointer;"
@click="subapplication">
申请租房
</button>
</div>
</el-col>
</el-main>
</el-container>
<!-- 评论区 -->
<el-main style="margin-top: 20px;">
<div style="display: flex; align-items: center; margin-bottom: 15px;">
<h2 style="font-size: 20px; font-weight: bold;">用户评论 ({{ commentCount }})</h2>
<div class="line" style="margin-left: 1.5%; flex: 1; height: 1px; background-color: #eee;"></div>
</div>
<!-- 评论列表(评论数>0时显示) -->
<div v-if="comments.length > 0">
<div
v-for="comment in comments"
:key="comment.id"
style="margin-bottom: 15px; padding: 15px; border: 1px solid #ebeef5; border-radius: 4px;"
>
<!-- 评论头部:用户信息+评分+时间 -->
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
<div>
<span style="font-weight: 600; color: #303133;">用户:{{ userMap[comment.tenantId] || '匿名用户' }}</span>
<el-rate
v-model="comment.rating"
disabled
:colors="['#99A9BF', '#F7BA1E', '#FF9900']"
style="margin-left: 10px;"
/>
</div>
<span style="font-size: 12px; color: #909399;">{{ formatDate(comment.commentTime) }}</span>
</div>
<!-- 评论内容 -->
<div style="color: #606266; line-height: 1.6;">{{ comment.content }}</div>
</div>
</div>
<!-- 暂无评论(评论数=0时显示) -->
<div v-else style="text-align: center; padding: 50px 0; color: #909399;">
暂无评论,快来发表第一条评论吧!
</div>
<!-- 评论输入框 -->
<div style="margin-bottom: 30px; padding: 20px; background-color: #f5f7fa; border-radius: 8px;">
<!-- 五星评分 -->
<div class="demo-rate-block">
<span class="demonstration" style="font-size: 20px; font-weight: bold;">评分:</span>
<el-rate v-model="rating" :colors="colors" />
</div>
<textarea
v-model="commentContent"
style="width: 100%; height: 120px; padding: 12px; border: 1px solid #dcdfe6; border-radius: 4px; resize: none; font-size: 14px; color: #606266; outline: none;"
placeholder="分享你的想法..."></textarea>
<div style="display: flex; justify-content: flex-end; margin-top: 15px;">
<button style="padding: 8px 16px; background-color: #409eff; color: white; border: none; border-radius: 4px; font-size: 14px; cursor: pointer;"
@click="subComment">
发布评论
</button>
</div>
</div>
</el-main>
</el-container>
</div>
</el-card>
</div>
</template>
<script src="@/assets/js/FavoriteHouseDisplay.js"></script>
|
2301_79970562/student_union_frontend
|
src/views/FavoriteHouseDisplay.vue
|
Vue
|
unknown
| 6,690
|
<template>
<div class="background">
<div class="common-layout">
<el-container>
<el-header class="header_background">
<div style="position: absolute; top: 0.1%; left: 2%;">
<img alt="" src="@/assets/logo1.png" style="width: 40px;">
</div>
<div style="position: absolute; top: 1.5%; left: 38%;">
<span style="font-size: 15px; font-weight: bold; color: whitesmoke">
您好,用户 {{ username }} !欢迎进入房屋租赁平台!
</span>
</div>
<div class="right-info">
<el-button @click="SignOut" style="margin-right: 10px;">
<el-icon :size="18" style="margin-right: 5px;">
<avatar />
</el-icon>
退出登录
</el-button>
</div>
</el-header>
<el-header class="sub_header_background">
<el-menu
:default-active="activeIndex"
router
class="el-menu-demo"
mode="horizontal"
background-color="#545c64"
text-color="whitesmoke"
active-text-color="white"
style="height: 102%;"
unique-opened
>
<el-menu-item index="/tenantHome">首页</el-menu-item>
<el-menu-item index="/TenantFavorite">我的收藏</el-menu-item>
<el-sub-menu index="transaction">
<template #title>交易管理</template>
<el-menu-item index="/TenantApplication">我的申请</el-menu-item>
<el-menu-item index="/TenantRecord">交易记录</el-menu-item>
</el-sub-menu>
<el-menu-item index="/SelectHouse">查看房源</el-menu-item>
<el-menu-item index="/VectorDatabase">向量数据库</el-menu-item>
<el-menu-item index="/PersonalAssistant">RAG问答助手</el-menu-item>
<el-menu-item index="/TenantSelfInfo">个人信息</el-menu-item>
</el-menu>
</el-header>
<el-main>
<el-card id="personal-info-card" style="margin: 5px; min-height: calc(100vh - 110px);">
<!-- 房源属性查询系统 -->
<div class="graph-rag-container">
<!-- 头部标题 -->
<div class="header">
<h1>房源属性查询系统</h1>
<p>输入小区名称,可指定查询属性(如租金、户型),留空则返回全部属性</p>
</div>
<!-- 输入表单 -->
<div class="form-group">
<label for="community">小区名称 <span style="color:#d32f2f">*</span></label>
<el-input
type="text"
id="community"
v-model="community"
placeholder="例如:春申万科城"
@keypress.enter="handleCommunityEnter"
></el-input>
<div class="form-hint">必填项,需准确输入小区名称关键词</div>
</div>
<div class="form-group">
<label for="property">查询属性(可选)</label>
<el-input
type="text"
id="property"
v-model="property"
placeholder="例如:租金、户型、面积(留空返回全部属性)"
@keypress.enter="submitQuery"
></el-input>
<div class="form-hint">支持同义词:如"价格"=租金、"楼层"=层高、"方向"=朝向</div>
</div>
<el-button class="btn-submit" @click="submitQuery" :loading="loading">
查询小区属性
</el-button>
<!-- 加载状态 -->
<div class="loading" v-if="loading">
<div class="spinner"></div>
<p>正在查询,请稍候...</p>
</div>
<!-- 错误提示 -->
<el-alert
v-if="error"
:title="error"
type="error"
show-icon
class="error-alert"
></el-alert>
<!-- 结果展示 -->
<div class="result" v-if="resultData">
<div class="result-header">
<div class="result-title">查询结果:{{ resultData.community }}</div>
<div class="result-subtitle">查询属性:{{ resultData.property }}</div>
</div>
<div class="result-content">{{ resultData.answer }}</div>
<div class="result-sources" v-if="resultData.sources && resultData.sources.length > 0">
<div class="sources-title">参考信息</div>
<div v-for="(src, index) in resultData.sources" :key="index" class="source-item">
{{ src }}
</div>
</div>
</div>
</div>
</el-card>
</el-main>
</el-container>
</div>
</div>
</template>
<script>
import request from "@/axios/request";
import { ElMessage } from 'element-plus';
export default {
data() {
return {
loading: false,
tenantId: '',
username: '',
password: '',
phone: '',
email: '',
activeIndex: '/PersonalAssistant',
// GraphRAG 相关数据
community: '',
property: '',
error: '',
resultData: null
};
},
mounted() {
this.fetchUserInfo();
},
methods: {
async fetchUserInfo() {
let token = JSON.parse(window.sessionStorage.getItem('userInfo'));
if (token && token.tenantId) {
const tenantId = token.tenantId;
const res = await request.get(`/tenant/findById/${tenantId}`);
if (res.code === 200) {
token = res.data;
} else {
ElMessage.error("获取用户信息失败");
}
console.log(token);
if (!token) {
ElMessage.error("获取用户信息失败");
console.log("获取用户信息失败");
return;
}
this.tenantId = token.tenantId;
this.username = token.username;
this.password = token.password;
this.phone = token.phone;
this.email = token.email;
}
},
SignOut() {
sessionStorage.clear();
ElMessage({
message: '用户退出登录',
type: 'success',
});
this.$router.replace({ path: '/Login' });
},
// 处理小区名称输入框的Enter键
handleCommunityEnter() {
document.getElementById("property").focus();
},
// 提交查询函数
async submitQuery() {
// 1. 输入验证
if (!this.community) {
this.error = "请输入小区名称(必填项)";
this.resultData = null;
return;
}
this.error = ''; // 清除之前的错误提示
// 2. 显示加载状态
this.loading = true;
this.resultData = null;
try {
// 3. 发送请求到后端
const response = await fetch("http://localhost:8085/rag/query", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
community: this.community,
question: this.property
})
});
// 4. 处理响应
if (!response.ok) {
throw new Error(`请求失败(${response.status}):${response.statusText}`);
}
const data = await response.json();
// 5. 展示结果
if (data.code === 200) {
this.resultData = data.data;
} else {
this.error = `查询失败:${data.msg}`;
}
} catch (err) {
// 6. 处理异常
this.error = `系统错误:${err.message}(请检查后端服务是否启动)`;
} finally {
// 7. 隐藏加载状态
this.loading = false;
}
}
}
};
</script>
<style scoped>
.background {
background-color: whitesmoke;
height: 100vh;
}
.header_background {
background-color: #1b4989;
height: 6vh;
}
.sub_header_background {
background-color: #545c64;
height: 7vh;
}
.right-info {
width: 100px;
position: absolute;
right: 2%;
top: 0.7%
}
.right-info:hover {
cursor: pointer;
}
.el-card:hover {
transform: translateY(-5px);
box-shadow: 0 10px 15px rgba(0, 0, 0, 0.2), 0 6px 20px rgba(0, 0, 0, 0.2);
border-color: #409EFF;
}
.line {
background: url(https://www.upc.edu.cn/ximages/tit1.png) center repeat-x;
height: 0.4rem;
flex: 1;
background-size: auto;
margin: 0.16rem;
}
/* GraphRAG 样式 */
.graph-rag-container {
max-width: 700px;
margin: 0 auto;
background: white;
border-radius: 12px;
padding: 30px;
box-shadow: 0 2px 15px rgba(0,0,0,0.05);
}
.graph-rag-container .header {
text-align: center;
margin-bottom: 30px;
}
.graph-rag-container .header h1 {
color: #1a73e8;
font-size: 24px;
margin-bottom: 8px;
}
.graph-rag-container .header p {
color: #666;
font-size: 14px;
}
.graph-rag-container .form-group {
margin-bottom: 22px;
}
.graph-rag-container .form-group label {
display: block;
margin-bottom: 8px;
color: #333;
font-weight: 500;
font-size: 15px;
}
.graph-rag-container .form-hint {
margin-top: 6px;
color: #888;
font-size: 13px;
}
.graph-rag-container .btn-submit {
width: 100%;
padding: 14px;
background-color: #1a73e8;
color: white;
border: none;
border-radius: 8px;
font-size: 16px;
font-weight: 500;
cursor: pointer;
transition: background-color 0.3s;
}
.graph-rag-container .btn-submit:hover {
background-color: #1557b0;
}
.graph-rag-container .loading {
text-align: center;
padding: 30px 0;
}
.graph-rag-container .loading .spinner {
width: 24px;
height: 24px;
border: 3px solid rgba(26, 115, 232, 0.2);
border-top-color: #1a73e8;
border-radius: 50%;
animation: spin 1s linear infinite;
margin: 0 auto 12px;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
.graph-rag-container .loading p {
color: #666;
font-size: 15px;
}
.graph-rag-container .result {
margin-top: 30px;
padding: 24px;
border-radius: 8px;
background-color: #f8fafc;
border: 1px solid #e2e8f0;
}
.graph-rag-container .result-header {
margin-bottom: 16px;
padding-bottom: 12px;
border-bottom: 1px solid #e2e8f0;
}
.graph-rag-container .result-title {
font-size: 16px;
color: #333;
font-weight: 500;
margin-bottom: 4px;
}
.graph-rag-container .result-subtitle {
font-size: 13px;
color: #666;
}
.graph-rag-container .result-content {
font-size: 15px;
color: #333;
line-height: 1.6;
white-space: pre-line;
}
.graph-rag-container .result-sources {
margin-top: 20px;
padding-top: 16px;
border-top: 1px dashed #e2e8f0;
}
.graph-rag-container .sources-title {
font-size: 14px;
color: #666;
font-weight: 500;
margin-bottom: 8px;
}
.graph-rag-container .source-item {
font-size: 13px;
color: #888;
margin-bottom: 4px;
padding-left: 12px;
position: relative;
}
.graph-rag-container .source-item::before {
content: "•";
position: absolute;
left: 0;
color: #bbb;
}
.graph-rag-container .error-alert {
margin-top: 30px;
}
</style>
|
2301_79970562/student_union_frontend
|
src/views/GraphRAGAssistant.vue
|
Vue
|
unknown
| 11,369
|
<template>
<div>
<el-breadcrumb separator-icon="ArrowRight" style="margin: 16px">
<el-breadcrumb-item :to="{ path: '/tenantHome' }">首页</el-breadcrumb-item>
<el-breadcrumb-item>房源信息展示</el-breadcrumb-item>
<router-link to="/TenantHome" style="position: relative; right: -80%;">
<el-button type="primary" style="width: 55px; height: 33px; font-size: 14px; font-family: 'Segoe UI'; border-radius: 10px;">返回</el-button>
</router-link>
</el-breadcrumb>
<el-card style="margin: 15px; min-height: calc(100vh - 111px)">
<div class="common-layout">
<el-container>
<el-header>
<h1 style="font-size: 26px; font-weight: bold; text-align: center; ">{{ Data.title }}</h1>
<el-tag
:type="getStatusTagType(Data.status)"
size="large" style="position: relative; left: 94%; top: -57%; font-weight: bold; font-size: 14px;">
{{ getStatusLabel(Data.status) }}
</el-tag>
</el-header>
<el-container>
<el-aside width="500px">
<el-image :src="Data.imageUrl" fit="fill" style="width: 100%; height: 100%; border-radius: 10px;"></el-image>
</el-aside>
<el-main>
<el-col :gutter="20" style="margin-top: -20px;">
<el-row :span="8"><p><strong>住房名称:</strong>{{ Data.title }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>住房编号:</strong>{{ Data.houseId }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>房东编号:</strong>{{ Data.landlordId }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>所在地区:</strong>{{ Data.area }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>地址:</strong>{{ Data.address }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>住房描述:</strong>{{ Data.description }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>住房面积:</strong>{{ Data.size }} 平方米</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>户型:</strong>{{ Data.roomCount }} 居室</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>楼层:</strong>{{ Data.floor }} 层</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>租金:</strong>{{ Data.price }} 元/月</p></el-row>
<el-row style="display: flex; justify-content: flex-end; margin-top: 5px;">
<el-button
:icon="isFavorited ? 'StarFilled' : 'Star'"
circle
:type="isFavorited ? 'warning' : 'default'"
size="large"
@click="handleFavorite"
/>
</el-row>
<div style="display: flex; justify-content: flex-end; margin-top: 15px;">
<button style="padding: 8px 16px; background-color: #409EFF; color: white; border: none; border-radius: 4px; font-size: 14px; cursor: pointer;"
@click="subapplication">
申请租房
</button>
</div>
</el-col>
</el-main>
</el-container>
<!-- 评论区 -->
<el-main style="margin-top: 20px;">
<div style="display: flex; align-items: center; margin-bottom: 15px;">
<h2 style="font-size: 20px; font-weight: bold;">用户评论 ({{ commentCount }})</h2>
<div class="line" style="margin-left: 1.5%; flex: 1; height: 1px; background-color: #eee;"></div>
</div>
<!-- 评论列表(评论数>0时显示) -->
<div v-if="comments.length > 0">
<div
v-for="comment in comments"
:key="comment.id"
style="margin-bottom: 15px; padding: 15px; border: 1px solid #ebeef5; border-radius: 4px;"
>
<!-- 评论头部:用户信息+评分+时间 -->
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
<div>
<span style="font-weight: 600; color: #303133;">{{ userMap[comment.tenantId] || '匿名用户' }}</span>
<el-rate
v-model="comment.rating"
disabled
:colors="['#99A9BF', '#F7BA1E', '#FF9900']"
style="margin-left: 10px;"
/>
</div>
<span style="font-size: 12px; color: #909399;">{{ formatDate(comment.commentTime) }}</span>
</div>
<!-- 评论内容 -->
<div style="color: #606266; line-height: 1.6;">{{ comment.content }}</div>
</div>
</div>
<!-- 暂无评论(评论数=0时显示) -->
<div v-else style="text-align: center; padding: 50px 0; color: #909399;">
暂无评论,快来发表第一条评论吧!
</div>
<!-- 评论输入框 -->
<div style="margin-bottom: 30px; padding: 20px; background-color: #f5f7fa; border-radius: 8px;">
<!-- 五星评分 -->
<div class="demo-rate-block">
<span class="demonstration" style="font-size: 20px; font-weight: bold;">评分:</span>
<el-rate v-model="rating" :colors="colors" />
</div>
<textarea
v-model="commentContent"
style="width: 100%; height: 120px; padding: 12px; border: 1px solid #dcdfe6; border-radius: 4px; resize: none; font-size: 14px; color: #606266; outline: none;"
placeholder="分享你的想法..."></textarea>
<div style="display: flex; justify-content: flex-end; margin-top: 15px;">
<button style="padding: 8px 16px; background-color: #409eff; color: white; border: none; border-radius: 4px; font-size: 14px; cursor: pointer;"
@click="subComment">
发布评论
</button>
</div>
</div>
</el-main>
</el-container>
</div>
</el-card>
</div>
</template>
<script src="@/assets/js/HomeDisplay.js"></script>
|
2301_79970562/student_union_frontend
|
src/views/HomeDisplay.vue
|
Vue
|
unknown
| 6,574
|
<template>
<div>
<el-breadcrumb separator-icon="ArrowRight" style="margin: 16px">
<el-breadcrumb-item :to="{ path: '/adminHome' }">首页</el-breadcrumb-item>
<el-breadcrumb-item>房源信息管理</el-breadcrumb-item>
<el-breadcrumb-item>房源审核</el-breadcrumb-item>
</el-breadcrumb>
<el-card style="margin: 15px; min-height: calc(100vh - 111px)">
<div style="color: black; font-size: 20px;font-weight: bolder; text-align: center;">待审核房源列表</div>
<div>
<div style="margin: 40px 0;">
<div style="margin: 10px 0">
<el-input v-model="search"
@input="filterData"
clearable
placeholder="请输入房东ID号"
prefix-icon="Search"
style="width: 20%"/>
<el-button icon="Search" style="margin-left: 5px" type="primary" @click="filterData"></el-button>
<el-button icon="refresh-left" style="margin-left: 10px" type="default" @click="reset"></el-button>
</div>
</div>
<!--房源容器-->
<div v-for="item in tableData" :key="item.houseId">
<el-card style="width: 100%; margin-bottom: 10px;">
<div class="common-layout">
<el-container>
<!-- 左侧显示图片 -->
<el-aside width="200px">
<el-image :src="item.imageUrl" fit="fill" style="width: 100%; height: 100%"></el-image>
</el-aside>
<el-container>
<!-- 头部显示标题及链接 -->
<el-header style="text-align: center;">
<router-link :to="{ name: 'AdminAuditionHouseDisplay', query: { houseId: item.houseId } }">
{{ item.title }}
</router-link>
</el-header>
<!-- 房源描述 -->
<el-main style="margin-top: -35px;">
{{ item.description }}
</el-main>
</el-container>
<!-- 操作按钮 -->
<el-aside width="200px" style="display: flex; flex-direction: column; align-items: center; justify-content: center;">
<el-space direction="vertical" alignment="center">
<el-button icon="CircleCheck" type="primary" @click="handleConfirm(item.houseId)">通过申请</el-button>
<el-popconfirm title="确认拒绝该出租请求?" @confirm="handleReject(item.houseId)">
<template #reference>
<el-button icon="Delete" type="danger">拒绝申请</el-button>
</template>
</el-popconfirm>
</el-space>
</el-aside>
</el-container>
</div>
</el-card>
</div>
<!--分页-->
<div style="margin: 40px 0">
<el-pagination
v-model:currentPage="currentPage"
:page-size="pageSize"
:page-sizes="[5, 10, 15]"
:total="total"
layout="total, sizes, prev, pager, next, jumper"
@size-change="handleSizeChange"
@current-change="handleCurrentChange"></el-pagination>
</div>
</div>
</el-card>
</div>
</template>
<script src="@/assets/js/HouseAudition.js"></script>
<style scoped>
.el-card:hover {
transform: translateY(-5px);
box-shadow: 0 10px 15px rgba(0, 0, 0, 0.2), 0 6px 20px rgba(0, 0, 0, 0.2);
border-color: rgba(0, 0, 0, 0.2);
}
</style>
|
2301_79970562/student_union_frontend
|
src/views/HouseAudition.vue
|
Vue
|
unknown
| 3,651
|
<template>
<div>
<el-breadcrumb separator-icon="ArrowRight" style="margin: 16px">
<el-breadcrumb-item :to="{ path: '/adminHome' }">首页</el-breadcrumb-item>
<el-breadcrumb-item>房源信息管理</el-breadcrumb-item>
<el-breadcrumb-item>房源删除</el-breadcrumb-item>
</el-breadcrumb>
<el-card style="margin: 15px; min-height: calc(100vh - 111px)">
<div style="color: black; font-size: 20px;font-weight: bolder; text-align: center;">房源总列表</div>
<div>
<div style="margin: 40px 0">
<div style="margin: 10px 0">
<el-input v-model="search"
@input="filterData"
clearable
placeholder="请输入房屋ID号"
prefix-icon="Search"
style="width: 20%"/>
<el-button icon="Search" style="margin-left: 5px" type="primary" @click="filterData"></el-button>
<el-button icon="refresh-left" style="margin-left: 10px" type="default" @click="reset"></el-button>
</div>
</div>
<!--表格-->
<el-table v-loading="loading" :data="tableData" border max-height="705" style="width: 100%">
<el-table-column label="房源信息">
<template #default="{ row }">
<el-card style="width: 100%; margin-bottom: 10px;">
<div class="common-layout">
<el-container>
<!-- 左侧显示图片 -->
<el-aside width="200px">
<el-image :src="row.imageUrl" fit="fill" style="width: 100%; height: 100%"></el-image>
</el-aside>
<el-container>
<!-- 头部显示标题及链接 -->
<el-header style="text-align: center;">
<router-link :to="{ name: 'AdminAuditionHouseDisplay', query: { houseId: row.houseId } }">
{{ row.title }}
</router-link>
<el-tag
:type="getStatusTagType(row.status)"
effect="dark"
size="medium"
style="width: auto; height: 30px; position: absolute; right: 30px; top: 15%; transform: translateY(-40%); font-weight: bolder ; font-size: 14.5px; white-space: nowrap;"
>
{{ getStatusLabel(row.status) }}
</el-tag>
</el-header>
<!-- 房源描述 -->
<el-main style="margin-top: -35px;">
{{ row.description }}
</el-main>
</el-container>
</el-container>
</div>
</el-card>
</template>
</el-table-column>
<el-table-column label="操作" width="130px">
<template #default="scope">
<el-popconfirm title="确认删除?" @confirm="handleDelete(scope.row)">
<template #reference>
<el-button icon="Delete" type="danger">删除</el-button>
</template>
</el-popconfirm>
</template>
</el-table-column>
</el-table>
<!--分页-->
<div style="margin: 40px 0">
<el-pagination
v-model:currentPage="currentPage"
:page-size="pageSize"
:page-sizes="[5, 10, 15]"
:total="total"
layout="total, sizes, prev, pager, next, jumper"
@size-change="handleSizeChange"
@current-change="handleCurrentChange"></el-pagination>
</div>
</div>
</el-card>
</div>
</template>
<script src="@/assets/js/HouseDelete.js"></script>
|
2301_79970562/student_union_frontend
|
src/views/HouseDelete.vue
|
Vue
|
unknown
| 3,860
|
<template>
<div>
<el-breadcrumb separator-icon="ArrowRight" style="margin: 16px">
<el-breadcrumb-item :to="{ path: '/tenantHome' }">首页</el-breadcrumb-item>
<el-breadcrumb-item :to="{ path: '/SelectHouse' }">查看房源</el-breadcrumb-item>
<el-breadcrumb-item>房源信息展示</el-breadcrumb-item>
<router-link to="/SelectHouse" style="position: relative; right: -72%;">
<el-button type="primary" style="width: 55px; height: 33px; font-size: 14px; font-family: 'Segoe UI'; border-radius: 10px;">返回</el-button>
</router-link>
</el-breadcrumb>
<el-card style="margin: 15px; min-height: calc(100vh - 111px)">
<div class="common-layout">
<el-container>
<el-header>
<h1 style="font-size: 26px; font-weight: bold; text-align: center; ">{{ Data.title }}</h1>
<el-tag
:type="getStatusTagType(Data.status)"
size="large" style="position: relative; left: 94%; top: -57%; font-weight: bold; font-size: 14px;">
{{ getStatusLabel(Data.status) }}
</el-tag>
</el-header>
<el-container>
<el-aside width="500px">
<el-image :src="Data.imageUrl" fit="fill" style="width: 100%; height: 100%; border-radius: 10px;"></el-image>
</el-aside>
<el-main>
<el-col :gutter="20" style="margin-top: -20px;">
<el-row :span="8"><p><strong>住房名称:</strong>{{ Data.title }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>住房编号:</strong>{{ Data.houseId }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>房东编号:</strong>{{ Data.landlordId }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>所在地区:</strong>{{ Data.area }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>地址:</strong>{{ Data.address }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>住房描述:</strong>{{ Data.description }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>住房面积:</strong>{{ Data.size }} 平方米</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>户型:</strong>{{ Data.roomCount }} 居室</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>楼层:</strong>{{ Data.floor }} 层</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>租金:</strong>{{ Data.price }} 元/月</p></el-row>
<el-row style="display: flex; justify-content: flex-end; margin-top: 5px;">
<el-button
:icon="isFavorited ? 'StarFilled' : 'Star'"
circle
:type="isFavorited ? 'warning' : 'default'"
size="large"
@click="handleFavorite"
/>
</el-row>
<div style="display: flex; justify-content: flex-end; margin-top: 15px;">
<button style="padding: 8px 16px; background-color: #409EFF; color: white; border: none; border-radius: 4px; font-size: 14px; cursor: pointer;"
@click="subapplication">
申请租房
</button>
</div>
</el-col>
</el-main>
</el-container>
<!-- 评论区 -->
<el-main style="margin-top: 20px;">
<div style="display: flex; align-items: center; margin-bottom: 15px;">
<h2 style="font-size: 20px; font-weight: bold;">用户评论 ({{ commentCount }})</h2>
<div class="line" style="margin-left: 1.5%; flex: 1; height: 1px; background-color: #eee;"></div>
</div>
<!-- 评论列表(评论数>0时显示) -->
<div v-if="comments.length > 0">
<div
v-for="comment in comments"
:key="comment.id"
style="margin-bottom: 15px; padding: 15px; border: 1px solid #ebeef5; border-radius: 4px;"
>
<!-- 评论头部:用户信息+评分+时间 -->
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
<div>
<span style="font-weight: 600; color: #303133;">{{ userMap[comment.tenantId] || '匿名用户' }}</span>
<el-rate
v-model="comment.rating"
disabled
:colors="['#99A9BF', '#F7BA1E', '#FF9900']"
style="margin-left: 10px;"
/>
</div>
<span style="font-size: 12px; color: #909399;">{{ formatDate(comment.commentTime) }}</span>
</div>
<!-- 评论内容 -->
<div style="color: #606266; line-height: 1.6;">{{ comment.content }}</div>
</div>
</div>
<!-- 暂无评论(评论数=0时显示) -->
<div v-else style="text-align: center; padding: 50px 0; color: #909399;">
暂无评论,快来发表第一条评论吧!
</div>
<!-- 评论输入框 -->
<div style="margin-bottom: 30px; padding: 20px; background-color: #f5f7fa; border-radius: 8px;">
<!-- 五星评分 -->
<div class="demo-rate-block">
<span class="demonstration" style="font-size: 20px; font-weight: bold;">评分:</span>
<el-rate v-model="rating" :colors="colors" />
</div>
<textarea
v-model="commentContent"
style="width: 100%; height: 120px; padding: 12px; border: 1px solid #dcdfe6; border-radius: 4px; resize: none; font-size: 14px; color: #606266; outline: none;"
placeholder="分享你的想法..."></textarea>
<div style="display: flex; justify-content: flex-end; margin-top: 15px;">
<button style="padding: 8px 16px; background-color: #409eff; color: white; border: none; border-radius: 4px; font-size: 14px; cursor: pointer;"
@click="subComment">
发布评论
</button>
</div>
</div>
</el-main>
</el-container>
</div>
</el-card>
</div>
</template>
<script src="@/assets/js/HouseDisplay.js"></script>
|
2301_79970562/student_union_frontend
|
src/views/HouseDisplay.vue
|
Vue
|
unknown
| 6,667
|
<template>
<div class="background">
<div class="common-layout">
<el-container>
<el-header class="header_background">
<div style="position: absolute; top: 0.1%; left: 2%;">
<img alt="" src="@/assets/logo1.png" style="width: 40px;">
</div>
<div style="position: absolute; top: 1.5%; left: 38%;">
<span style="font-size: 15px; font-weight: bold; color: whitesmoke">
您好,房东 {{ username }} !欢迎进入房屋租赁平台!
</span>
</div>
<div class="right-info">
<el-button @click="SignOut" style="margin-right: 10px;">
<el-icon :size="18" style="margin-right: 5px;">
<avatar />
</el-icon>
退出登录
</el-button>
</div>
</el-header>
<el-header class="sub_header_background">
<el-menu
:default-active="activeIndex"
router
class="el-menu-demo"
mode="horizontal"
background-color="#545c64"
text-color="whitesmoke"
active-text-color="white"
style="height: 102%;"
unique-opened
>
<el-menu-item index="/LandlordHome">首页</el-menu-item>
<el-menu-item index="/LandlordHouse">我的房源</el-menu-item>
<el-sub-menu index="transaction">
<template #title>交易管理</template>
<el-menu-item index="/ApplicationAudition">租客申请审核</el-menu-item>
<el-menu-item index="/LandlordTransactionRecord">交易记录</el-menu-item>
</el-sub-menu>
<el-menu-item index="/LandlordSelfInfo">个人信息</el-menu-item>
</el-menu>
</el-header>
<el-header class="sub_sub_header_background">
<div class="block text-center">
<el-carousel :interval="4000" type="card" height="300px">
<el-carousel-item v-for="(image, index) in images" :key="index">
<img :src="image.src" :alt="image.alt" style="width: 160%; height: 100%; object-fit: fill;" />
</el-carousel-item>
</el-carousel>
</div>
</el-header>
<el-main>
<div class="font" style="font-weight: bold; font-family: Microsoft YaHei; font-size: 20px; margin-top: 0%;">
精选<font>房源</font>
<router-link to="/AllHouses" style="position: relative; left: 87%; font-size: 14px">查看更多</router-link>
</div>
<div class="line"></div>
<div style="display: flex; flex-wrap: wrap; gap: 20px;">
<div v-if="total === 0" style="position: relative; left: 47.5%; margin-top: 8%;">
暂无数据
</div>
<!-- 将v-for移到el-card上,确保每个数据项都有独立的卡片 -->
<div v-else v-for="item in firstSixData" :key="item.houseId">
<el-card shadow="hover" style="margin-top: 1%;margin-left: 5%; width: calc(90% - 10px); padding: 15px; background-color: #f9f9f9; border: 1px solid #ebebeb; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1), 0 6px 20px rgba(0, 0, 0, 0.1); transition: all 0.3s ease; ">
<div class="common-layout">
<el-container>
<el-aside width="200px">
<el-image :src="item.imageUrl" fit="fill" style="width: 100%; height: 100%"></el-image>
</el-aside>
<el-container>
<el-header style="position: relative; padding-right: 80px;">
<router-link
:to="{ name: 'LandlordHomeDisplay', query: { houseId: item.houseId } }"
style="font-family: Microsoft YaHei; display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;"
>
{{ item.title }}:{{ item.address }}
</router-link>
<el-tag
:type="getStatusTagType(item.status)"
effect="dark"
size="medium"
style="width: auto; height: 30px; position: absolute; right: 0; top: 20%; transform: translateY(-40%); font-weight: bolder ; font-size: 14.5px; white-space: nowrap;"
>
{{ getStatusLabel(item.status) }}
</el-tag>
</el-header>
<el-main style="margin-top: -5%;">
{{ item.description }}
</el-main>
</el-container>
</el-container>
</div>
</el-card>
</div>
</div>
</el-main>
</el-container>
</div>
</div>
</template>
<script src="@/assets/js/LandlordHome.js"></script>
<style scoped>
.background {
background-color: whitesmoke;
min-height: 100vh;
}
.header_background {
background-color: #1b4989;
height: 6vh;
}
.sub_header_background {
background-color: #545c64;
height: 7vh;
}
.sub_sub_header_background {
background-color: #ddebff;
height: 43.1vh;
}
.right-info {
width: 100px;
position: absolute;
right: 2%;
top: 0.7%
}
.right-info:hover {
cursor: pointer;
}
.el-carousel__item h3 {
color: #475669;
opacity: 0.75;
line-height: 200px;
margin: 0;
text-align: center;
}
.el-carousel__item:nth-child(2n) {
background-color: #99a9bf;
}
.el-carousel__item:nth-child(2n + 1) {
background-color: #d3dce6;
}
.font font {
color: #0465C4;
}
.line{
background: url(https://www.upc.edu.cn/ximages/tit1.png) center repeat-x;
height: 0.4rem;
flex: 1;
background-size: auto;
margin: 0.16rem;
}
.el-card:hover {
transform: translateY(-7px);
box-shadow: 0 10px 15px rgba(0, 0, 0, 0.2), 0 6px 20px rgba(0, 0, 0, 0.2);
border-color: rgba(0, 0, 0, 0.2);
}
</style>
|
2301_79970562/student_union_frontend
|
src/views/LandlordHome.vue
|
Vue
|
unknown
| 6,973
|
<template>
<div>
<el-breadcrumb separator-icon="ArrowRight" style="margin: 16px">
<el-breadcrumb-item :to="{ path: '/landlordHome' }">首页</el-breadcrumb-item>
<el-breadcrumb-item>房源信息展示</el-breadcrumb-item>
<router-link to="/landlordHome" style="position: relative; right: -80%;">
<el-button type="primary" style="width: 55px; height: 33px; font-size: 14px; font-family: 'Segoe UI'; border-radius: 10px;">返回</el-button>
</router-link>
</el-breadcrumb>
<el-card style="margin: 15px; min-height: calc(100vh - 111px)">
<div class="common-layout">
<el-container>
<el-header>
<h1 style="font-size: 26px; font-weight: bold; text-align: center; ">{{ Data.title }}</h1>
<el-tag
:type="getStatusTagType(Data.status)"
size="large" style="position: relative; left: 94%; top: -57%; font-weight: bold; font-size: 14px;">
{{ getStatusLabel(Data.status) }}
</el-tag>
</el-header>
<el-container>
<el-aside width="500px">
<el-image :src="Data.imageUrl" fit="fill" style="width: 100%; height: 100%; border-radius: 10px;"></el-image>
</el-aside>
<el-main>
<el-col :gutter="20" style="margin-top: -20px;">
<el-row :span="8"><p><strong>住房名称:</strong>{{ Data.title }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>住房编号:</strong>{{ Data.houseId }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>房东编号:</strong>{{ Data.landlordId }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>所在地区:</strong>{{ Data.area }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>地址:</strong>{{ Data.address }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>住房描述:</strong>{{ Data.description }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>住房面积:</strong>{{ Data.size }} 平方米</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>户型:</strong>{{ Data.roomCount }} 居室</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>楼层:</strong>{{ Data.floor }} 层</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>租金:</strong>{{ Data.price }} 元/月</p></el-row>
</el-col>
</el-main>
</el-container>
<!-- 评论区 -->
<el-main style="margin-top: 20px;">
<div style="display: flex; align-items: center; margin-bottom: 15px;">
<h2 style="font-size: 20px; font-weight: bold;">用户评论 ({{ commentCount }})</h2>
<div class="line" style="margin-left: 1.5%; flex: 1; height: 1px; background-color: #eee;"></div>
</div>
<!-- 评论列表(评论数>0时显示) -->
<div v-if="comments.length > 0">
<div
v-for="comment in comments"
:key="comment.id"
style="margin-bottom: 15px; padding: 15px; border: 1px solid #ebeef5; border-radius: 4px;"
>
<!-- 评论头部:用户信息+评分+时间 -->
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
<div>
<span style="font-weight: 600; color: #303133;">{{ userMap[comment.tenantId] || '匿名用户' }}</span>
<el-rate
v-model="comment.rating"
disabled
:colors="['#99A9BF', '#F7BA1E', '#FF9900']"
style="margin-left: 10px;"
/>
</div>
<span style="font-size: 12px; color: #909399;">{{ formatDate(comment.commentTime) }}</span>
</div>
<!-- 评论内容 -->
<div style="color: #606266; line-height: 1.6;">{{ comment.content }}</div>
</div>
</div>
<!-- 暂无评论(评论数=0时显示) -->
<div v-else style="text-align: center; padding: 50px 0; color: #909399;">
暂无评论
</div>
</el-main>
</el-container>
</div>
</el-card>
</div>
</template>
<script src="@/assets/js/HomeDisplay.js"></script>
|
2301_79970562/student_union_frontend
|
src/views/LandlordHomeDisplay.vue
|
Vue
|
unknown
| 4,644
|
<template>
<div class="background">
<div class="common-layout">
<el-container>
<el-header class="header_background">
<div style="position: absolute; top: 0.1%; left: 2%;">
<img alt="" src="@/assets/logo1.png" style="width: 40px;">
</div>
<div style="position: absolute; top: 1.5%; left: 38%;">
<span style="font-size: 15px; font-weight: bold; color: whitesmoke">
您好,房东 {{ username }} !欢迎进入房屋租赁平台!
</span>
</div>
<div class="right-info">
<el-button @click="SignOut" style="margin-right: 10px;">
<el-icon :size="18" style="margin-right: 5px;">
<avatar />
</el-icon>
退出登录
</el-button>
</div>
</el-header>
<el-header class="sub_header_background">
<el-menu
:default-active="activeIndex"
router
class="el-menu-demo"
mode="horizontal"
background-color="#545c64"
text-color="whitesmoke"
active-text-color="white"
style="height: 102%;"
unique-opened
>
<el-menu-item index="/LandlordHome">首页</el-menu-item>
<el-menu-item index="/LandlordHouse">我的房源</el-menu-item>
<el-sub-menu index="transaction">
<template #title>交易管理</template>
<el-menu-item index="/ApplicationAudition">租客申请审核</el-menu-item>
<el-menu-item index="/LandlordTransactionRecord">交易记录</el-menu-item>
</el-sub-menu>
<el-menu-item index="/LandlordSelfInfo">个人信息</el-menu-item>
</el-menu>
</el-header>
<el-main>
<div style="display: flex; font-weight: bold; font-family: Microsoft YaHei; font-size: 20px; margin-top: 0%;">
我的房源列表
<div class="line" style="margin-left: 1.5%; margin-top: 1%;"></div>
</div>
<div style="display: flex; align-items: center; justify-content: space-between; margin-top: 1%;">
<div style="display: flex; align-items: center; gap: 50px;">
<el-switch v-model="available" inactive-text="上线中"></el-switch>
<el-switch v-model="rented" inactive-text="已出租"></el-switch>
<el-switch v-model="pending" inactive-text="待审核"></el-switch>
<el-switch v-model="rejected" inactive-text="已拒绝"></el-switch>
</div>
<el-tooltip content="添加出租申请" placement="top">
<el-button icon="plus" style="width: 50px; margin-right: 1%;" type="primary" @click="add"></el-button>
</el-tooltip>
</div>
<div style="display: flex; flex-wrap: wrap; gap: 20px;">
<el-card shadow="hover" style="margin-top: 2%; width: calc(100% - 10px); padding: 15px; background-color: #f9f9f9; border: 1px solid #ebebeb; box-shadow: 0 10px 15px rgba(0, 0, 0, 0.2), 0 6px 20px rgba(0, 0, 0, 0.2); transition: all 0.3s ease; ">
<el-table :data="filteredData" style="width: 100%" border>
<el-table-column label="房源列表" header-align="center">
<template #default="{ row }">
<div class="common-layout">
<el-container>
<el-aside width="200px">
<el-image :src="row.imageUrl" fit="fill" style="width: 100%; height: 100%"></el-image>
</el-aside>
<el-container>
<el-header>
<router-link :to="{ name: 'MyHouseDisplay', query: { houseId: row.houseId } }" style="font-family: Microsoft YaHei;">
{{ row.title }}:{{ row.address }}
</router-link>
</el-header>
<el-main style="margin-top: -5%;">
{{ row.description }}
<el-tag
:type="getStatusTagType(row.status)"
effect="dark"
style="position: absolute; bottom: 10px; right: 10px;"
>
{{ getStatusLabel(row.status) }}
</el-tag>
</el-main>
</el-container>
</el-container>
</div>
</template>
</el-table-column>
<el-table-column label="操作" width="150" header-align="center">
<template #default="scope">
<div style="display: flex; flex-direction: column; align-items: baseline; gap: 8px;">
<el-button icon="Edit" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
<el-popconfirm title="确认删除该房源?" @confirm="handleDelete(scope.row)">
<template #reference>
<el-button icon="Delete" type="danger">删除</el-button>
</template>
</el-popconfirm>
</div>
</template>
</el-table-column>
</el-table>
</el-card>
</div>
</el-main>
</el-container>
<!-- 修改信息弹窗 -->
<el-dialog v-model="dialogVisible1" title="编辑房源信息" width="70%" @close="resetForm1">
<el-form ref="formRef1" :model="form1" label-width="120px">
<el-form-item label="住房编号" prop="houseId">
<el-input v-model="form1.houseId" disabled style="width: 80%"></el-input>
</el-form-item>
<el-form-item label="房东编号" prop="landlordId">
<el-input v-model="form1.landlordId" disabled style="width: 80%"></el-input>
</el-form-item>
<el-form-item label="住房名称" prop="title">
<el-input v-model="form1.title" style="width: 80%"></el-input>
</el-form-item>
<el-form-item label="住房地址" prop="address">
<el-input v-model="form1.address" style="width: 80%"></el-input>
</el-form-item>
<el-form-item label="房屋描述" prop="description">
<el-input v-model="form1.description" style="width: 80%"></el-input>
</el-form-item>
<el-form-item label="出租价格" prop="price">
<el-input v-model="form1.price" style="width: 80%"></el-input>
</el-form-item>
<el-form-item label="住房所在地" prop="area">
<el-input v-model="form1.area" style="width: 80%"></el-input>
</el-form-item>
<el-form-item label="住房面积" prop="size">
<el-input v-model="form1.size" style="width: 80%"></el-input>
</el-form-item>
<el-form-item label="房间数" prop="roomCount">
<el-input v-model="form1.roomCount" style="width: 80%"></el-input>
</el-form-item>
<el-form-item label="楼层" prop="floor">
<el-input v-model="form1.floor" style="width: 80%"></el-input>
</el-form-item>
<el-form-item label="房屋图片" prop="imageUrl">
<el-upload
action="#"
:auto-upload="false"
:show-file-list="true"
:on-change="handleImageChange1"
:on-remove="handleRemove1"
:limit="1"
list-type="picture-card"
:file-list="fileList1"
>
<el-button v-if="form1.imageUrl === ''" type="primary">点击上传</el-button>
<el-text v-else>只能上传一张图片</el-text>
</el-upload>
</el-form-item>
<el-form-item label="房屋状态" prop="status">
<el-input v-model="form1.status" disabled style="width: 80%"></el-input>
</el-form-item>
</el-form>
<template #footer>
<span class="dialog-footer">
<el-button @click="cancel1">取 消</el-button>
<el-button type="primary" @click="save1">确认并重新提交审核</el-button>
</span>
</template>
</el-dialog>
<el-dialog v-model="dialogVisible2" title="添加房源信息" width="70%" @close="resetForm2">
<el-form ref="formRef2" :model="form2" label-width="120px">
<el-form-item label="住房名称" prop="title">
<el-input v-model="form2.title" style="width: 80%"></el-input>
</el-form-item>
<el-form-item label="住房地址" prop="address">
<el-input v-model="form2.address" style="width: 80%"></el-input>
</el-form-item>
<el-form-item label="房屋描述" prop="description">
<el-input v-model="form2.description" style="width: 80%"></el-input>
</el-form-item>
<el-form-item label="出租价格" prop="price">
<el-input v-model="form2.price" style="width: 80%"></el-input>
</el-form-item>
<el-form-item label="住房所在地" prop="area">
<el-input v-model="form2.area" style="width: 80%"></el-input>
</el-form-item>
<el-form-item label="住房面积" prop="size">
<el-input v-model="form2.size" style="width: 80%"></el-input>
</el-form-item>
<el-form-item label="房间数" prop="roomCount">
<el-input v-model="form2.roomCount" style="width: 80%"></el-input>
</el-form-item>
<el-form-item label="楼层" prop="floor">
<el-input v-model="form2.floor" style="width: 80%"></el-input>
</el-form-item>
<div style="display: flex; gap: 20px;">
<el-form-item label="房屋图片" prop="imageUrl">
<el-upload
action="#"
:auto-upload="false"
:show-file-list="true"
:on-change="handleImageChange2"
:on-remove="handleRemove2"
:limit="1"
list-type="picture-card"
:file-list="fileList2"
>
<el-button v-if="form2.imageUrl === ''" type="primary">点击上传</el-button>
<el-text v-else>只能上传一张图片</el-text>
</el-upload>
</el-form-item>
<el-form-item label="房屋信息文本" prop="houseInfoText">
<el-upload
action="#"
:auto-upload="false"
:on-change="handleFileChange"
:on-remove="handleFileRemove"
:limit="1"
:accept="'.doc,.docx,.pdf'"
:file-list="fileList"
>
<el-button type="primary">文件上传</el-button>
<template #tip>
<div class="el-upload__tip">
请上传 doc/docx/pdf 文件(大小<=10MB)
</div>
</template>
</el-upload>
</el-form-item>
</div>
</el-form>
<template #footer>
<span class="dialog-footer">
<el-button @click="cancel2">取 消</el-button>
<el-button type="primary" @click="save2">确认并提交审核</el-button>
</span>
</template>
</el-dialog>
</div>
</div>
</template>
<script src="@/assets/js/LandlordHouse.js"></script>
<style scoped>
.background {
background-color: whitesmoke;
height: 100vh;
}
.header_background {
background-color: #1b4989;
height: 6vh;
}
.sub_header_background {
background-color: #545c64;
height: 7vh;
}
.right-info {
width: 100px;
position: absolute;
right: 2%;
top: 0.7%
}
.right-info:hover {
cursor: pointer;
}
.el-carousel__item h3 {
color: #475669;
opacity: 0.75;
line-height: 200px;
margin: 0;
text-align: center;
}
.el-carousel__item:nth-child(2n) {
background-color: #99a9bf;
}
.el-carousel__item:nth-child(2n + 1) {
background-color: #d3dce6;
}
.line{
background: url(https://www.upc.edu.cn/ximages/tit1.png) center repeat-x;
height: 0.4rem;
flex: 1;
background-size: auto;
margin: 0.16rem;
}
</style>
|
2301_79970562/student_union_frontend
|
src/views/LandlordHouse.vue
|
Vue
|
unknown
| 14,328
|
<template>
<div>
<el-breadcrumb separator-icon="ArrowRight" style="margin: 16px">
<el-breadcrumb-item :to="{ path: '/landlordHome' }">首页</el-breadcrumb-item>
<el-breadcrumb-item :to="{ path: '/AllHouses' }">查看房源</el-breadcrumb-item>
<el-breadcrumb-item>房源信息展示</el-breadcrumb-item>
<router-link to="/AllHouses" style="position: relative; right: -72%;">
<el-button type="primary" style="width: 55px; height: 33px; font-size: 14px; font-family: 'Segoe UI'; border-radius: 10px;">返回</el-button>
</router-link>
</el-breadcrumb>
<el-card style="margin: 15px; min-height: calc(100vh - 111px)">
<div class="common-layout">
<el-container>
<el-header>
<h1 style="font-size: 26px; font-weight: bold; text-align: center; ">{{ Data.title }}</h1>
<el-tag
:type="getStatusTagType(Data.status)"
size="large" style="position: relative; left: 94%; top: -57%; font-weight: bold; font-size: 14px;">
{{ getStatusLabel(Data.status) }}
</el-tag>
</el-header>
<el-container>
<el-aside width="500px">
<el-image :src="Data.imageUrl" fit="fill" style="width: 100%; height: 100%; border-radius: 10px;"></el-image>
</el-aside>
<el-main>
<el-col :gutter="20" style="margin-top: -20px;">
<el-row :span="8"><p><strong>住房名称:</strong>{{ Data.title }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>住房编号:</strong>{{ Data.houseId }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>房东编号:</strong>{{ Data.landlordId }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>所在地区:</strong>{{ Data.area }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>地址:</strong>{{ Data.address }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>住房描述:</strong>{{ Data.description }}</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>住房面积:</strong>{{ Data.size }} 平方米</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>户型:</strong>{{ Data.roomCount }} 居室</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>楼层:</strong>{{ Data.floor }} 层</p></el-row>
<el-row :span="8" style="margin-top: 5px;"><p><strong>租金:</strong>{{ Data.price }} 元/月</p></el-row>
</el-col>
</el-main>
</el-container>
<!-- 评论区 -->
<el-main style="margin-top: 20px;">
<div style="display: flex; align-items: center; margin-bottom: 15px;">
<h2 style="font-size: 20px; font-weight: bold;">用户评论 ({{ commentCount }})</h2>
<div class="line" style="margin-left: 1.5%; flex: 1; height: 1px; background-color: #eee;"></div>
</div>
<!-- 评论列表(评论数>0时显示) -->
<div v-if="comments.length > 0">
<div
v-for="comment in comments"
:key="comment.id"
style="margin-bottom: 15px; padding: 15px; border: 1px solid #ebeef5; border-radius: 4px;"
>
<!-- 评论头部:用户信息+评分+时间 -->
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
<div>
<span style="font-weight: 600; color: #303133;">{{ userMap[comment.tenantId] || '匿名用户' }}</span>
<el-rate
v-model="comment.rating"
disabled
:colors="['#99A9BF', '#F7BA1E', '#FF9900']"
style="margin-left: 10px;"
/>
</div>
<span style="font-size: 12px; color: #909399;">{{ formatDate(comment.commentTime) }}</span>
</div>
<!-- 评论内容 -->
<div style="color: #606266; line-height: 1.6;">{{ comment.content }}</div>
</div>
</div>
<!-- 暂无评论(评论数=0时显示) -->
<div v-else style="text-align: center; padding: 50px 0; color: #909399;">
暂无评论
</div>
</el-main>
</el-container>
</div>
</el-card>
</div>
</template>
<script src="@/assets/js/HouseDisplay.js"></script>
|
2301_79970562/student_union_frontend
|
src/views/LandlordHouseDisplay.vue
|
Vue
|
unknown
| 4,731
|
<template>
<div>
<el-breadcrumb separator-icon="ArrowRight" style="margin: 16px">
<el-breadcrumb-item :to="{ path: '/adminHome' }">首页</el-breadcrumb-item>
<el-breadcrumb-item>用户信息管理</el-breadcrumb-item>
<el-breadcrumb-item>房东信息</el-breadcrumb-item>
</el-breadcrumb>
<el-card style="margin: 15px; min-height: calc(100vh - 111px)">
<div style="color: black; font-size: 20px;font-weight: bolder; text-align: center;">房东信息</div>
<div>
<div style="margin: 40px 0">
<div style="margin: 10px 0">
<el-input v-model="search"
@input="filterData"
clearable
placeholder="请输入房东ID号"
prefix-icon="Search"
style="width: 20%"/>
<el-button icon="Search" style="margin-left: 5px" type="primary" @click="filterData"></el-button>
<el-button icon="refresh-left" style="margin-left: 10px" type="default" @click="reset"></el-button>
<div style="float: right">
<el-tooltip content="添加" placement="top">
<el-button icon="plus" style="width: 50px" type="primary" @click="add"></el-button>
</el-tooltip>
</div>
</div>
</div>
<!--表格-->
<el-table v-loading="loading" :data="tableData" border max-height="705" style="width: 100%">
<el-table-column label="房东ID" prop="landlordId"/>
<el-table-column label="用户名" prop="username" sortable/>
<el-table-column label="密码" prop="password" />
<el-table-column label="电话号码" prop="phone"/>
<el-table-column :show-overflow-tooltip="true" label="邮箱" prop="email"/>
<el-table-column label="操作" width="130px">
<template #default="scope">
<el-space direction="vertical" alignment="center" style="margin-left: 13%; margin-top: 5%">
<el-button icon="Edit" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
<el-popconfirm title="确认删除?" @confirm="handleDelete(scope.row.landlordId)">
<template #reference>
<el-button icon="Delete" type="danger">删除</el-button>
</template>
</el-popconfirm>
</el-space>
</template>
</el-table-column>
</el-table>
<!--分页-->
<div style="margin: 40px 0">
<el-pagination
v-model:currentPage="currentPage"
:page-size="pageSize"
:page-sizes="[5, 10, 15]"
:total="total"
layout="total, sizes, prev, pager, next, jumper"
@size-change="handleSizeChange"
@current-change="handleCurrentChange"></el-pagination>
</div>
<div>
<!--弹窗-->
<el-dialog v-model="dialogVisible" title="添加房东信息" width="30%" @close="cancel">
<el-form ref="form" :model="form" :rules="rules" label-width="120px">
<!-- <el-form-item label="房东ID" prop="landlordId" v-if="!judgeAddOrEdit">
<el-input v-model="form.landlordId" :disabled="judgeAddOrEdit" style="width: 80%"></el-input>
</el-form-item> -->
<el-form-item label="用户名" prop="username">
<el-input v-model="form.username" :disabled="false" style="width: 80%"></el-input>
</el-form-item>
<el-form-item label="密码" prop="password">
<el-input v-model="form.password" :disabled="false" :show-password="showpassword" style="width: 80%"></el-input>
</el-form-item>
<el-form-item label="电话号码" prop="phone">
<el-input v-model.number="form.phone" style="width: 80%"></el-input>
</el-form-item>
<el-form-item label="邮箱地址" prop="email">
<el-input v-model="form.email" style="width: 80%"></el-input>
</el-form-item>
</el-form>
<template #footer>
<span class="dialog-footer">
<el-button @click="cancel">取 消</el-button>
<el-button type="primary" @click="save">确 定</el-button>
</span>
</template>
</el-dialog>
</div>
</div>
</el-card>
</div>
</template>
<script src="@/assets/js/LandlordInfo.js"></script>
|
2301_79970562/student_union_frontend
|
src/views/LandlordInfo.vue
|
Vue
|
unknown
| 4,594
|
<template>
<div class="background">
<div class="common-layout">
<el-container>
<el-header class="header_background">
<div style="position: absolute; top: 0.1%; left: 2%;">
<img alt="" src="@/assets/logo1.png" style="width: 40px;">
</div>
<div style="position: absolute; top: 1.5%; left: 38%;">
<span style="font-size: 15px; font-weight: bold; color: whitesmoke">
您好,房东 {{ username }} !欢迎进入房屋租赁平台!
</span>
</div>
<div class="right-info">
<el-button @click="SignOut" style="margin-right: 10px;">
<el-icon :size="18" style="margin-right: 5px;">
<avatar />
</el-icon>
退出登录
</el-button>
</div>
</el-header>
<el-header class="sub_header_background">
<el-menu
:default-active="activeIndex"
router
class="el-menu-demo"
mode="horizontal"
background-color="#545c64"
text-color="whitesmoke"
active-text-color="white"
style="height: 102%;"
unique-opened
>
<el-menu-item index="/LandlordHome">首页</el-menu-item>
<el-menu-item index="/LandlordHouse">我的房源</el-menu-item>
<el-sub-menu index="transaction">
<template #title>交易管理</template>
<el-menu-item index="/ApplicationAudition">租客申请审核</el-menu-item>
<el-menu-item index="/LandlordTransactionRecord">交易记录</el-menu-item>
</el-sub-menu>
<el-menu-item index="/LandlordSelfInfo">个人信息</el-menu-item>
</el-menu>
</el-header>
<el-main>
<!-- 卡片容器 -->
<el-card id="personal-info-card" style="margin: 15px; min-height: calc(100vh - 111px);">
<div style="display: flex; justify-content: center;">
<div style="width: 600px; margin-left: 30px; position: relative">
<!-- 用户信息展示 -->
<div style="margin: 20px 0;">
<h3 class="personal-info-title" style="margin-bottom: 30px; color: #333;font-size: 30px;">👤 个人信息</h3>
<div style="display: flex; flex-wrap: wrap; gap: 20px;">
<!-- 房东ID -->
<el-card shadow="hover" style="width: calc(50% - 10px); padding: 15px; background-color: #f9f9f9; border: 1px solid #ebebeb; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1), 0 6px 20px rgba(0, 0, 0, 0.1); transition: all 0.3s ease; user-select: none;">
<div style="display: flex; align-items: center;">
<i class="el-icon-user" style="margin-right: 10px; color: #409EFF;"></i>
<div style="position: relative; flex: 1;">
<strong>房东ID</strong>
<span style="margin-left: 10px; display: block;">{{ landlordId }}</span>
<el-icon style="position: absolute; right: 0; top: 0;">
<User />
</el-icon>
</div>
</div>
</el-card>
<!-- 用户名 -->
<el-card shadow="hover" style="width: calc(50% - 10px); padding: 15px; background-color: #f9f9f9; border: 1px solid #ebebeb; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1), 0 6px 20px rgba(0, 0, 0, 0.1); transition: all 0.3s ease; user-select: none;">
<div style="display: flex; align-items: center;">
<i class="el-icon-document" style="margin-right: 10px; color: #409EFF;"></i>
<div style="position: relative; flex: 1;">
<strong>用户名</strong>
<span style="margin-left: 10px; display: block;">{{ username }}</span>
<el-icon style="position: absolute; right: 0; top: 0;">
<UserFilled />
</el-icon>
</div>
</div>
</el-card>
<!-- 手机号 -->
<el-card shadow="hover" style="width: calc(50% - 10px); padding: 15px; background-color: #f9f9f9; border: 1px solid #ebebeb; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1), 0 6px 20px rgba(0, 0, 0, 0.1); transition: all 0.3s ease; user-select: none;">
<div style="display: flex; align-items: center;">
<i class="el-icon-phone" style="margin-right: 10px; color: #409EFF;"></i>
<div style="position: relative; flex: 1;">
<strong>手机号</strong>
<span style="margin-left: 10px; display: block;">{{ phone }}</span>
<el-icon style="position: absolute; right: 0; top: 0;">
<Iphone />
</el-icon>
</div>
</div>
</el-card>
<!-- 邮箱 -->
<el-card shadow="hover" style="width: calc(50% - 10px); padding: 15px; background-color: #f9f9f9; border: 1px solid #ebebeb; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1), 0 6px 20px rgba(0, 0, 0, 0.1); transition: all 0.3s ease; user-select: none;">
<div style="display: flex; align-items: center;">
<i class="el-icon-message" style="margin-right: 10px; color: #409EFF;"></i>
<div style="position: relative; flex: 1;">
<strong>邮箱</strong>
<span style="margin-left: 10px; display: block;">{{ email }}</span>
<el-icon style="position: absolute; right: 0; top: 0;">
<Message />
</el-icon>
</div>
</div>
</el-card>
</div>
</div>
<!-- 修改按钮 -->
<el-tooltip content="修改信息" placement="bottom">
<el-button
icon="Edit"
size="large"
type="primary"
style="
margin-top: 30px;
width: 80px;
transition: transform 0.2s ease;
"
@click="Edit"
@mouseenter.native="e => e.target.style.transform = 'scale(1.1)'"
@mouseleave.native="e => e.target.style.transform = 'scale(1)'"
>
</el-button>
</el-tooltip>
</div>
</div>
</el-card>
<!-- 修改信息弹窗 -->
<el-dialog v-model="dialogVisible" title="操作" width="30%" @close="resetForm">
<el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
<el-form-item label="房东ID" prop="landlordId">
<el-input v-model="form.landlordId" disabled style="width: 80%"></el-input>
</el-form-item>
<el-form-item label="用户名" prop="username">
<el-input v-model="form.username" style="width: 80%"></el-input>
</el-form-item>
<el-form-item label="密码" prop="password">
<el-input v-model="form.password" :disabled="disabled" show-password style="width: 80%"></el-input>
<el-tooltip content="修改密码" placement="right">
<el-icon size="large" style="margin-left: 5px; cursor: pointer" @click="EditPass">
<edit />
</el-icon>
</el-tooltip>
</el-form-item>
<!-- <el-form-item label="确认密码" prop="checkPass" :style="display">
<el-input v-model="form.checkPass" show-password style="width: 80%"></el-input>
</el-form-item> -->
<el-form-item label="手机号" prop="phone">
<el-input v-model.number="form.phone" style="width: 80%"></el-input>
</el-form-item>
<el-form-item label="邮箱地址" prop="email">
<el-input v-model="form.email" style="width: 80%"></el-input>
</el-form-item>
</el-form>
<template #footer>
<span class="dialog-footer">
<el-button @click="cancel">取 消</el-button>
<el-button type="primary" @click="save">确 定</el-button>
</span>
</template>
</el-dialog>
</el-main>
</el-container>
</div>
</div>
</template>
<script>
import request from "@/axios/request";
const {ElMessage} = require('element-plus');
export default {
data() {
return {
loading: true,
landlordId: '',
username: '',
password: '',
phone: '',
email: '',
dialogVisible: false,
form: {
landlordId: '',
username: '',
password: '',
checkPass: '',
phone: '',
email: ''
},
rules: {
// 验证规则(可根据实际需求扩展)
username: [
{ required: true, message: '请输入用户名', trigger: 'blur' },
{ min: 2, max: 20, message: '长度在2到20个字符之间', trigger: 'blur' }
],
password: [
{ required: true, message: '请输入密码', trigger: 'blur' },
{ min: 6, message: '密码至少6位', trigger: 'blur' }
],
checkPass: [
{ validator: (rule, value, callback) => {
if (value !== this.form.password) {
callback(new Error('两次输入密码不一致'));
} else {
callback();
}
}, trigger: 'blur' }
],
phone: [
{ required: true, message: '请输入手机号', trigger: 'blur' },
{ pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
],
email: [
{ required: true, message: '请输入邮箱地址', trigger: 'blur' },
{ type: 'email', message: '邮箱格式不正确', trigger: ['blur', 'change'] }
]
},
display: { display: 'none' },
disabled: true
};
},
mounted() {
this.fetchUserInfo();
},
methods: {
async fetchUserInfo() {
let token = JSON.parse(window.sessionStorage.getItem('userInfo'));
const landlordId = token.landlordId;
const res = await request.get(`/landlord/findById/${landlordId}`);
if (res.code === 200) {
token=res.data;
} else {
ElMessage.error("获取用户信息失败");
}
console.log(token);
if(!token) {
ElMessage.error("获取用户信息失败");
console.log("获取用户信息失败");
return;
}
this.landlordId = token.landlordId;
this.username = token.username;
this.password = token.password;
this.phone = token.phone;
this.email = token.email;
console.log(token);
},
Edit() {
this.form.landlordId = this.landlordId;
this.form.username = this.username;
this.form.password = this.password;
this.form.phone = this.phone;
this.form.email = this.email;
this.dialogVisible = true;
},
cancel() {
this.resetForm();
this.dialogVisible = false;
},
save() {
console.log('提交数据:', this.form);
fetch('/landlord/updateById', {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(this.form)
})
.then(res => res.json())
.then(data => {
if (data.success) {
this.fetchUserInfo(); // 刷新页面数据
} else {
alert('更新失败,请重试');
}
})
.catch(err => {
console.error('请求出错:', err);
});
this.resetForm();
this.dialogVisible = false;
},
EditPass() {
this.disabled = false;
this.display.display = 'block';
},
resetForm() {
this.form.username = this.username;
this.form.password = this.password;
this.form.checkPass = '';
this.form.phone = this.phone;
this.form.email = this.email;
this.disabled = true;
this.display.display = 'none';
if (this.$refs.formRef && this.$refs.formRef.resetFields) {
this.$refs.formRef.resetFields();
}
},
SignOut() {
sessionStorage.clear();
ElMessage({
message: '用户退出登录',
type: 'success',
});
this.$router.replace({ path: '/Login' });
},
}
};
</script>
<style scoped>
.background {
background-color: whitesmoke;
height: 100vh;
}
.header_background {
background-color: #1b4989;
height: 6vh;
}
.sub_header_background {
background-color: #545c64;
height: 7vh;
}
.right-info {
width: 100px;
position: absolute;
right: 2%;
top: 0.7%
}
.right-info:hover {
cursor: pointer;
}
.el-carousel__item h3 {
color: #475669;
opacity: 0.75;
line-height: 200px;
margin: 0;
text-align: center;
}
.el-carousel__item:nth-child(2n) {
background-color: #99a9bf;
}
.el-carousel__item:nth-child(2n + 1) {
background-color: #d3dce6;
}
.el-card:hover {
transform: translateY(-5px);
box-shadow: 0 10px 15px rgba(0, 0, 0, 0.2), 0 6px 20px rgba(0, 0, 0, 0.2);
border-color: #409EFF;
}
</style>
|
2301_79970562/student_union_frontend
|
src/views/LandlordSelfInfo.vue
|
Vue
|
unknown
| 15,430
|
<template>
<div class="background">
<div class="common-layout">
<el-container>
<el-header class="header_background">
<div style="position: absolute; top: 0.1%; left: 2%;">
<img alt="" src="@/assets/logo1.png" style="width: 40px;">
</div>
<div style="position: absolute; top: 1.5%; left: 38%;">
<span style="font-size: 15px; font-weight: bold; color: whitesmoke">
您好,房东 {{ username }} !欢迎进入房屋租赁平台!
</span>
</div>
<div class="right-info">
<el-button @click="SignOut" style="margin-right: 10px;">
<el-icon :size="18" style="margin-right: 5px;">
<avatar />
</el-icon>
退出登录
</el-button>
</div>
</el-header>
<el-header class="sub_header_background">
<el-menu
:default-active="activeIndex"
router
class="el-menu-demo"
mode="horizontal"
background-color="#545c64"
text-color="whitesmoke"
active-text-color="white"
style="height: 102%;"
>
<el-menu-item index="/LandlordHome">首页</el-menu-item>
<el-menu-item index="/LandlordHouse">我的房源</el-menu-item>
<el-sub-menu index="transaction">
<template #title>交易管理</template>
<el-menu-item index="/ApplicationAudition">租客申请审核</el-menu-item>
<el-menu-item index="/LandlordTransactionRecord">交易记录</el-menu-item>
</el-sub-menu>
<el-menu-item index="/LandlordSelfInfo">个人信息</el-menu-item>
</el-menu>
</el-header>
<el-main>
<div style="display: flex; font-weight: bold; font-family: Microsoft YaHei; font-size: 20px; margin-top: 0%;">
历史交易记录
<div class="line" style="margin-left: 1.5%; margin-top: 1%;"></div>
</div>
<div style="display: flex; flex-wrap: wrap; gap: 20px;">
<el-card shadow="hover" style="margin-top: 2%; width: calc(100% - 10px); padding: 15px; background-color: #f9f9f9; border: 1px solid #ebebeb; box-shadow: 0 10px 15px rgba(0, 0, 0, 0.2), 0 6px 20px rgba(0, 0, 0, 0.2); transition: all 0.3s ease; ">
<el-table v-loading="loading" :data="tableTransactionData" border max-height="705" style="width: 100%">
<el-table-column label="交易单号" prop="recordId"/>
<el-table-column label="房屋编号" prop="houseId"/>
<el-table-column label="房屋名称" prop="houseId" :formatter="(row) => getHouseTitle(row.houseId)"/>
<el-table-column label="租客编号" prop="tenantId"/>
<el-table-column label="租客用户名" prop="tenantId" :formatter="(row) => getTenantUsername(row.tenantId)"/>
<el-table-column label="租客电话号码" prop="tenantId" :formatter="(row) => getTenantPhone(row.tenantId)"/>
<el-table-column label="租客邮箱" prop="tenantId" :formatter="(row) => getTenantEmail(row.tenantId)"/>
<el-table-column label="交易时间" prop="recordTime":formatter="(row) => formatTime(row.recordTime)"/>
</el-table>
</el-card>
</div>
<div style="margin: 30px 0;">
<el-pagination
v-model:currentPage="currentPage"
:page-size="pageSize"
:page-sizes="[5, 10, 15]"
:total="transaction_total"
layout="total, sizes, prev, pager, next, jumper"
@size-change="handleSizeChange"
@current-change="handleCurrentChange"></el-pagination>
</div>
</el-main>
</el-container>
</div>
</div>
</template>
<script src="@/assets/js/LandlordTransactionRecord.js"></script>
<style scoped>
.background {
background-color: whitesmoke;
height: 100vh;
}
.header_background {
background-color: #1b4989;
height: 6vh;
}
.sub_header_background {
background-color: #545c64;
height: 7vh;
}
.right-info {
width: 100px;
position: absolute;
right: 2%;
top: 0.7%
}
.right-info:hover {
cursor: pointer;
}
.el-carousel__item h3 {
color: #475669;
opacity: 0.75;
line-height: 200px;
margin: 0;
text-align: center;
}
.el-carousel__item:nth-child(2n) {
background-color: #99a9bf;
}
.el-carousel__item:nth-child(2n + 1) {
background-color: #d3dce6;
}
.line{
background: url(https://www.upc.edu.cn/ximages/tit1.png) center repeat-x;
height: 0.4rem;
flex: 1;
background-size: auto;
margin: 0.16rem;
}
</style>
|
2301_79970562/student_union_frontend
|
src/views/LandlordTransactionRecord.vue
|
Vue
|
unknown
| 5,450
|