<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>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document-copy"
            @click="handleUploadReport(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="520px" append-to-body>
      <div class="qr-label-wrapper">
        <!-- 外层圆角标签 -->
        <div class="qr-label" ref="qrCard">
          <!-- 内层线框 + 四角折角 -->
          <div class="qr-label-inner">
            <!-- 四角折角装饰 -->
            <div class="corner corner-tl"></div>
            <div class="corner corner-tr"></div>
            <div class="corner corner-bl"></div>
            <div class="corner corner-br"></div>

            <!-- 上半区：左侧信息 + 右侧二维码 -->
            <div class="label-top">
              <!-- 左侧品牌信息 -->
              <div class="label-left">
                <div class="brand-name">{{ qrData.brandName }}</div>
                <div class="brand-en">{{ qrData.brandEn }}</div>
                <div class="divider-line"></div>
                <div class="scan-tip">扫码查看溯源信息</div>
              </div>

              <!-- 右侧二维码 -->
              <div class="label-right">
                <div class="qr-code-area">
                  <canvas id="qrCanvas"></canvas>
                </div>
              </div>
            </div>

            <!-- 主分隔线 -->
            <div class="main-divider"></div>

            <!-- 下半区：批次信息 -->
            <div class="label-bottom">
              <div class="batch-row">批次: {{ qrData.batchNo }}</div>
              <div class="label-bottom-divider"></div>
              <div class="origin-row">{{ qrData.origin }}原产</div>
            </div>
          </div>
        </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>
      <!-- 顶部批次基础信息 -->
      <div class="report-batch-info">
        <div class="batch-info-item">
          <span class="label">批次号：</span>
          <span class="value">{{ certForm.batchNo }}</span>
        </div>
        <div class="batch-info-item">
          <span class="label">商品名称：</span>
          <span class="value">{{ certForm.productName }}</span>
        </div>
        <div class="batch-info-item">
          <span class="label">农场名称：</span>
          <span class="value">{{ certForm.farmName }}</span>
        </div>
      </div>

      <el-divider></el-divider>

      <el-form ref="certForm" :model="certForm" :rules="certRules" label-width="100px">
        <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="1"
            :file-type="['jpg', 'jpeg', 'png', 'pdf']"
            :file-size="2"
          />
          <div class="el-upload__tip">
            仅支持上传 jpg/jpeg/png/pdf 格式文件，单个文件大小不超过 2MB，仅支持上传 1 个文件
          </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>

    <!-- 上传检测报告弹窗 -->
    <el-dialog :title="reportTitle" :visible.sync="reportVisible" width="760px" append-to-body>
      <!-- 顶部批次基础信息 -->
      <div class="report-batch-info">
        <div class="batch-info-item">
          <span class="label">批次号：</span>
          <span class="value">{{ reportForm.batchNo }}</span>
        </div>
        <div class="batch-info-item">
          <span class="label">商品名称：</span>
          <span class="value">{{ reportForm.productName }}</span>
        </div>
        <div class="batch-info-item">
          <span class="label">农场名称：</span>
          <span class="value">{{ reportForm.farmName }}</span>
        </div>
      </div>

      <el-divider></el-divider>

      <!-- 检测报告列表 -->
      <div class="report-list-container">
        <el-form ref="reportFormRef" :model="reportForm" :rules="reportRules" label-width="0">
          <div
            v-for="(item, index) in reportForm.reportItems"
            :key="index"
            class="report-item"
          >
            <div class="report-item-header">
              <span class="report-item-title">检测报告 {{ index + 1 }}</span>
              <el-button
                type="text"
                size="small"
                icon="el-icon-delete"
                class="delete-btn"
                @click="removeReportItem(index)"
              >
                删除
              </el-button>
            </div>

            <div class="report-item-content">
              <el-form-item
                :label="'报告编号'"
                :prop="'reportItems.' + index + '.reportNo'"
                :rules="{
                  required: true,
                  message: '报告编号不能为空',
                  trigger: 'blur'
                }"
                label-width="90px"
              >
                <el-input
                  v-model="item.reportNo"
                  placeholder="请输入报告编号"
                  style="width: 100%"
                />
              </el-form-item>

              <el-form-item
                :label="'检测日期'"
                :prop="'reportItems.' + index + '.reportDate'"
                :rules="{
                  required: true,
                  message: '检测日期不能为空',
                  trigger: 'change'
                }"
                label-width="90px"
              >
                <el-date-picker
                  v-model="item.reportDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="请选择检测日期"
                  style="width: 100%"
                />
              </el-form-item>

              <el-form-item
                :label="'检测文件'"
                :prop="'reportItems.' + index + '.reportFile'"
                :rules="{
                  required: true,
                  message: '请上传检测文件',
                  trigger: 'change'
                }"
                label-width="90px"
              >
                <file-upload
                  v-model="item.reportFile"
                  :limit="1"
                  :file-type="['jpg', 'jpeg', 'png', 'pdf']"
                  :file-size="2"
                />
              </el-form-item>

              <div class="report-tip">
                <i class="el-icon-info"></i>
                仅支持上传 jpg/jpeg/png/pdf 格式文件，单个文件大小不超过 2MB，每份检测报告仅支持上传 1 个文件；若原始报告为多页，请先合成为一张图片后上传
              </div>
            </div>
          </div>
        </el-form>

        <!-- 新增报告项按钮 -->
        <div class="add-report-btn">
          <el-button type="dashed" icon="el-icon-plus" @click="addReportItem">
            新增一份检测报告
          </el-button>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitReportForm">确 定</el-button>
        <el-button @click="cancelReport">取 消</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: "JIAYOU HOUYUAN",
        batchNo: "",
        origin: "",
        qrUrl: ""
      },
      // 是否显示合格证弹窗
      certVisible: false,
      // 合格证弹窗标题
      certTitle: "",
      // 合格证表单
      certForm: {
        id: null,
        batchId: null,
        batchNo: "",
        productName: "",
        farmName: "",
        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" }
        ]
      },

      // 检测报告弹窗相关
      reportVisible: false,
      reportTitle: "上传检测报告",
      reportForm: {
        batchId: null,
        batchNo: "",
        productName: "",
        farmName: "",
        reportItems: [
          {
            reportNo: "",
            reportDate: "",
            reportFile: ""
          }
        ]
      },
      reportRules: {},

      // 查询参数
      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.origin = 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: 140,
              height: 140,
              margin: 1,
              color: {
                dark: '#000000',
                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.certForm.productName = row.productName
      this.certForm.farmName = row.farmName
      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,
            productName: row.productName,
            farmName: row.farmName,
            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: "",
        productName: "",
        farmName: "",
        certNo: "",
        certIssueDate: null,
        certStatus: "pending",
        certFiles: []
      }
      this.resetForm("certForm")
    },
    /** 提交合格证表单 */
    /** 提交合格证表单 */
    submitCertForm() {
      this.$refs["certForm"].validate(valid => {
        if (valid) {
          // 前端兜底校验：检查文件类型
          const allowedTypes = ['jpg', 'jpeg', 'png', 'pdf']
          const certFilesValue = this.certForm.certFiles

          // 如果有上传文件，进行兜底校验
          if (certFilesValue && (typeof certFilesValue === 'string' ? certFilesValue.trim() : (Array.isArray(certFilesValue) && certFilesValue.length > 0))) {
            let fileUrls = []

            if (typeof certFilesValue === 'string') {
              fileUrls = certFilesValue.split(',')
            } else if (Array.isArray(certFilesValue)) {
              fileUrls = certFilesValue.map(file => file.url || file)
            }

            for (const fileUrl of fileUrls) {
              const url = typeof fileUrl === 'string' ? fileUrl.trim() : (fileUrl.url || '')
              if (!url) continue

              // 获取文件扩展名（小写）
              const ext = url.split('.').pop().toLowerCase()

              // 检查文件类型
              if (!allowedTypes.includes(ext)) {
                this.$message.warning("合格证文件仅支持 jpg/jpeg/png/pdf 格式")
                return
              }
            }
          }

          // 确保 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()
            })
          }
        }
      })
    },

    /** 打开上传检测报告弹窗 */
    handleUploadReport(row) {
      this.resetReport()
      this.reportForm.batchId = row.id
      this.reportForm.batchNo = row.batchNo
      this.reportForm.productName = row.productName
      this.reportForm.farmName = row.farmName
      this.reportVisible = true
      this.reportTitle = "上传检测报告"

      // TODO: 查询该批次是否已有检测报告数据
      // listReport({ batchId: row.id }).then(response => {
      //   if (response.rows && response.rows.length > 0) {
      //     // 已有检测报告，设置为编辑模式
      //   }
      // })
    },

    /** 取消检测报告 */
    cancelReport() {
      this.reportVisible = false
      this.resetReport()
    },

    /** 重置检测报告表单 */
    resetReport() {
      this.reportForm = {
        batchId: null,
        batchNo: "",
        productName: "",
        farmName: "",
        reportItems: [
          {
            reportNo: "",
            reportDate: "",
            reportFile: ""
          }
        ]
      }
      this.resetForm("reportFormRef")
    },

    /** 新增一条检测报告 */
    addReportItem() {
      this.reportForm.reportItems.push({
        reportNo: "",
        reportDate: "",
        reportFile: ""
      })
    },

    /** 删除一条检测报告 */
    removeReportItem(index) {
      if (this.reportForm.reportItems.length === 1) {
        this.$message.warning("至少保留一条检测报告")
        return
      }
      this.reportForm.reportItems.splice(index, 1)
    },

    /** 提交检测报告表单 */
    submitReportForm() {
      // 校验整个报告表单
      this.$refs["reportFormRef"].validate(valid => {
        if (valid) {
          // 校验每条报告项 - file-upload 组件返回逗号分隔的字符串
          const hasEmptyItem = this.reportForm.reportItems.some(item => {
            // 报告编号和检测日期是字符串，直接判断非空
            // reportFile 是上传组件返回的字符串，上传后会有值（如 "url1,url2"）
            const isReportFileEmpty = !item.reportFile || item.reportFile.trim() === ""
            return !item.reportNo || !item.reportDate || isReportFileEmpty
          })

          if (hasEmptyItem) {
            this.$message.warning("请完善每条检测报告的必填信息")
            return
          }

          // 前端兜底校验：检查文件类型和大小
          const allowedTypes = ['jpg', 'jpeg', 'png', 'pdf']
          const maxSize = 2 * 1024 * 1024 // 2MB

          for (let i = 0; i < this.reportForm.reportItems.length; i++) {
            const item = this.reportForm.reportItems[i]
            const files = item.reportFile

            // 如果有上传文件，进行兜底校验
            if (files && files.trim()) {
              const fileUrls = files.split(',')
              for (const fileUrl of fileUrls) {
                const trimmedUrl = fileUrl.trim()
                if (!trimmedUrl) continue

                // 获取文件扩展名（小写）
                const ext = trimmedUrl.split('.').pop().toLowerCase()

                // 检查文件类型
                if (!allowedTypes.includes(ext)) {
                  this.$message.warning(`第 ${i + 1} 条检测报告的文件格式不正确，仅支持 jpg/jpeg/png/pdf 格式`)
                  return
                }

                // 注意：这里无法直接获取文件大小进行校验
                // 文件大小由上传组件在上传前进行限制
                // 此处只能通过文件扩展名进行类型兜底校验
              }
            }
          }

          // 前端校验通过，打印数据
          console.log("检测报告表单数据:", this.reportForm)
          this.$message.success("前端校验通过，待接接口")

          // TODO: 接接口时的提交逻辑
          // const data = {
          //   batchId: this.reportForm.batchId,
          //   reportItems: this.reportForm.reportItems
          // }
        }
      })
    },
  }
}
</script>
<style scoped>
/* 二维码标签包装器 */
.qr-label-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 16px;
}

