package com.java1234.controller.admin;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.java1234.entity.*;
import com.java1234.service.IProductService;
import com.java1234.util.DateUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 管理员-商品Controller控制器
* @author java1234_小锋
* @site www.java1234.com
* @company 南通小锋网络科技有限公司
* @create 2022-05-21 21:07
*/
@RestController
@RequestMapping("/admin/product")
public class AdminProductController {
@Autowired
private IProductService productService;
@Value("${productImagesFilePath}")
private String productImagesFilePath;
@Value("${swiperImagesFilePath}")
private String swiperImagesFilePath;
/**
* 根据条件分页查询
* @param pageBean
* @return
*/
@RequestMapping("/list")
public R list(@RequestBody PageBean pageBean){
System.out.println(pageBean);
Map<String,Object> map=new HashMap<>();
map.put("name",pageBean.getQuery().trim());
map.put("start",pageBean.getStart());
map.put("pageSize",pageBean.getPageSize());
List<Product> productList=productService.list(map);
Long total=productService.getTotal(map);
Map<String,Object> resultMap=new HashMap<>();
resultMap.put("productList",productList);
resultMap.put("total",total);
return R.ok(resultMap);
}
/**
* 更新热门状态
* @param id
* @param hot
* @return
*/
@GetMapping("/updateHot/{id}/state/{hot}")
public R updateHot(@PathVariable(value = "id")Integer id,@PathVariable(value = "hot")boolean hot){
Product product = productService.getById(id);
product.setHot(hot);
if(hot){
product.setHotDateTime(new Date());
}else{
product.setHotDateTime(null);
}
productService.saveOrUpdate(product);
return R.ok();
}
/**
* 更新swiper状态
* @param id
* @param swiper
* @return
*/
@GetMapping("/updateSwiper/{id}/state/{swiper}")
public R updateSwiper(@PathVariable(value = "id")Integer id,@PathVariable(value = "swiper")boolean swiper){
Product product = productService.getById(id);
product.setSwiper(swiper);
productService.saveOrUpdate(product);
return R.ok();
}
/**
* 删除
* @param id
* @return
*/
@GetMapping("/delete/{id}")
public R delete(@PathVariable(value = "id")Integer id){
productService.removeById(id);
return R.ok();
}
/**
* 上传商品大类图片
* @param file
* @return
* @throws Exception
*/
@RequestMapping("/uploadImage")
public Map<String,Object> uploadImage(MultipartFile file)throws Exception{
Map<String,Object> resultMap=new HashMap<>();
if(!file.isEmpty()){
// 获取文件名
String originalFilename = file.getOriginalFilename();
String suffixName=originalFilename.substring(originalFilename.lastIndexOf("."));
String newFileName=DateUtil.getCurrentDateStr()+suffixName;
FileUtils.copyInputStreamToFile(file.getInputStream(),new File(productImagesFilePath+newFileName));
resultMap.put("code",0);
resultMap.put("msg","上传成功");
Map<String,Object> dataMap=new HashMap<>();
dataMap.put("title",newFileName);
dataMap.put("src","/image/product/"+newFileName);
resultMap.put("data",dataMap);
}
return resultMap;
}
/**
* 上传swiper幻灯图片
* @param file
* @return
* @throws Exception
*/
@RequestMapping("/uploadSwiperImage")
public Map<String,Object> uploadSwiperImage(MultipartFile file)throws Exception{
Map<String,Object> resultMap=new HashMap<>();
if(!file.isEmpty()){
// 获取文件名
String originalFilename = file.getOriginalFilename();
String suffixName=originalFilename.substring(originalFilename.lastIndexOf("."));
String newFileName=DateUtil.getCurrentDateStr()+suffixName;
FileUtils.copyInputStreamToFile(file.getInputStream(),new File(swiperImagesFilePath+newFileName));
resultMap.put("code",0);
resultMap.put("msg","上传成功");
Map<String,Object> dataMap=new HashMap<>();
dataMap.put("title",newFileName);
dataMap.put("src","/image/swiper/"+newFileName);
resultMap.put("data",dataMap);
}
return resultMap;
}
/**
* 添加或者修改
* @param product
* @return
*/
@RequestMapping("/save")
public R save(@RequestBody Product product){
if(product.getId()==null || product.getId()==-1){
productService.add(product);
}else{
productService.update(product);
}
return R.ok();
}
/**
* 根据id查询
* @param id
* @return
*/
@GetMapping("/{id}")
public R findById(@PathVariable(value = "id")Integer id){
Product product = productService.findById(id);
Map<String,Object> map=new HashMap<>();
map.put("product",product);
return R.ok(map);
}
}
<template>
<el-dialog
model-value="dialogVisible"
:title="dialogTitle"
width="50%"
@close="handleClose"
>
<el-form
ref="formRef"
:model="form"
:rules="rules"
label-width="100px"
>
<el-form-item label="商品名称" prop="name">
<el-input v-model="form.name" style="width: 400px"/>
</el-form-item>
<el-form-item label="商品价格" prop="price">
<el-input v-model="form.price" style="width: 100px"/>
</el-form-item>
<el-form-item label="商品库存" prop="stock">
<el-input v-model="form.stock" style="width: 100px"/>
</el-form-item>
<el-form-item label="商品类别">
<el-select v-model="bigTypeId" class="m-2" placeholder="请选择商品大类..." @change="handleBigTypeChange">
<el-option
v-for="item in bigTypeSelectOptions"
:key="item.id"
:label="item.name"
:value="item.id"></el-option>
</el-select>
<el-select v-model="form.type.id" class="m-2" placeholder="请选择商品小类..." >
<el-option
v-for="item in smallTypeSelectOptions"
:key="item.id"
:label="item.name"
:value="item.id"></el-option>
</el-select>
</el-form-item>
<el-form-item label="商品描述" prop="description">
<el-input v-model="form.description" type="textarea" :rows="4"/>
</el-form-item>
<el-form-item label="商品介绍">
</el-form-item>
<QuillEditor
v-model:content="form.productIntroImgs"
contentType="html"
toolbar="full"
theme="snow"
style="height:200px"
/>
<el-form-item label="商品参数">
</el-form-item>
<QuillEditor
v-model:content="form.productParaImgs"
contentType="html"
toolbar="full"
theme="snow"
style="height:200px"
/>
</el-form>
<template
<span class="dialog-footer">
<el-button @click="handleClose">取消</el-button>
<el-button type="primary" @click="handleConfirm">确认</el-button>
</span>
</template>
</el-dialog>
</template>
<script setup>
import {defineEmits, defineProps, ref, watch} from "vue";
import axios from "@/util/axios";
import { ElMessage } from 'element-plus'
const props=defineProps(
{
id:{
type:Number,
default:-1,
required:true
},
dialogTitle:{
type:String,
default:'',
required:true
},
dialogVisible:{
type:Boolean,
default:false,
required:true
}
}
)
const form=ref({
id:-1,
name:'',
price:null,
stock:null,
type:{
id:''
},
description:'',
productIntroImgs:'',
productParaImgs:''
})
const bigTypeId=ref("")
const bigTypeSelectOptions=ref([]);
const smallTypeSelectOptions=ref([]);
const initBigTypeSelectList=async()=>{
const res=await axios.get("admin/bigType/listAll");
bigTypeSelectOptions.value=res.data.bigTypeList;
}
const initSmallTypeSelectList=async(bigTypeId)=>{
form.value.type.id=""
const res=await axios.get("admin/smallType/listAll/"+bigTypeId);
smallTypeSelectOptions.value=res.data.smallTypeList;
}
initBigTypeSelectList();
const rules=ref({
name:[
{
required: true,
message: '请输入商品小类名称!',
}
],
price:[
{ required: true, message: '请输入商品价格!' },
{ type: 'number', message: '商品价格是数值类型!',transform: (value) => Number(value) },
],
stock:[
{ required: true, message: '请输入商品库存!' },
{ type: 'number', message: '商品库存是数值类型!',transform: (value) => Number(value) },
],
description:[
{
required: true,
message: '请输入商品小类描述!',
},
],
})
const formRef=ref(null)
const initFormData=async(id)=>{
const res=await axios.get("admin/product/"+id);
bigTypeId.value=res.data.product.type.bigType.id;
initSmallTypeSelectList(bigTypeId.value);
form.value=res.data.product;
}
const handleBigTypeChange=(bigTypeId)=>{
console.log("bigTypeId="+bigTypeId);
initSmallTypeSelectList(bigTypeId)
}
watch(
()=>props.dialogVisible,
()=>{
let id=props.id;
if(id!=-1){
initFormData(id)
}else{
form.value={
id:-1,
name:'',
price:null,
stock:null,
type:{
id:''
},
description:''
}
}
}
)
const emits=defineEmits(['update:modelValue','initProductList'])
const handleClose=()=>{
emits('update:modelValue',false)
}
const handleConfirm=()=>{
formRef.value.validate(async(valid)=>{
if(valid){
if(form.value.type.id==""){
ElMessage.error("请选择商品类别");
return;
}
let result=await axios.post("admin/product/save",form.value);
let data=result.data;
if(data.code==0){
ElMessage.success("执行成功!")
formRef.value.resetFields();
emits("initProductList")
handleClose();
}else{
ElMessage.error(data.msg);
}
}else{
console.log("fail")
}
})
}
</script>
<style scoped>
</style>
<template>
<el-card>
<el-row :gutter="20" class="header">
<el-col :span="7">
<el-input placeholder="请输入商品名称..." v-model="queryForm.query" clearable></el-input>
</el-col>
<el-button type="primary" :icon="Search" @click="initProductList">搜索</el-button>
<el-button type="primary" :icon="DocumentAdd" @click="handleDialogValue()">添加商品</el-button>
</el-row>
<el-table :data="tableData" stripe style="width: 100%">
<el-table-column prop="name" label="商品名称" width="200" fixed/>
<el-table-column prop="image" label="商品图片" width="150" align="center">
<template v-slot="scope">
<img :src="getServerUrl()+'/image/product/'+scope.row.proPic" width="80" height="80"/>
</template>
</el-table-column>
<el-table-column prop="price" label="商品价格" width="100" />
<el-table-column prop="stock" label="商品库存" width="100" />
<el-table-column prop="type" label="商品类别" width="200" :formatter="typeNameFormatter"/>
<el-table-column prop="hot" label="热卖?" width="100" align="center">
<template v-slot="{row}">
<el-switch v-model="row.hot" @change="hotChangeHandle(row)"></el-switch>
</template>
</el-table-column>
<el-table-column prop="swiper" label="首页幻灯?" width="100" align="center">
<template v-slot="{row}">
<el-switch v-model="row.swiper" @change="swiperChangeHandle(row)"></el-switch>
</template>
</el-table-column>
<el-table-column prop="stock" label="商品库存" width="100" />
<el-table-column prop="swiperPic" label="幻灯图片" width="150" align="center">
<template v-slot="scope">
<img :src="getServerUrl()+'/image/swiper/'+scope.row.swiperPic" width="150" height="75"/>
</template>
</el-table-column>
<el-table-column prop="swiperSort" label="幻灯排序" width="150" align="center"/>
<el-table-column prop="description" label="商品描述" width="400"/>
<el-table-column prop="action" label="操作" width="500" fixed="right">
<template v-slot="scope">
<el-button type="success" @click="handleImageDialogValue(scope.row)">更换图片</el-button>
<el-button type="primary" @click="handleSwiperImageDialogValue(scope.row)">幻灯设置</el-button>
<el-button type="primary" :icon="Edit" @click="handleDialogValue(scope.row.id)"/>
<el-button type="danger" :icon="Delete" @click="handleDelete(scope.row.id)"/>
<el-button type="primary" @click="handleProductSwiperImageDialogValue(scope.row)">轮播图设置</el-button>
</template>
</el-table-column>
</el-table>
<el-pagination
v-model:currentPage="queryForm.pageNum"
v-model:page-size="queryForm.pageSize"
:page-sizes="[10, 20, 30, 40,50]"
layout="total, sizes, prev, pager, next, jumper"
:total="total"
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
/>
</el-card>
<Dialog v-model="dialogVisible" :dialogVisible="dialogVisible" :id="id" :dialogTitle="dialogTitle" @initProductList="initProductList"></Dialog>
<imageDialog v-model="imageDialogVisible" :imageDialogValue="imageDialogValue" @initProductList="initProductList"></imageDialog>
<SwiperImageDialog v-model="swiperImageDialogVisible" :imageDialogValue="imageDialogValue" @initProductList="initProductList"></SwiperImageDialog>
<ProductSwiperImageDialog v-model="productSwiperImageDialogVisible" :imageDialogValue="imageDialogValue" @initProductList="initProductList"></ProductSwiperImageDialog>
</template>
<script setup>
import { Search ,Delete,DocumentAdd ,Edit} from '@element-plus/icons-vue'
import { ref } from 'vue'
import axios,{ getServerUrl } from "@/util/axios";
import { ElMessage, ElMessageBox } from 'element-plus'
import Dialog from './components/dialog'
import ImageDialog from './components/imageDialog'
import SwiperImageDialog from './components/swiperImageDialog'
import ProductSwiperImageDialog from './components/productSwiperImageDialog'
const queryForm=ref({
query:'',
pageNum:1,
pageSize:10
})
const total=ref(0)
const tableData = ref([])
const dialogVisible=ref(false)
const dialogTitle=ref('')
const imageDialogVisible=ref(false)
const swiperImageDialogVisible=ref(false)
const productSwiperImageDialogVisible=ref(false)
const imageDialogValue=ref({})
const id=ref(-1)
const initProductList=async()=>{
const res=await axios.post("admin/product/list",queryForm.value)
tableData.value=res.data.productList;
total.value=res.data.total;
}
initProductList();
const handleImageDialogValue=(row)=>{
imageDialogVisible.value=true
imageDialogValue.value=JSON.parse(JSON.stringify(row))
}
const handleSwiperImageDialogValue=(row)=>{
swiperImageDialogVisible.value=true
imageDialogValue.value=JSON.parse(JSON.stringify(row))
}
const handleProductSwiperImageDialogValue=(row)=>{
productSwiperImageDialogVisible.value=true
imageDialogValue.value=JSON.parse(JSON.stringify(row))
}
const handleDialogValue=(productId)=>{
if(productId){
id.value=productId;
dialogTitle.value="商品修改"
}else{
id.value=-1;
dialogTitle.value="商品添加"
}
dialogVisible.value=true
}
const handleSizeChange=(pageSize)=>{
queryForm.value.pageNum=1;
queryForm.value.pageSize=pageSize;
initProductList();
}
const handleCurrentChange=(pageNum)=>{
queryForm.value.pageNum=pageNum;
initProductList();
}
const typeNameFormatter=(row)=>{
return row.type.name;
}
const handleDelete=(id,status)=>{
ElMessageBox.confirm(
'您确定要删除这条记录吗?',
'系统提示',
{
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning',
}
)
.then(async() => {
let res=await axios.get('admin/product/delete/'+id)
if(res.data.code==0){
ElMessage({
type: 'success',
message: '删除成功',
})
initProductList();
}else{
ElMessage({
type: 'error',
message: res.data.msg,
})
}
})
.catch(() => {
})
}
const hotChangeHandle=async (row)=>{
let res=await axios.get("admin/product/updateHot/"+row.id+"/state/"+row.hot);
if(res.data.code==0){
ElMessage({
type: 'success',
message: '执行成功!'
})
}else{
ElMessage({
type: 'error',
message: res.data.msg,
})
initProductList();
}
}
const swiperChangeHandle=async (row)=>{
let res=await axios.get("admin/product/updateSwiper/"+row.id+"/state/"+row.swiper);
if(res.data.code==0){
ElMessage({
type: 'success',
message: '执行成功!'
})
}else{
ElMessage({
type: 'error',
message: res.data.msg,
})
initProductList();
}
}
</script>
<style lang="scss" scoped>
.header{
padding-bottom: 16px;
box-sizing: border-box;
}
.el-pagination{
padding-top: 15px;
box-sizing: border-box;
}
</style>