gaoluyang
6 天以前 c7b4b9a2f4c0f05aeb60a9e3f5fba5d9a3676f3f
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
<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>二维码与防伪码生成器</span>
          <el-button type="primary" @click="showBatchDialog" icon="Plus">
            批量生成
          </el-button>
        </div>
      </template>
      
      <!-- 集成二维码生成组件 -->
      <QRCodeGenerator ref="qrGeneratorRef" />
    </el-card>
 
    <!-- 批量生成对话框 -->
    <el-dialog v-model="batchDialogVisible" title="批量生成设置" width="800px">
      <el-form :model="batchForm" :rules="batchRules" ref="batchFormRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="标识类型" prop="type">
              <el-select v-model="batchForm.type" placeholder="请选择标识类型" style="width: 100%">
                <el-option label="二维码" value="qrcode"></el-option>
                <el-option label="防伪码" value="security"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生成数量" prop="quantity">
              <el-input-number 
                v-model="batchForm.quantity" 
                :min="1" 
                :max="1000" 
                :step="10"
                style="width: 100%"
              ></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="前缀" prop="prefix">
              <el-input v-model="batchForm.prefix" placeholder="请输入前缀,如:PROD_"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="起始编号" prop="startNumber">
              <el-input-number v-model="batchForm.startNumber" :min="1" style="width: 100%"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="尺寸" prop="size">
              <el-input-number 
                v-model="batchForm.size" 
                :min="100" 
                :max="500" 
                :step="50"
                style="width: 100%"
              ></el-input-number>
            </el-col>
          <el-col :span="12">
            <el-form-item label="边距" prop="margin">
              <el-input-number 
                v-model="batchForm.margin" 
                :min="0" 
                :max="10" 
                :step="1"
                style="width: 100%"
              ></el-input-number>
            </el-col>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="前景色" prop="foregroundColor">
              <el-color-picker v-model="batchForm.foregroundColor" style="width: 100%"></el-color-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="背景色" prop="backgroundColor">
              <el-color-picker v-model="batchForm.backgroundColor" style="width: 100%"></el-color-picker>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input 
                v-model="batchForm.remark" 
                type="textarea" 
                :rows="3"
                placeholder="请输入备注信息"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="batchDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="startBatchGeneration" :loading="generating">
            开始生成
          </el-button>
        </div>
      </template>
    </el-dialog>
 
    <!-- 批量生成进度 -->
    <el-dialog v-model="progressDialogVisible" title="批量生成进度" width="500px" :close-on-click-modal="false">
      <div class="progress-container">
        <el-progress 
          :percentage="progressPercentage" 
          :status="progressStatus"
          :stroke-width="20"
        ></el-progress>
        <p class="progress-text">{{ progressText }}</p>
        <div class="progress-details">
          <p>已生成: {{ generatedCount }} / {{ totalCount }}</p>
          <p>当前内容: {{ currentContent }}</p>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelGeneration" :disabled="!canCancel">取消</el-button>
          <el-button type="primary" @click="downloadBatchResults" v-if="generationCompleted">
            下载结果
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
 
<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import QRCodeGenerator from '@/components/QRCodeGenerator/index.vue'
import QRCode from 'qrcode'
import JSZip from 'jszip'
 
defineOptions({
  name: 'QRCodeGeneratorPage'
})
 
// 组件引用
const qrGeneratorRef = ref()
 
// 批量生成相关
const batchDialogVisible = ref(false)
const progressDialogVisible = ref(false)
const generating = ref(false)
const generationCompleted = ref(false)
const canCancel = ref(true)
 
const batchForm = reactive({
  type: 'qrcode',
  quantity: 100,
  prefix: 'PROD_',
  startNumber: 1,
  size: 200,
  margin: 2,
  foregroundColor: '#000000',
  backgroundColor: '#FFFFFF',
  remark: ''
})
 
const batchRules = {
  type: [{ required: true, message: '请选择标识类型', trigger: 'change' }],
  quantity: [{ required: true, message: '请输入生成数量', trigger: 'blur' }],
  prefix: [{ required: true, message: '请输入前缀', trigger: 'blur' }],
  startNumber: [{ required: true, message: '请输入起始编号', trigger: 'blur' }]
}
 
// 进度相关
const progressPercentage = ref(0)
const progressStatus = ref('')
const progressText = ref('准备中...')
const generatedCount = ref(0)
const totalCount = ref(0)
const currentContent = ref('')
 
// 生成结果
const batchResults = ref([])
 
// 显示批量生成对话框
const showBatchDialog = () => {
  batchDialogVisible.value = true
  // 重置表单
  Object.assign(batchForm, {
    type: 'qrcode',
    quantity: 100,
    prefix: 'PROD_',
    startNumber: 1,
    size: 200,
    margin: 2,
    foregroundColor: '#000000',
    backgroundColor: '#FFFFFF',
    remark: ''
  })
}
 
// 开始批量生成
const startBatchGeneration = async () => {
  try {
    await batchFormRef.value.validate()
    
    if (!batchForm.prefix.trim()) {
      ElMessage.warning('请输入前缀')
      return
    }
    
    batchDialogVisible.value = false
    progressDialogVisible.value = true
    generating.value = true
    generationCompleted.value = false
    canCancel.value = true
    
    // 重置进度
    progressPercentage.value = 0
    progressStatus.value = ''
    progressText.value = '开始生成...'
    generatedCount.value = 0
    totalCount.value = batchForm.quantity
    batchResults.value = []
    
    await generateBatchCodes()
    
  } catch (error) {
    console.error('批量生成失败:', error)
    ElMessage.error('批量生成失败:' + error.message)
  }
}
 