/* 外层圆角标签 - 3:2 比例 (60mm x 40mm) */
.qr-label {
  width: 390px;
  height: 260px;
  background: #ffffff;
  border: 1.5px solid #000000;
  border-radius: 8px;
  padding: 5px;
  box-shadow: none;
  box-sizing: border-box;
  overflow: hidden;
  aspect-ratio: 3 / 2;
  flex: 0 0 auto;
  flex-shrink: 0;
}

/* 内层线框 */
.qr-label-inner {
  position: relative;
  width: 100%;
  height: 100%;
  border: 1px solid #000000;
  border-radius: 4px;
  padding: 14px 16px 12px;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}

/* 四角折角装饰 */
.corner {
  position: absolute;
  width: 12px;
  height: 12px;
  border: 1px solid #000000;
}
.corner-tl {
  top: -1px;
  left: -1px;
  border-right: none;
  border-bottom: none;
  border-radius: 4px 0 0 0;
}
.corner-tr {
  top: -1px;
  right: -1px;
  border-left: none;
  border-bottom: none;
  border-radius: 0 4px 0 0;
}
.corner-bl {
  bottom: -1px;
  left: -1px;
  border-right: none;
  border-top: none;
  border-radius: 0 0 0 4px;
}
.corner-br {
  bottom: -1px;
  right: -1px;
  border-left: none;
  border-top: none;
  border-radius: 0 0 4px 0;
}

