MenuManagement.vue 19.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
<template>
  <div class="menuManagement">
    <a-button style="margin-bottom: 20px" type="primary" @click="showModal()">添加菜品</a-button>
    <div style="display: flex">
      <div class="productionMenu">
        <div class="productionMenuTitle">菜品所有分类</div>
        <div class="productionMenuList">
          <div :class="item.productCategoryId === menuId ? 'menuItem menuItemAction' : 'menuItem'" v-show="item.isDisplay === 'DISPLAY'" v-for="item in dataSource" :key="item.productCategoryId" @click="changeMenuItem(item.productCategoryId)">
            {{item.productCategoryName}}
          </div>
        </div>
        <div class="productionMenuTitle">以下分类已隐藏</div>
        <div class="productionMenuList">
          <div :class="item.productCategoryId === menuId ? 'menuItem menuItemAction' : 'menuItem'" v-show="item.isDisplay === 'HIDDEN'" v-for="item in dataSource" :key="item.productCategoryId" @click="changeMenuItem(item.productCategoryId)">
            {{item.productCategoryName}}
          </div>
        </div>
      </div>
      <div style="flex: 1;padding-left: 20px">
        <a-table :columns="columns" :dataSource="tableSource" rowKey="productId" :pagination="pagination">
          <span slot="productIcon" slot-scope="productIcon">
            <img style="width: 100px" :src="productIcon" alt="" />
          </span>
          <span slot="productName"></span>
          <span slot="productPrice" slot-scope="productPrice">
            {{ productPrice.toFixed(2) }}
          </span>
          <span slot="productStatus" slot-scope="productStatus">
            <a-badge v-if="productStatus === 'UP'" status="success" text="已上架" />
            <a-badge v-else-if="productStatus === 'DOWN'" status="error" text="已下架" />
          </span>
          <span slot="action" slot-scope="text, record, index">
            <a style="margin-right: 8px" href="javascript:;" @click="showModal('change', record, index)">修改</a>
            <a href="javascript:;" @click="showConfirm(record)">{{record.productStatus === 'UP' ? '下架' : '上架'}}</a>
          </span>
        </a-table>
      </div>
    </div>
    <a-modal
      title="增加分类"
      :visible="visible"
      @ok="saveProduct"
      :confirmLoading="confirmLoading"
      @cancel="handleCancel"
    >
      <div class="item">
        <label>菜品名称:</label><a-input v-model="addProduct.productName" placeholder="请输入分品名称"/>
      </div>
      <div class="item">
        <label>选择分类:</label>
        <a-select placeholder="请选择" :allowClear="true" style="width: 220px" v-model="addProduct.productCategoryId" @change="selectproductCategory">
          <a-select-option v-for="(item, index) in dataSource" :key="index" :value="item.productCategoryId">{{ item.productCategoryName }}</a-select-option>
        </a-select>
      </div>
      <div class="item">
        <label>设置价格:</label><a-input v-model="addProduct.productPrice" placeholder="请输入菜品单价(元/份))"/>
      </div>
      <div class="item">
        <label>排序值:</label><a-input v-model="addProduct.sort" placeholder="排序值为正整数"/>
      </div>
      <div class="item">
        <label>上传图片:</label>
        <div style="width:220px">
          <a-upload
            name="avatar"
            listType="picture-card"
            class="avatar-uploader"
            :fileList="fileList"
            :showUploadList="false"
            action=""
            :beforeUpload="beforeUpload"
            :customRequest="customRequest"
          >
            <img style="width: 120px" v-if="imageUrl" :src="imageUrl" alt="avatar" />
            <div v-else>
                <a-icon :type="loading ? 'loading' : 'plus'" />
                <div class="ant-upload-text">Upload</div>
            </div>
          </a-upload>
        </div>
      </div>
      <div class="item">
        <label></label><div>*请上传小于5M、16:9像素的PNG、JPG横图</div>
      </div>
    </a-modal>
  </div>
</template>