// 生成防伪码内容
const generateSecurityCode = (content) => {
  const timestamp = Date.now()
  const random = Math.random().toString(36).substr(2, 8)
  return `SEC_${content}_${timestamp}_${random}`
}
 
// 批量生成码
const generateBatchCodes = async () => {
  try {
    for (let i = 0; i < batchForm.quantity; i++) {
      if (!canCancel.value) {
        progressText.value = '生成已取消'
        progressStatus.value = 'exception'
        break
      }
      
      const number = batchForm.startNumber + i
      const content = `${batchForm.prefix}${number.toString().padStart(6, '0')}`
      currentContent.value = content
      
      let codeUrl
      if (batchForm.type === 'qrcode') {
        codeUrl = await QRCode.toDataURL(content, {
          width: batchForm.size,
          margin: batchForm.margin,
          color: {
            dark: batchForm.foregroundColor,
            light: batchForm.backgroundColor
          },
          errorCorrectionLevel: 'M'
        })
      } else {
        const securityContent = generateSecurityCode(content)
        codeUrl = await QRCode.toDataURL(securityContent, {
          width: batchForm.size,
          margin: batchForm.margin,
          color: {
            dark: batchForm.foregroundColor,
            light: batchForm.backgroundColor
          },
          errorCorrectionLevel: 'H'
        })
      }
      
      batchResults.value.push({
        content,
        url: codeUrl,
        type: batchForm.type,
        generateTime: new Date().toLocaleString()
      })
      
      generatedCount.value = i + 1
      progressPercentage.value = Math.round(((i + 1) / batchForm.quantity) * 100)
      progressText.value = `正在生成第 ${i + 1} 个码...`
      
      // 添加小延迟,让用户看到进度
      await new Promise(resolve => setTimeout(resolve, 50))
    }
    
    if (canCancel.value) {
      progressText.value = '生成完成!'
      progressStatus.value = 'success'
      generationCompleted.value = true
      ElMessage.success(`批量生成完成,共生成 ${batchForm.quantity} 个码`)
    }
    
  } catch (error) {
    console.error('批量生成失败:', error)
    progressText.value = '生成失败:' + error.message
    progressStatus.value = 'exception'
    ElMessage.error('批量生成失败:' + error.message)
  } finally {
    generating.value = false
  }
}
 
// 取消生成
const cancelGeneration = () => {
  canCancel.value = false
  progressText.value = '正在取消...'
  setTimeout(() => {
    progressDialogVisible.value = false
    ElMessage.info('生成已取消')
  }, 1000)
}
 
// 下载批量生成结果
const downloadBatchResults = async () => {
  if (batchResults.value.length === 0) {
    ElMessage.warning('没有可下载的结果')
    return
  }
  
  try {
    const zip = new JSZip()
    
    // 创建说明文件
    const readme = `批量生成说明
类型: ${batchForm.type === 'qrcode' ? '二维码' : '防伪码'}
数量: ${batchResults.value.length}
前缀: ${batchForm.prefix}
起始编号: ${batchForm.startNumber}
尺寸: ${batchForm.size}x${batchForm.size}px
生成时间: ${new Date().toLocaleString()}
备注: ${batchForm.remark || '无'}
 
文件列表:
${batchResults.value.map((item, index) => `${index + 1}. ${item.content}.png`).join('\n')}
`
    
    zip.file('README.txt', readme)
    
    // 添加图片文件
    batchResults.value.forEach((result, index) => {
      const base64Data = result.url.split(',')[1]
      const byteCharacters = atob(base64Data)
      const byteNumbers = new Array(byteCharacters.length)
      for (let i = 0; i < byteCharacters.length; i++) {
        byteNumbers[i] = byteCharacters.charCodeAt(i)
      }
      const byteArray = new Uint8Array(byteNumbers)
      
      zip.file(`${result.content}.png`, byteArray)
    })
    
    const content = await zip.generateAsync({ type: 'blob' })
    const a = document.createElement('a')
    a.href = URL.createObjectURL(content)
    a.download = `批量${batchForm.type === 'qrcode' ? '二维码' : '防伪码'}_${batchForm.prefix}_${new Date().getTime()}.zip`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(a.href)
    
    ElMessage.success('批量下载完成!')
    progressDialogVisible.value = false
    
  } catch (error) {
    console.error('批量下载失败:', error)
    ElMessage.error('批量下载失败:' + error.message)
  }
}
 
// 表单引用
const batchFormRef = ref()
</script>
 
<style scoped>
.app-container {
  padding: 20px;
}
 
.box-card {
  margin-bottom: 20px;
}
 
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
 
.progress-container {
  text-align: center;
  padding: 20px;
}
 
.progress-text {
  margin: 20px 0;
  font-size: 16px;
  font-weight: bold;
}
 
.progress-details {
  margin-top: 20px;
  text-align: left;
  background: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
}
 
.progress-details p {
  margin: 8px 0;
  color: #666;
}
 
.dialog-footer {
  text-align: right;
}
</style>