fuliqi
2024-01-24 29c1e7eb5ac16e90d8991a86c1c071bc312ec8d9
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
<template>
  <div class="inner-bg-style couponMgtStyle">
    <h5 class="titleStyle">{{ title }}</h5>
    <el-row>
      <el-col :span="16">
        <el-form ref="form" size="mini" label-width="120px" :model="form" :rules="formRules">
          <el-form-item label="优惠券名称:" prop="couponName">
            <el-input v-model="form.couponName" placeholder="请输入优惠券" clearable></el-input>
          </el-form-item>
          <el-form-item label="优惠券类型:" prop="recordType">
            <el-select placeholder="请选择优惠券类型" v-model="form.recordType"
                       @change="selectedRecordType(form.recordType)" clearable class="selectStyle">
              <el-option v-for="item in recordTypeArr" :key="item.id" :value="item.id"
                         :label="item.name"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发放总量:" prop="totalAmountIssued">
            <el-input-number :min="-1" @keydown.native="limiInputType"
                             :disabled="form.recordType === '4' || form.recordType === '5'"
                             v-model="form.totalAmountIssued"></el-input-number>
            <span class="couponTag">
              <i class="el-icon-warning"></i> -1为不限制
            </span>
          </el-form-item>
          <el-form-item label="适用商品:" prop="applyType">
            <el-radio-group v-model="form.applyType">
              <el-radio v-for="item in applicableArr" :key="item.id" :label="item.id">
                {{ item.name }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="form.applyType === '2'" prop="promotionProducts">
            <coupon-product ref="table" :productData.sync="form.promotionProducts"
                            @hand-selected="handSelected" :formRules="formRules"
                            :isShowSpuId="false"></coupon-product>
          </el-form-item>
          <el-form-item label="使用门槛:" prop="applicableThreshold">
            <el-radio-group v-model="form.applicableThreshold"
                            @change="form.fullMinusCondition = null">
              <el-radio label="1">无使用门槛</el-radio>
              <el-radio label="2">订单满
                <el-input-number size="mini" :disabled="
                                        !form.applicableThreshold ||
                                        form.applicableThreshold === '1' ? true : false"
                                 @keydown.native="limiInputType" v-model="form.fullMinusCondition"
                                 :min='0' @change="changeFullMinusCondition"></el-input-number>
                元
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="form.recordType === '2'" label="优惠折扣:" prop="deductionAmount">
            打 <el-input-number @keydown.native="limiInputType" v-model="form.deductionAmount"
                             @change="changeFullMinusCondition" :min='1'
                             :max='9.99'></el-input-number>
            折
            <span class="couponTag">
              <i class="el-icon-warning"></i> 输入折扣范围在1~9.99之间
            </span>
          </el-form-item>
          <el-form-item v-else label="优惠面额:" prop="deductionAmount">
            <el-input-number @keydown.native="limiInputType" v-model="form.deductionAmount"
                             @change="changeFullMinusCondition"></el-input-number>
            元
          </el-form-item>
          <el-form-item label="用券时间:" prop="couponTimeType">
            <el-radio-group v-model="form.couponTimeType" @change="changeUseTime">
              <el-radio label="1">领券后当日生效</el-radio>
              <el-radio label="2">固定时间</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="有效天数:" v-if="form.couponTimeType === '1'" prop="effectiveDays">
            <el-input-number :min="0" @keydown.native="limiInputType" v-model="form.effectiveDays">
            </el-input-number>
            天
          </el-form-item>
          <el-form-item label="起止时间:" v-if="form.couponTimeType === '2'" prop="startAndEndTime">
            <el-date-picker v-model="form.startAndEndTime" type="datetimerange" range-separator="至"
                            start-placeholder="开始日期" value-format="yyyy-MM-dd HH:mm:ss"
                            @change="getStartAndEndTime"
                            :picker-options="{disabledDate:time => time.getTime() <= Date.now() - 86400000}"
                            end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="每人限领张数:" prop="frequency">
            <el-input-number :min="-1" @keydown.native="limiInputType"
                             :disabled="form.recordType === '6' || form.recordType === '5'"
                             v-model="form.frequency"></el-input-number>
            次
            <span class="couponTag">
              <i class="el-icon-warning"></i> -1为不限制
            </span>
          </el-form-item>
          <el-form-item label="优惠券描述:" prop="couponDes">
            <el-input v-model="form.couponDes" type="textarea"
                      :autosize="{ minRows: 2, maxRows: 4 }" placeholder="请输入" clearable></el-input>
          </el-form-item>
        </el-form>
        <el-row class="buttonPosition">
          <el-button type="primary" size="mini" @click="submit">保存</el-button>
          <el-button size="mini" @click="cancel">取消</el-button>
        </el-row>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import couponProduct from '@/views/couponMgt/components/couponProduct.vue'
import { limiInputType } from '@/utils/limiInputType'
import couponApi from '@/api/promotion/coupon'
import couponType from '@/utils/constant/couponType'
import { inputNumberValid } from '@/utils/validator'
 
export default {
  components: { couponProduct },
  data() {
    const numberValid = (rule, value, callback) => {
      const reg = /^[0-9]*$/ // 只能输入正整数
      if (value !== -1 && !reg.test(value)) {
        callback(new Error('请输入整数'))
      } else if (value === 0) {
        callback(new Error('输入数量不能为 0'))
      } else {
        callback()
      }
    }
    // 每人限领次数限制
    const frequencyValid = (rule, value, callback) => {
      if ((this.form.recordType === '1' || this.form.recordType === '4') && value === -1) {
        callback(new Error('当为优惠券、新人券每人限领次数不能为-1'))
      } else if (this.form.recordType !== '6' && this.form.totalAmountIssued && value && this.form.totalAmountIssued !== -1) {
        if (value === -1) {
          callback(new Error('因发放总量不为-1,所以限领张数不能为-1'))
        } else if (value > this.form.totalAmountIssued) {
          callback(new Error('限领张数不能大于发放总量'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    const startAndEndTimeValidator = (rule, val, callback) => {
      var oDate1 = new Date(val[0])
      if (val[0] === val[1]) {
        callback(new Error('开始时间与结束时间不能相同'))
      } else if (oDate1.getTime() < Date.now()) {
        callback(new Error('开始时间不能小于当前时间'))
      } else {
        callback()
      }
    }
    return {
      title: '新增优惠券',
      form: {
        couponName: null,
        totalAmountIssued: null,
        applyType: null,
        applicableThreshold: null,
        deductionAmount: null,
        couponTimeType: null,
        startAndEndTime: [],
        frequency: null,
        effectiveDays: null,
        effectiveStartDate: null,
        effectiveEndDate: null,
        fullMinusCondition: 0,
        couponDes: null,
        recordType: null,
        npPromotionProds: [],
        promotionProducts: []
      },
      formRules: {
        couponName: [
          { required: true, message: '请输入优惠券名称' },
          { max: 20, message: '优惠券名称最多只能输入 20 个字' }
        ],
        recordType: [{ required: true, message: '请选择优惠券类型' }],
        totalAmountIssued: [
          { required: true, message: '请输入发放总量' },
          { validator: numberValid }
        ],
        promotionProducts: [
          { type: 'array', required: true, message: '请选择指定商品', trigger: 'submit' }
        ],
        couponSkuId: [{ type: 'array', required: true, message: '请选择商品规格', trigger: 'change' }],
        applyType: [{ required: true, message: '请选择适用商品', trigger: 'change' }],
        applicableThreshold: [
          { required: true, message: '请选择使用门槛' },
          {
            validator: (rule, value, callback) => {
              const reg = /^(?!0+$)(?!0*\.0*$)\d{1,9}(\.\d{1,2})?$/ // 最多输入两位小数
              if (value === '2' && !this.form.fullMinusCondition) {
                callback(new Error('请输入满减金额'))
              } else if (value === '2' && this.form.fullMinusCondition > 999999999) {
                callback(new Error('最大金额不能超过 999999999'))
              } else if (value === '2' && !reg.test(this.form.fullMinusCondition)) {
                callback(new Error('最多输入两位小数'))
              } else if (value === '2' && this.form.deductionAmount && this.form.fullMinusCondition <= this.form.deductionAmount && this.form.recordType !== '2') {
                callback(new Error('满减金额不能小于等于优惠面额'))
              } else {
                callback()
              }
            }
          }
        ],
        deductionAmount: [
          {
            required: true,
            validator: (rule, value, callback) => {
              const reg = /^(?!0+$)(?!0*\.0*$)\d{1,9}(\.\d{1,2})?$/ // 最多输入两位小数
              if ((!value || value <= 0) && this.form.recordType !== '2') {
                callback(new Error('优惠面额应大于0'))
              } else if ((!value || value <= 0) && this.form.recordType === '2') {
                callback(new Error('优惠折扣应大于0'))
              } else if (value > 999999999) {
                callback(new Error('优惠面额不能超过 999999999'))
              } else if (!reg.test(value)) {
                callback(new Error('最多输入两位小数'))
              } else if (this.form.fullMinusCondition && this.form.fullMinusCondition <= this.form.deductionAmount && this.form.recordType !== '2') {
                callback(new Error('优惠面额不能大于等于满减金额'))
              } else {
                callback()
              }
            }
          }
        ],
        couponTimeType: [{ required: true, message: '请选择用券时间' }],
        effectiveDays: [
          { required: true, message: '请输入有效天数' },
          { validator: inputNumberValid }
        ],
        startAndEndTime: [
          {
            type: 'array',
            required: true,
            message: '请选择起止时间'
          },
          { validator: startAndEndTimeValidator }
        ],
        frequency: [
          { required: true, message: '请输入每人限领张数', trigger: 'change' },
          { validator: numberValid, trigger: 'change' },
          { validator: frequencyValid, trigger: 'change' }
        ],
        couponDes: [
          { required: true, message: '请输入优惠券描述' },
          { max: 500, message: '优惠券描述最多只能输入 500 个字' }
        ]
      },
      applicableArr: [
        {
          id: '1',
          name: '全部商品可用'
        },
        {
          id: '2',
          name: '指定商品可用'
        }
      ],
      recordTypeArr: couponType, // 优惠券类型
      isCopy: null
    }
  },
  created() {
    if (this.$route.query.id) {
      this.getDetails()
      this.title = '编辑优惠券'
      this.isCopy = this.$route.query.isCopy
    }
  },
  methods: {
    // 当满减金额、优惠面额改变时触发验证
    changeFullMinusCondition(val) {
      this.$refs.form.validateField('applicableThreshold')
      this.$refs.form.validateField('deductionAmount')
    },
    // 当选择商品时
    handSelected() {
      this.$refs.form.clearValidate('promotionProducts')
    },
    /**
         * 选择优惠券类型时触发
         * 设置发放总量及发放总量的编辑状态
         */
    selectedRecordType(val) {
      switch (val) {
        case '4':
          this.form.totalAmountIssued = -1
          this.form.frequency = 0
          break
        case '5':
          // this.form.couponTimeType = '1'
          this.form.frequency = -1
          this.form.totalAmountIssued = -1
          break
        case '6':
          this.form.frequency = -1
          this.form.totalAmountIssued = 0
          break
        default:
          this.form.totalAmountIssued = 0
          this.form.frequency = 0
          break
      }
      this.$refs.form.clearValidate()
    },
    /**
         * 限制不能输入数字
         */
    limiInputType(e) {
      limiInputType(e)
      this.$refs.form.clearValidate()
    },
    /**
         * 获取起止时间
         */
    getStartAndEndTime(val) {
      if (val && val.length) {
        this.form.effectiveStartDate = val[0]
        this.form.effectiveEndDate = val[1]
      } else {
        this.form.effectiveStartDate = null
        this.form.effectiveEndDate = null
      }
    },
    /**
         * 获取详情
         */
    getDetails() {
      couponApi
        .detailsInfo({ couponInfoId: this.$route.query.id })
        .then((res) => {
          if (res.data) {
            res.data.startAndEndTime = []
            this.form = res.data
            this.form.promotionProducts = []
            const tempArr = []
            const arr = res.data.npPromotionProds
            const afterArr = this.form.promotionProducts
            this.setProductSkuIds(tempArr, arr, afterArr)
            if (this.form.couponTimeType === '2') {
              this.form.startAndEndTime = [
                this.form.effectiveStartDate,
                this.form.effectiveEndDate
              ]
              this.form.effectiveDays = null
            } else {
              this.form.effectiveStartDate = null
              this.form.effectiveEndDate = null
            }
            // this.selectedRecordType(this.form.recordType, 2) // 选择优惠券类型时触发
          }
        })
    },
    /**
     * 查看详情时遍历返回的商品,把prodId相同的skuId组装在一起
     */
    setProductSkuIds(tempArr, arr, afterArr) {
      for (let i = 0; i < arr.length; i++) {
        const prodSpecsArr = []
        const skuIdArr = []
        const skuReduceStorageArr = []
        if (tempArr.indexOf(arr[i].prodId) === -1) {
          prodSpecsArr.push(arr[i].prodSpecs)
          skuIdArr.push(arr[i].skuId)
          skuReduceStorageArr.push(arr[i].skuReduceStorage)
          afterArr.push({
            prodId: arr[i].prodId,
            prodName: arr[i].prodName,
            spuNum: arr[i].spuNum,
            prodSpecs: prodSpecsArr,
            skuId: skuIdArr,
            extparams: arr[i].extparams,
            spuUnit: arr[i].spuUnit,
            skuReduceStorageArr: skuReduceStorageArr
          })
          tempArr.push(arr[i].prodId)
        } else {
          for (let j = 0; j < afterArr.length; j++) {
            if (afterArr[j].prodId === arr[i].prodId) {
              afterArr[j].skuId.push(arr[i].skuId)
              afterArr[j].prodSpecs.push(arr[i].prodSpecs)
              afterArr[j].skuReduceStorageArr.push(arr[i].skuReduceStorage)
              break
            }
          }
        }
      }
    },
    /**
         * 改变用券时间时触发
         */
    changeUseTime() {
      this.$refs.form.clearValidate('effectiveDays')
      this.$refs.form.clearValidate('startAndEndTime')
      this.form.effectiveDays = null
      this.form.startAndEndTime = []
      this.form.effectiveStartDate = null
      this.form.effectiveEndDate = null
    },
    /**
         * 处理表单数据
         */
    handFormData() {
      this.form.npPromotionProds = this.$refs.table ? this.$refs.table.handTableData() : null
      if (this.form.applyType !== '2') {
        this.form.npPromotionProds = []
      }
      if (this.form.recordType === '4') {
        this.form.areSell = '0'
      } else {
        this.form.areSell = ''
      }
    },
    /**
         * 提交
         */
    submit() {
      this.$refs.form.validate().then((res) => {
        this.handFormData() // 处理表单数据
        if (this.form.couponInfoId && !this.isCopy) {
          this.editInfo() // 编辑优惠券
        } else {
          this.addInfo() // 增加优惠券
        }
      })
    },
    /**
         * 增加优惠券
         */
    addInfo() {
      couponApi.addItem(this.form).then((res) => {
        if (res.data) {
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          this.$router.push({ name: 'couponMgtList' })
        }
      })
    },
    /**
         * 编辑优惠券
         */
    editInfo() {
      couponApi.editItem(this.form).then((res) => {
        if (res.data) {
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          this.$router.push({ name: 'couponMgtList' })
        }
      })
    },
    /**
         *取消
         */
    cancel() {
      this.$router.push({ name: 'couponMgtList' })
    }
  }
}
</script>
<style>
.titleStyle {
  margin-bottom: 10px;
}
.couponTag {
  color: #f56c6c;
}
.couponMgtStyle {
  padding: 20px;
}
.selectStyle {
  width: 100%;
}
</style>