<script>
import { $http } from './../../../api/axios.js'
import axios from 'axios'
function getBase64 (img, callback) {
  const reader = new FileReader()
  reader.addEventListener('load', () => callback(reader.result))
  reader.readAsDataURL(img)
}
function dataURLtoFile (dataurl, filename) {
  var arr = dataurl.split(',')
  var mime = arr[0].match(/:(.*?);/)[1]
  var bstr = atob(arr[1])
  var n = bstr.length
  var u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], filename, { type: mime })
}
function changeFileToBaseURL (file, fn) {
// 创建读取文件对象
  var fileReader = new FileReader()
  // 如果file没定义返回null
  if (file === undefined) return fn(null)
  // 读取file文件,得到的结果为base64位
  fileReader.readAsDataURL(file)
  fileReader.onload = function () {
    // 把读取到的base64
    var imgBase64Data = this.result
    fn(imgBase64Data)
  }
}
function pressImg (param) {
  // 如果没有回调函数就不执行
  if (param && param.succ) {
    // 如果file没定义返回null
    if (param.file === undefined) return param.succ(null)
    // 给参数附初始值
    param.targetSize = param.hasOwnProperty('targetSize') ? param.targetSize : -1
    param.width = param.hasOwnProperty('width') ? param.width : -1
    param.fileName = param.hasOwnProperty('fileName') ? param.fileName : 'image'
    param.quality = param.hasOwnProperty('quality') ? param.quality : 0.92
    var _this = this
    // 得到文件类型
    var fileType = param.file.type
    // console.log(fileType) //image/jpeg
    if (fileType.indexOf('image') === -1) {
      console.log('请选择图片文件^_^')
      return param.succ(null)
    }
    // 如果当前size比目标size小,直接输出
    var size = param.file.size
    if (param.targetSize > size) {
      return param.succ(param.file)
    }
    // 读取file文件,得到的结果为base64位
    changeFileToBaseURL(param.file, function (base64) {
      if (base64) {
        var image = new Image()
        image.src = base64
        image.onload = function () {
          // 获得长宽比例
          var scale = this.width / this.height
          // console.log(scale);
          // 创建一个canvas
          var canvas = document.createElement('canvas')
          // 获取上下文
          var context = canvas.getContext('2d')
          // 获取压缩后的图片宽度,如果width为-1,默认原图宽度
          canvas.width = param.width === -1 ? this.width : param.width
          // 获取压缩后的图片高度,如果width为-1,默认原图高度
          canvas.height = param.width === -1 ? this.height : parseInt(param.width / scale)
          // 把图片绘制到canvas上面
          context.drawImage(image, 0, 0, canvas.width, canvas.height)
          // 压缩图片,获取到新的base64Url
          var newImageData = canvas.toDataURL(fileType, param.quality)
          // 将base64转化成文件流
          var resultFile = dataURLtoFile(newImageData, param.fileName)
          // 判断如果targetSize有限制且压缩后的图片大小比目标大小大,就弹出错误
          if (param.targetSize !== -1 && param.targetSize < resultFile.size) {
            console.log('图片上传尺寸太大,请重新上传^_^')
            param.succ(null)
          } else {
            // 返回文件流
            param.succ(resultFile)
          }
        }
      }
    })
  }
}
export default {
  name: 'menuManagement',
  data () {
    return {
      dataSource: [],
      tableSource: [],
      addProduct: {},
      visible: false,
      loading: false,
      imageUrl: '',
      confirmLoading: false,
      menuId: '',
      columns: [{
        title: '产品图',
        dataIndex: 'productIcon',
        scopedSlots: { customRender: 'productIcon' }
      }, {
        title: '菜名',
        dataIndex: 'productName'
      }, {
        title: '价格(元)',
        dataIndex: 'productPrice',
        scopedSlots: { customRender: 'productPrice' }
      }, {
        title: '排序值',
        dataIndex: 'sort'
      }, {
        title: '状态',
        dataIndex: 'productStatus',
        scopedSlots: { customRender: 'productStatus' }
      }, {
        title: '操作',
        key: 'action',
        scopedSlots: { customRender: 'action' }
      }],
      pagination: {
        current: 1,
        defaultCurrent: 1,
        defaultPageSize: 1000,
        hideOnSinglePage: true,
        total: 0
      },
      changeSource: {},
      changeType: '',
      fileList: [],
      changeSourceIndex: ''
    }
  },
  created: function () {
    this.getProductCategoryList('action')
  },
  methods: {
    getProductCategoryList (type) {
      let getProductCategoryListData = {
      }
      if (type === 'action') {
        $http.post(`/mingpay/v1/isv/product/list_product_category`, getProductCategoryListData).then((res) => {
          if (res.data.resultCode === 0) {
            this.dataSource = res.data.data
            this.menuId = this.dataSource[0].productCategoryId
            let listProductData = {
              productCategoryId: this.menuId
            }
            $http.post(`/mingpay/v1/isv/product/list_product`, listProductData).then((res) => {
              if (res.data.resultCode === 0) {
                this.tableSource = res.data.data
              }
            })
          }
        })
      } else {
        let listProductData = {
          productCategoryId: this.menuId
        }
        $http.post(`/mingpay/v1/isv/product/list_product`, listProductData).then((res) => {
          if (res.data.resultCode === 0) {
            this.tableSource = res.data.data
          }
        })
      }
    },
    selectproductCategory (value) {
      this.addProduct.categoryId = value
    },
    showConfirm (record) {
      let that = this
      let title
      let content
      if (record.productStatus === 'UP') {
        title = '确认要下架该菜品吗?'
        content = '下架后该菜品设备端不可见'
      } else {
        title = '确认要上架该菜品吗?'
        content = '上架后该菜品在设备端可正常使用'
      }
      this.$confirm({
        title: title,
        content: content,
        onOk () {
          that.changeData(record)
        },
        onCancel () {}
      })
    },
    changeData (record) {
      let saveProductCategoryData
      if (record.productStatus === 'UP') {
        saveProductCategoryData = {
          productId: record.productId,
          productStatus: 'DOWN'
        }
      } else {
        saveProductCategoryData = {
          productId: record.productId,
          productStatus: 'UP'
        }
      }
      $http.post(`/mingpay/v1/isv/product/update_product`, saveProductCategoryData).then((res) => {
        if (res.data.resultCode === 0) {
          this.getProductCategoryList('refresh')
          this.$message.success('操作成功')
        } else {
          this.$message.error('操作失败')
        }
      }).catch(() => {
        this.$message.error('操作失败')
        this.confirmLoading = false
      })
    },
    handleCancel (e) {
      this.addProduct = {}
      this.imageUrl = ''
      this.fileList = []
      this.visible = false
    },
    showModal (type, record, index) {
      if (type === 'change') {
        this.changeSource = record
        this.addProduct = {
          productId: record.productId,
          productCategoryId: record.productCategoryId,
          productName: record.productName,
          productPrice: record.productPrice,
          productIcon: record.productIcon,
          uploadSuccess: true,
          sort: record.sort,
          productStatus: record.productStatus
        }
        this.imageUrl = record.productIcon
        this.changeSourceIndex = index
        this.changeType = 1
      } else {
        this.changeType = 0
      }
      this.visible = true
    },
    customRequest () {
      let that = this
      pressImg({
        file: this.fileList[0],
        targetSize: 50 * 1024,
        quality: 0.5,
        width: 180,
        succ: function (resultFile) {
          // 如果不是null就是压缩成功
          if (resultFile) {
            let file = resultFile
            let namelast = '.' + file.name.replace(/.+\./, '')
            let g_object_name = that.random_string(10) + namelast
            $http.post('/mingpay/v1/file/getOSSUploadSignature').then((res) => {
              var data = that.doData(res.data.data, file, g_object_name)
              that.doUpLoad(res.data.data.host, data)
            })
          }
        }
      })
    },
    saveProduct () {
      const temp = /^\d+\.?\d{0,2}$/
      if (!temp.test(this.addProduct.productPrice) || parseFloat(this.addProduct.productPrice) > 1000) {
        this.$message.error('请输入正确的数字金额,最多保留小数点后两位,最高金额为1000')
        return
      }
      if (!/^[0-9]*$/.test(this.addProduct.sort)) {
        this.$message.error('排序值为正整数')
        return false
      }
      if (!this.addProduct.uploadSuccess || !this.addProduct.productName || !this.addProduct.productPrice || !this.addProduct.productIcon || !this.addProduct.sort) {
        this.$message.error('请完整填写栏目')
        return false
      }
      if (this.changeType === 1) {
        let saveProductCategoryData = {
          productName: this.addProduct.productName === this.tableSource[this.changeSourceIndex].productName ? '' : this.addProduct.productName,
          productPrice: this.addProduct.productPrice === this.tableSource[this.changeSourceIndex].productPrice ? '' : this.addProduct.productPrice,
          productIcon: this.fileList.length === 0 ? '' : this.addProduct.productIcon,
          productStatus: '',
          productCategoryId: this.addProduct.productCategoryId === this.tableSource[this.changeSourceIndex].productCategoryId ? '' : this.addProduct.productCategoryId,
          productId: this.addProduct.productId,
          sort: this.addProduct.sort === this.tableSource[this.changeSourceIndex].sort ? '' : parseInt(this.addProduct.sort)
        }
        $http.post(`/mingpay/v1/isv/product/update_product`, saveProductCategoryData).then((res) => {
          if (res.data.resultCode === 0) {
            this.addProduct = {}
            this.imageUrl = ''
            this.fileList = []
            this.confirmLoading = false
            this.visible = false
            this.getProductCategoryList('refresh')
            this.$message.success('操作成功')
          } else {
            this.$message.error('操作失败')
          }
        }).catch(() => {
          this.$message.error('操作失败')
          this.confirmLoading = false
        })
      } else {
        let saveProductData = {
          productName: this.addProduct.productName,
          productPrice: this.addProduct.productPrice,
          productIcon: this.addProduct.productIcon,
          productStatus: '',
          productCategoryId: this.addProduct.productCategoryId,
          sort: parseInt(this.addProduct.sort)
        }
        this.confirmLoading = true
        $http.post(`/mingpay/v1/isv/product/save_product`, saveProductData).then((res) => {
          if (res.data.resultCode === 0) {
            this.addProduct = {}
            this.imageUrl = ''
            this.fileList = []
            this.confirmLoading = false
            this.visible = false
            this.$message.success('操作成功')
            this.getProductCategoryList('refresh')
          }
        }).catch(() => {
          this.confirmLoading = false
          this.$message.error('操作失败')
        })
      }
    },
    changeMenuItem (id) {
      this.menuId = id
      this.getProductCategoryList('refresh')
    },
    // 文件名十位数随机
    random_string (len) {
      len = len || 32
      var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
      var maxPos = chars.length
      var pwd = ''
      for (let i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos))
      }
      return pwd
    },
    beforeUpload (file) {
      const isJPG = file.type === 'image/jpeg' || 'image/png'
      if (!isJPG) {
        this.$message.error('请上传JPG或PNG格式图片!')
      }
      const isLt2M = file.size / 1024 / 1024 < 5
      if (!isLt2M) {
        this.$message.error('图片大小不能超过5MB!')
      }
      if (isJPG && isLt2M) {
        this.fileList = [file]
        this.imageUrl = ''
        return true
      } else {
        return false
      }
    },
    // 设置请求参数
    doData (params, file, g_object_name) {
      var request = new FormData()
      // 文件名字,可设置路径
      request.append('key', params.dir + g_object_name)
      // policy规定了请求的表单域的合法性
      request.append('policy', params.policy)
      // Bucket 拥有者的Access Key Id
      request.append('OSSAccessKeyId', params.accessid)
      // 让服务端返回200,不然,默认会返回204
      request.append('success_action_status', '200')
      // 根据Access Key Secret和policy计算的签名信息,OSS验证该签名信息从而验证该Post请求的合法性
      request.append('callback', '')
      request.append('Signature', params.signature)
      // 需要上传的文件filer
      request.append('Filename', g_object_name)
      request.append('file', file, g_object_name)
      return request
    },
    // 文件oss上传请求
    doUpLoad (url, data) {
      this.loading = true
      var that = this
      return new Promise((resolve, reject) => {
        let aliAxios = axios.create()
        aliAxios({
          url: url,
          method: 'post',
          withCredentials: false,
          baseURL: '',
          onUploadProgress: function (progressEvent) {
          },
          data: data,
          headers: { 'Content-Type': 'multipart/form-data' }
        }).then((res) => {
          console.log(res)
          if (res.status === 200) {
            that.loading = false
            that.addProduct.productIcon = data.get('key')
            that.addProduct.uploadSuccess = true
            getBase64(this.fileList[0], (imageUrl) => {
              this.imageUrl = imageUrl
              this.loading = false
            })
          }
        }).catch((err) => {
          console.log(err)
          this.$message.error('上传失败')
        })
      })
    }
  }
}
</script>

<style lang="less" scoped>
.item{
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 10px;
}
.item>label{
  width: 75px;
  text-align: right;
  margin-right: 8px;
}
.item>input{
  width: 220px;
}
.productionMenu{
  background: #fafafa;
  width: 200px;
}
.productionMenuTitle{
  background: #e6f7ff;
  font-weight: bold;
  height: 40px;
  line-height: 40px;
  text-align: center;
  color: #1890ff;
}
.productionMenuList>.menuItem{
  height: 40px;
  line-height: 40px;
  position: relative;
  text-align: center;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis
}
.productionMenuList>.menuItemAction{
  background: #ffffff;
  color: #1890ff;
}
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}
.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
// .menuProductStatus{
//   position: absolute;
//   left: 0;
//   top: 0;
//   width: 40px;
//   height: 40px;
// }
// .menuProductStatus img{
//   width: 40px;
//   height: 40px;
//   display: block;
// }
</style>