/* 上半区 */
.label-top {
  flex: 1;
  display: flex;
  align-items: center;
  box-sizing: border-box;
}

/* 左侧品牌信息 */
.label-left {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding-right: 14px;
}

.brand-name {
  font-size: 28px;
  font-weight: 900;
  color: #000000;
  letter-spacing: 8px;
  margin-bottom: 2px;
  line-height: 1.1;
  white-space: nowrap;
}

.brand-en {
  font-size: 10px;
  color: #000000;
  letter-spacing: 5px;
  margin-bottom: 10px;
  font-weight: 600;
  white-space: nowrap;
}

.divider-line {
  width: 100%;
  height: 1.5px;
  background: #000000;
  margin-bottom: 10px;
}

.scan-tip {
  font-size: 15px;
  color: #000000;
  letter-spacing: 2px;
  font-weight: 700;
  line-height: 1.3;
}

/* 右侧二维码 */
.label-right {
  width: 120px;
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.qr-code-area {
  width: 110px;
  height: 110px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 3px;
  border: 1px solid #000000;
}

.qr-code-area canvas,
#qrCanvas {
  width: 102px !important;
  height: 102px !important;
}

/* 主分隔线 */
.main-divider {
  width: 100%;
  height: 1.5px;
  background: #000000;
  margin: 10px 0;
}

