<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="批次号" prop="batchNo">
        <el-input
          v-model="queryParams.batchNo"
          placeholder="请输入批次号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="商品规格" prop="productSpec">
        <el-input
          v-model="queryParams.productSpec"
          placeholder="请输入商品规格"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="农场名称" prop="farmName">
        <el-input
          v-model="queryParams.farmName"
          placeholder="请输入农场名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="农场所在地" prop="farmRegion">
        <el-input
          v-model="queryParams.farmRegion"
          placeholder="请输入农场所在地"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="生产/采收日期" prop="produceDate">
        <el-date-picker clearable
          v-model="queryParams.produceDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择生产/采收日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="包装日期" prop="packageDate">
        <el-date-picker clearable
          v-model="queryParams.packageDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择包装日期">
        </el-date-picker>
      </el-form-item> -->
       <el-form-item label="生产/采收日期" prop="produceDate">
        <el-date-picker clearable
          v-model="dateRange.produceDate"
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="包装日期" prop="packageDate">
        <el-date-picker clearable
          v-model="dateRange.packageDate"
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.batch_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="创建时间" prop="createdAt">
        <el-date-picker clearable
          v-model="queryParams.createdAt"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="更新时间" prop="updatedAt">
        <el-date-picker clearable
          v-model="queryParams.updatedAt"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择更新时间">
        </el-date-picker>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['base:batch:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['base:batch:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['base:batch:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['base:batch:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="batchList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="主键ID" align="center" prop="id" /> -->
      <el-table-column label="批次号" align="center" prop="batchNo" />
      <el-table-column label="商品名称" align="center" prop="productName" />
      <el-table-column label="商品规格" align="center" prop="productSpec" />
      <!-- <el-table-column label="商品图片URL" align="center" prop="productImage" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.productImage" :width="50" :height="50"/>
        </template>
      </el-table-column> -->
      <el-table-column label="商品简介" align="center" prop="productDesc" />
      <el-table-column label="农场名称" align="center" prop="farmName" />
      <el-table-column label="农场所在地" align="center" prop="farmRegion" />
      <!-- <el-table-column label="农场图片URL" align="center" prop="farmImage" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.farmImage" :width="50" :height="50"/>
        </template>
      </el-table-column> -->
      <el-table-column label="农场简介" align="center" prop="farmIntro" />
      <el-table-column label="生产/采收日期" align="center" prop="produceDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.produceDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="包装日期" align="center" prop="packageDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.packageDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.batch_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <!-- <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updatedAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updatedAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['base:batch:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['base:batch:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-share"
            @click="handleGenerateQrCode(scope.row)"
          >生成二维码</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document"
            @click="handleUploadCertificate(scope.row)"
          >上传合格证</el-button>

        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改批次管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="批次号" prop="batchNo">
          <el-input v-model="form.batchNo" placeholder="请输入批次号" />
        </el-form-item>
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品规格" prop="productSpec">
          <el-input v-model="form.productSpec" placeholder="请输入商品规格" />
        </el-form-item>
        <el-form-item label="商品图片" prop="productImage">
          <image-upload v-model="form.productImage"/>
        </el-form-item>
        <el-form-item label="商品简介" prop="productDesc">
          <el-input v-model="form.productDesc" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="农场名称" prop="farmName">
          <el-input v-model="form.farmName" placeholder="请输入农场名称" />
        </el-form-item>
        <el-form-item label="农场所在地" prop="farmRegion">
          <el-input v-model="form.farmRegion" placeholder="请输入农场所在地" />
        </el-form-item>
        <el-form-item label="农场图片" prop="farmImage">
          <image-upload v-model="form.farmImage"/>
        </el-form-item>
        <el-form-item label="农场简介" prop="farmIntro">
          <el-input v-model="form.farmIntro" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="生产/采收日期" prop="produceDate">
          <el-date-picker clearable
            v-model="form.produceDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择生产/采收日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="包装日期" prop="packageDate">
          <el-date-picker clearable
            v-model="form.packageDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择包装日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.batch_status"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- <el-form-item label="创建时间" prop="createdAt">
          <el-date-picker clearable
            v-model="form.createdAt"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择创建时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="更新时间" prop="updatedAt">
          <el-date-picker clearable
            v-model="form.updatedAt"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择更新时间">
          </el-date-picker>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

     <!-- 生成二维码弹窗 -->
    <el-dialog :title="qrTitle" :visible.sync="qrVisible" width="420px" append-to-body>
      <div class="qr-card" ref="qrCard">
        <div class="qr-header">
          <div class="brand-name">{{ qrData.brandName }}</div>
          <div class="brand-en">{{ qrData.brandEn }}</div>
        </div>
        <div class="qr-content">
          <div class="scan-tip">扫码查看溯源信息</div>
          <div class="batch-info">批次号：{{ qrData.batchNo }}</div>
          <div class="origin">{{ qrData.origin }}</div>
        </div>
        <div class="qr-code-wrapper">
          <canvas id="qrCanvas"></canvas>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleDownloadQrCode">下载二维码</el-button>
        <el-button @click="qrVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 上传合格证弹窗 -->
    <el-dialog :title="certTitle" :visible.sync="certVisible" width="600px" append-to-body>
      <el-form ref="certForm" :model="certForm" :rules="certRules" label-width="100px">
        <el-form-item label="批次号">
          <span>{{ certForm.batchNo }}</span>
        </el-form-item>
        <el-form-item label="合格证编号" prop="certNo">
          <el-input v-model="certForm.certNo" placeholder="请输入合格证编号" />
        </el-form-item>
        <el-form-item label="开具日期" prop="certIssueDate">
          <el-date-picker
            v-model="certForm.certIssueDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择开具日期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="状态" prop="certStatus">
          <el-select v-model="certForm.certStatus" placeholder="请选择状态">
            <el-option label="已上传" value="uploaded" />
            <el-option label="待上传" value="pending" />
          </el-select>
        </el-form-item>
        <el-form-item label="合格证文件" prop="certFiles">
          <file-upload v-model="certForm.certFiles" :limit="5" />
          <div class="el-upload__tip">
            支持上传多个文件，总数量不超过 5 个
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitCertForm">确 定</el-button>
        <el-button @click="cancelCert">取 消</el-button>
      </div>
    </el-dialog>

  
  </div>
</template>

<script>
import { listBatch, getBatch, delBatch, addBatch, updateBatch } from "@/api/base/batch"
import QRCode from 'qrcode'
import { listReport, getReport, addReport, updateReport } from "@/api/base/report"
import { listCertificate, getCertificate, addCertificate, updateCertificate } from "@/api/base/certificate"



export default {
  name: "Batch",
  dicts: ['batch_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 批次管理表格数据
      batchList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      // 日期范围
      dateRange: {
        produceDate: [],
        packageDate: []
      },

      // 是否显示二维码弹窗
      qrVisible: false,
      // 二维码弹窗标题
      qrTitle: "生成二维码",
      // 二维码数据
      qrData: {
        brandName: "爱智农",
        brandEn: "AIZHONGNONG",
        batchNo: "",
        origin: "",
        qrUrl: ""
      },
      // 是否显示合格证弹窗
      certVisible: false,
      // 合格证弹窗标题
      certTitle: "",
      // 合格证表单
      certForm: {
        id: null,
        batchId: null,
        batchNo: "",
        certNo: "",
        certIssueDate: null,
        certStatus: "pending",
        certFiles: []
      },
      // 合格证表单校验规则
      certRules: {
        certNo: [
          { required: true, message: "合格证编号不能为空", trigger: "blur" }
        ],
        certIssueDate: [
          { required: true, message: "开具日期不能为空", trigger: "change" }
        ],
        certStatus: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ]
      },
     
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        batchNo: null,
        productName: null,
        productSpec: null,
        productImage: null,
        productDesc: null,
        farmName: null,
        farmRegion: null,
        farmImage: null,
        farmIntro: null,
        produceDate: null,
        packageDate: null,
        produceDateStart: null,
        produceDateEnd: null,
        packageDateStart: null,
        packageDateEnd: null,
        status: null,
        createdAt: null,
        updatedAt: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        batchNo: [
          { required: true, message: "批次号不能为空", trigger: "blur" }
        ],
        productName: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
        farmName: [
          { required: true, message: "农场名称不能为空", trigger: "blur" }
        ],
        farmRegion: [
          { required: true, message: "农场所在地不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询批次管理列表 */
    getList() {
      this.loading = true
      listBatch(this.queryParams).then(response => {
        this.batchList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        batchNo: null,
        productName: null,
        productSpec: null,
        productImage: null,
        productDesc: null,
        farmName: null,
        farmRegion: null,
        farmImage: null,
        farmIntro: null,
        produceDate: null,
        packageDate: null,
        status: null,
        createdAt: null,
        updatedAt: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.queryParams.produceDateStart = this.dateRange.produceDate?.[0] || null
      this.queryParams.produceDateEnd = this.dateRange.produceDate?.[1] || null
      this.queryParams.packageDateStart = this.dateRange.packageDate?.[0] || null
      this.queryParams.packageDateEnd = this.dateRange.packageDate?.[1] || null
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange.produceDate = []
      this.dateRange.packageDate = []
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加批次管理"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getBatch(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改批次管理"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateBatch(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addBatch(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除批次管理编号为"' + ids + '"的数据项？').then(function() {
        return delBatch(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('base/batch/export', {
        ...this.queryParams
      }, `batch_${new Date().getTime()}.xlsx`)
    },
    /** 生成二维码 */
    async handleGenerateQrCode(row) {
      this.qrData.batchNo = row.batchNo
      this.qrData.farmRegion = row.farmRegion || '未知产地'
      // 这里替换成你的溯源页面地址，可以根据实际域名配置
     // const baseUrl = window.location.origin
      const baseUrl = 'https://nxy.gbdfarm.com:9001'
      this.qrData.qrUrl = `${baseUrl}/${row.id}`
      
      this.qrVisible = true
      
      // 等待 DOM 渲染后生成二维码
      this.$nextTick(async () => {
        const canvas = document.getElementById('qrCanvas')
        if (canvas) {
          try {
            await QRCode.toCanvas(canvas, this.qrData.qrUrl, {
              width: 150,
              height: 150,
              margin: 2,
              color: {
                dark: '#333333',
                light: '#ffffff'
              }
            })
          } catch (error) {
            console.error('二维码生成失败:', error)
            this.$message.error('二维码生成失败，请重试')
          }
        }
      })
    },


     /** 下载二维码卡片 */
    async handleDownloadQrCode() {
      const cardElement = this.$refs.qrCard
      if (!cardElement) {
        this.$message.warning('卡片未加载，请重试')
        return
      }

      try {
        // 动态导入 html2canvas
        const html2canvas = (await import('html2canvas')).default
        
        // 将整个卡片转换为图片
        const canvas = await html2canvas(cardElement, {
          backgroundColor: '#ffffff',
          scale: 2, // 提高清晰度
          useCORS: true,
          logging: false
        })
        
        // 转为图片并下载
        const imgUrl = canvas.toDataURL('image/png')
        const link = document.createElement('a')
        link.download = `溯源卡片_${this.qrData.batchNo}.png`
        link.href = imgUrl
        link.click()
        
        this.$message.success('下载成功')
      } catch (error) {
        console.error('下载失败:', error)
        this.$message.error('下载失败，请重试')
      }
    },
     /** 上传合格证按钮操作 */
    handleUploadCertificate(row) {
      this.resetCert()
      this.certForm.batchId = row.id
      this.certForm.batchNo = row.batchNo
      this.certVisible = true
      this.certTitle = "上传合格证"
      
      // 查询该批次是否已有合格证
      listCertificate({ batchId: row.id }).then(response => {
        if (response.rows && response.rows.length > 0) {
          // 已有合格证，设置为编辑模式
          const cert = response.rows[0]
          this.certForm = {
            id: cert.id,
            batchId: cert.batchId,
            batchNo: row.batchNo,
            certNo: cert.certNo,
            certIssueDate: cert.certIssueDate,
            certStatus: cert.certStatus,
            certFiles: []
          }
          
          // 解析 certFiles 字段（JSON 数组）
          if (cert.certFiles) {
            try {
              const parsedFiles = JSON.parse(cert.certFiles)
              if (Array.isArray(parsedFiles)) {
                // 确保每个文件对象都有 name 属性
                this.certForm.certFiles = parsedFiles.map(file => {
                  if (!file.name && file.url) {
                    const lastSlashIndex = file.url.lastIndexOf('/')
                    file.name = lastSlashIndex > -1 ? file.url.substring(lastSlashIndex + 1) : file.url
                  }
                  return file
                })
              } else {
                if (!parsedFiles.name && parsedFiles.url) {
                  const lastSlashIndex = parsedFiles.url.lastIndexOf('/')
                  parsedFiles.name = lastSlashIndex > -1 ? parsedFiles.url.substring(lastSlashIndex + 1) : parsedFiles.url
                }
                this.certForm.certFiles = [parsedFiles]
              }
            } catch (e) {
              console.error('certFiles JSON 解析失败:', e)
              this.certForm.certFiles = []
            }
          }
          
          this.certTitle = "编辑合格证"
        }
      })
    },
    /** 取消合格证 */
    cancelCert() {
      this.certVisible = false
      this.resetCert()
    },
    /** 重置合格证表单 */
    resetCert() {
      this.certForm = {
        id: null,
        batchId: null,
        batchNo: "",
        certNo: "",
        certIssueDate: null,
        certStatus: "pending",
        certFiles: []
      }
      this.resetForm("certForm")
    },
    /** 提交合格证表单 */
    /** 提交合格证表单 */
    submitCertForm() {
      this.$refs["certForm"].validate(valid => {
        if (valid) {
          // 确保 certFiles 是正确的格式
          let certFilesArray = []
          
          if (Array.isArray(this.certForm.certFiles)) {
            // 如果已经是数组，确保每个文件都有 name 属性
            certFilesArray = this.certForm.certFiles.map(file => {
              if (!file.name && file.url) {
                const lastSlashIndex = file.url.lastIndexOf('/')
                file.name = lastSlashIndex > -1 ? file.url.substring(lastSlashIndex + 1) : file.url
              }
              return file
            })
          } else if (typeof this.certForm.certFiles === 'string') {
            // 如果是字符串，先尝试解析为 JSON
            try {
              const parsed = JSON.parse(this.certForm.certFiles)
              if (Array.isArray(parsed)) {
                certFilesArray = parsed.map(file => {
                  if (!file.name && file.url) {
                    const lastSlashIndex = file.url.lastIndexOf('/')
                    file.name = lastSlashIndex > -1 ? file.url.substring(lastSlashIndex + 1) : file.url
                  }
                  return file
                })
              } else {
                certFilesArray = [{ 
                  url: typeof parsed === 'string' ? parsed : parsed.url,
                  name: typeof parsed === 'string' ? parsed.split('/').pop() : parsed.url?.split('/').pop()
                }]
              }
            } catch (e) {
              // JSON 解析失败，说明是逗号分隔的字符串
              console.warn('certFiles 不是 JSON 格式，按逗号分隔处理:', e)
              if (this.certForm.certFiles.trim()) {
                certFilesArray = this.certForm.certFiles.split(',').map(url => {
                  const trimmedUrl = url.trim()
                  return {
                    url: trimmedUrl,
                    name: trimmedUrl.split('/').pop() || trimmedUrl
                  }
                })
              }
            }
          }
          
          // 准备提交数据（使用大驼峰命名）
          const data = {
            batchId: this.certForm.batchId,
            certNo: this.certForm.certNo,
            certIssueDate: this.certForm.certIssueDate,
            certStatus: this.certForm.certStatus,
            // 关键：转为 JSON 字符串存储到数据库
            certFiles: JSON.stringify(certFilesArray)
          }
          
          if (this.certForm.id != null) {
            // 修改
            updateCertificate({ ...data, id: this.certForm.id }).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.certVisible = false
              this.resetCert()
            })
          } else {
            // 新增
            addCertificate(data).then(response => {
              this.$modal.msgSuccess("上传成功")
              this.certVisible = false
              this.resetCert()
            })
          }
        }
      })
    },
  }
}
</script>
<style scoped>
.qr-card {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30px 20px;
  border: 2px solid #e0e0e0;
  border-radius: 12px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  font-size: 14px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.qr-header {
  flex: 1;
  text-align: left;
  padding-right: 15px;
}

.brand-name {
  font-size: 22px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
  letter-spacing: 1px;
}

.brand-en {
  font-size: 12px;
  color: #666;
  margin-bottom: 15px;
  letter-spacing: 0.5px;
}

.qr-content {
  flex: 1;
  text-align: left;
  padding: 0 15px;
}

.scan-tip {
  margin-bottom: 12px;
  color: #333;
  font-weight: 500;
  font-size: 13px;
}

.batch-info {
  margin-bottom: 10px;
  font-weight: 600;
  color: #2c3e50;
  font-size: 15px;
}

.origin {
  color: #666;
  font-size: 13px;
}

.qr-code-wrapper {
  width: 160px;
  height: 160px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff;
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

#qrCanvas {
  width: 150px;
  height: 150px;
}

.dialog-footer {
  text-align: center;
  padding-top: 10px;
}
</style>