/* 下半区 */
.label-bottom {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 0;
  box-sizing: border-box;
}

.batch-row {
  font-size: 17px;
  color: #000000;
  font-weight: 800;
  letter-spacing: 2px;
  margin-bottom: 8px;
  width: 100%;
  text-align: center;
  line-height: 1.3;
}

.label-bottom-divider {
  width: 100%;
  height: 1px;
  background: #000000;
  margin-bottom: 8px;
}

.origin-row {
  font-size: 16px;
  color: #000000;
  letter-spacing: 4px;
  font-weight: 700;
  text-align: center;
  width: 100%;
  line-height: 1.3;
}

.dialog-footer {
  text-align: center;
  padding-top: 10px;
}

/* 检测报告弹窗样式 */
.report-batch-info {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  padding: 10px 0;
}

.batch-info-item {
  display: flex;
  align-items: center;
}

.batch-info-item .label {
  color: #909399;
  font-size: 14px;
}

.batch-info-item .value {
  color: #303133;
  font-size: 14px;
  font-weight: 500;
}

.report-list-container {
  max-height: 450px;
  overflow-y: auto;
  padding-right: 5px;
}

.report-item {
  border: 1px solid #ebeef5;
  border-radius: 6px;
  margin-bottom: 16px;
  background-color: #fafafa;
  transition: border-color 0.3s;
}

.report-item:hover {
  border-color: #dcdfe6;
}

.report-item:last-of-type {
  margin-bottom: 12px;
}

.report-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  background-color: #ecf5ff;
  border-bottom: 1px solid #e4e7ed;
  border-radius: 6px 6px 0 0;
}

.report-item-title {
  font-size: 14px;
  font-weight: 500;
  color: #409eff;
}

.delete-btn {
  color: #f56c6c;
}

.delete-btn:hover {
  color: #f78989;
}

.report-item-content {
  padding: 15px;
}

.report-item-content .el-form-item {
  margin-bottom: 14px;
}

.report-item-content .el-form-item:last-child {
  margin-bottom: 0;
}

.report-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
  line-height: 1.4;
}

.report-tip i {
  margin-right: 4px;
}

.add-report-btn {
  margin-top: 8px;
}

.add-report-btn .el-button {
  width: 100%;
  border-style: dashed;
}
</style>