<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form ref="queryFormRef" :inline="true" :model="queryParams" class="-mb-15px" label-width="68px">
      <el-form-item label="产品名称" prop="name">
        <el-input v-model="queryParams.name" class="!w-240px" clearable placeholder="请输入产品名称"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="ProductKey" prop="productKey">
        <el-input v-model="queryParams.productKey" class="!w-240px" clearable placeholder="请输入产品标识"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
        <el-button v-hasPermi="['iot:product:create']" plain type="primary" @click="openForm('create')">
          <Icon class="mr-5px" icon="ep:plus" />
          新增
        </el-button>
        <el-button v-hasPermi="['iot:product:export']" :loading="exportLoading" plain type="success"
          @click="handleExport">
          <Icon class="mr-5px" icon="ep:download" />
          导出
        </el-button>
        <el-button plain type="warning" @click="openBatchQrDialog">
          <Icon class="mr-5px" icon="mdi:qrcode" />
          批量二维码
        </el-button>
      </el-form-item>
      <!-- 视图切换按钮 -->
      <el-form-item class="float-right !mr-0 !mb-0">
        <el-button-group>
          <el-button :type="viewMode === 'card' ? 'primary' : 'default'" @click="viewMode = 'card'">
            <Icon icon="ep:grid" />
          </el-button>
          <el-button :type="viewMode === 'list' ? 'primary' : 'default'" @click="viewMode = 'list'">
            <Icon icon="ep:list" />
          </el-button>
        </el-button-group>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 卡片视图 -->
  <ContentWrap>
    <el-row v-if="viewMode === 'card'" :gutter="16">
      <el-col v-for="item in list" :key="item.id" :lg="6" :md="12" :sm="12" :xs="24" class="mb-4">
        <el-card :body-style="{ padding: '0' }" class="h-full transition-colors relative">
          <!-- 二维码图标按钮 -->
          <div class="absolute top-3 right-3 z-10 flex items-center space-x-2">
            <div
              class="w-8 h-8 rounded-full bg-primary/10 hover:bg-primary/20 flex items-center justify-center cursor-pointer transition-colors group"
              @click="openBindDialog(item)" title="绑定采集卡">
              <Icon icon="ep:link" class="text-primary text-lg group-hover:scale-110 transition-transform" />
            </div>
            <div
              class="w-8 h-8 rounded-full bg-primary/10 hover:bg-primary/20 flex items-center justify-center cursor-pointer transition-colors group"
              @click="openQr(item)" title="生成二维码">
              <Icon icon="mdi:qrcode" class="text-primary text-lg group-hover:scale-110 transition-transform" />
            </div>
          </div>

          <!-- 内容区域 -->
          <div class="p-4">
            <!-- 标题区域 -->
            <div class="flex items-center mb-3 pr-8">
              <div class="mr-2.5 flex items-center">
                <el-image :src="item.icon || defaultIconUrl" class="w-[35px] h-[35px]" />
              </div>
              <div class="flex items-center">
                <div class="text-[16px] font-600">{{ item.name }}</div>
                <div class="ml-2 rounded-full flex-shrink-0" :class="{
                  'w-2 h-2 w-2 bg-gray-400': item.status === 0,
                  'w-3 h-4 w-4 bg-yellow-400': item.status === 1,
                  'w-3 h-4 w-4 bg-green-400': item.status === 2,
                  'w-3 h-4 w-4 bg-red-400': item.status === 3
                }"></div>
              </div>
            </div>

            <!-- 信息区域 -->
            <div class="flex items-center text-[14px]">
              <div class="flex-1">
                <div class="mb-2.5 last:mb-0">
                  <span class="text-[#717c8e] mr-2.5">产品分类</span>
                  <span class="text-[#0070ff]">{{ item.categoryName }}</span>
                </div>
<!--                <div class="mb-2.5 last:mb-0">-->
<!--                  <span class="text-[#717c8e] mr-2.5">产品类型</span>-->
<!--                  <dict-tag :type="DICT_TYPE.IOT_PRODUCT_DEVICE_TYPE" :value="item.deviceType" />-->
<!--                </div>-->
                <div class="mb-2.5 last:mb-0">
                  <span class="text-[#717c8e] mr-2.5">产品标识</span>
                  <span
                    class="text-[#0b1d30] inline-block align-middle overflow-hidden text-ellipsis whitespace-nowrap max-w-[140px]">
                    {{ item.productKey }}
                  </span>
                </div>
              </div>
              <div class="w-[100px] h-[100px]">
                <el-image :src="item.picUrl || defaultPicUrl" class="w-full h-full" />
              </div>
            </div>

            <!-- 分隔线 -->
            <el-divider class="!my-3" />

            <!-- 按钮组 -->
            <div class="flex items-center px-0">
              <el-button v-hasPermi="['iot:product:update']" class="flex-1 !px-2 !h-[32px] text-[13px]" plain
                type="primary" @click="openForm('update', item.id)">
                <Icon class="mr-1" icon="ep:edit-pen" />
                编辑
              </el-button>
              <el-button class="flex-1 !px-2 !h-[32px] !ml-[10px] text-[13px]" plain type="warning"
                @click="openDetail(item.id)">
                <Icon class="mr-1" icon="ep:view" />
                详情
              </el-button>
              <!--              <el-button class="flex-1 !px-2 !h-[32px] !ml-[10px] text-[13px]" plain type="success"-->
              <!--                @click="openObjectModel(item)">-->
              <!--                <Icon class="mr-1" icon="ep:scale-to-original" />-->
              <!--                物模型-->
              <!--              </el-button>-->
              <div class="mx-[10px] h-[20px] w-[1px] bg-[#dcdfe6]"></div>
              <el-button v-hasPermi="['iot:product:delete']" :disabled="item.status === 1"
                class="!px-2 !h-[32px] text-[13px]" plain type="danger" @click="handleDelete(item.id)">
                <Icon icon="ep:delete" />
              </el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 列表视图 -->
    <el-table v-else v-loading="loading" :data="list" :show-overflow-tooltip="true" :stripe="true">
      <el-table-column align="center" label="ID" prop="id" />
      <el-table-column align="center" label="ProductKey" prop="productKey" />
      <el-table-column align="center" label="品类" prop="categoryName" />
      <el-table-column align="center" label="设备类型" prop="deviceType">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.IOT_PRODUCT_DEVICE_TYPE" :value="scope.row.deviceType" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="产品图片" prop="picture">
        <template #default="scope">
          <el-image v-if="scope.row.picUrl" :preview-src-list="[scope.row.picture]" :src="scope.row.picUrl"
            class="w-40px h-40px" />
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column :formatter="dateFormatter" align="center" label="创建时间" prop="createTime" width="180px" />
      <el-table-column align="center" label="操作">
        <template #default="scope">
          <el-button v-hasPermi="['iot:product:query']" link type="primary" @click="openDetail(scope.row.id)">
            查看
          </el-button>
          <el-button link type="primary" @click="openBindDialog(scope.row)"> 绑定采集卡 </el-button>
          <el-button link type="primary" @click="openQr(scope.row)"> 二维码 </el-button>
          <el-button v-hasPermi="['iot:product:update']" link type="primary" @click="openForm('update', scope.row.id)">
            编辑
          </el-button>
          <el-button v-hasPermi="['iot:product:delete']" :disabled="scope.row.status === 1" link type="danger"
            @click="handleDelete(scope.row.id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <Pagination v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNo" :total="total"
      @pagination="getList" />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <ProductForm ref="formRef" @success="getList" />

  <!-- 批量二维码弹窗 -->
  <el-dialog v-model="batchQrDialogVisible" title="批量生成二维码" width="600px" :close-on-click-modal="false">
    <div class="space-y-4">
      <!-- 模式选择 -->
      <div>
        <div class="text-sm font-medium mb-3">选择生成模式：</div>
        <el-radio-group v-model="batchMode" class="w-full">
          <el-radio value="shared" class="w-full mb-2">
            <div
              class="flex items-center p-3 border border-gray-200 rounded-lg hover:border-blue-300 hover:bg-blue-50 transition-all">
              <div class="flex-1">
                <div class="font-medium text-gray-800">统一Logo模式</div>
              </div>
              <Icon icon="ep:grid" class="text-xl text-blue-500" />
            </div>
          </el-radio>
          <el-radio value="individual" class="w-full">
            <div
              class="flex items-center p-3 border border-gray-200 rounded-lg hover:border-green-300 hover:bg-green-50 transition-all">
              <div class="flex-1">
                <div class="font-medium text-gray-800">单独Logo模式</div>
              </div>
              <Icon icon="ep:list" class="text-xl text-green-500" />
            </div>
          </el-radio>
        </el-radio-group>
      </div>

      <!-- 统一Logo模式 -->
      <div v-if="batchMode === 'shared'" class="border border-gray-200 rounded-lg p-4">
        <div class="text-sm font-medium mb-3">上传统一Logo</div>
        <el-upload ref="batchLogoUploadRef" :auto-upload="false" :show-file-list="false" accept="image/*"
          :on-change="handleBatchLogoChange" class="w-full">
          <div
            class="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center hover:border-blue-400 transition-colors">
            <div v-if="!batchLogoImageUrl" class="text-gray-500">
              <Icon icon="ep:upload" class="text-3xl mb-3" />
              <div class="font-medium mb-1">点击上传统一Logo图片</div>
              <div class="text-sm text-gray-400">建议尺寸：64x64px，将应用到所有 {{ list.length }} 个设备</div>
            </div>
            <div v-else class="flex items-center justify-center">
              <img :src="batchLogoImageUrl" class="w-16 h-16 object-contain rounded border" />
              <div class="ml-4 text-left">
                <div class="font-medium text-gray-800">已选择统一Logo</div>
                <div class="text-sm text-gray-500 mt-1">将应用到所有 {{ list.length }} 个设备</div>
                <el-button size="small" type="danger" plain @click.stop="clearBatchLogo" class="mt-2">重新选择</el-button>
              </div>
            </div>
          </div>
        </el-upload>
      </div>

      <!-- 单独Logo模式 -->
      <div v-if="batchMode === 'individual'" class="border border-gray-200 rounded-lg p-4">
        <div class="flex items-center justify-between mb-3">
          <div class="text-sm font-medium text-gray-700">设备Logo状态</div>
          <div class="text-xs text-gray-500">已上传: {{ devicesWithLogo }}/{{ list.length }}</div>
        </div>
        <div class="max-h-40 overflow-y-auto space-y-2">
          <div v-for="product in list" :key="product.id"
            class="flex items-center space-x-3 p-2 border border-gray-100 rounded hover:bg-gray-50">
            <div class="flex-1 min-w-0">
              <div class="font-medium text-sm truncate">{{ product.name }}</div>
              <div class="text-xs text-gray-500">ID: {{ product.id }}</div>
            </div>
            <div class="w-10 h-10 border border-gray-200 rounded flex items-center justify-center flex-shrink-0">
              <img v-if="productLogos[product.id]" :src="productLogos[product.id]"
                class="w-full h-full object-contain rounded" />
              <Icon v-else icon="ep:picture" class="text-gray-300" />
            </div>
            <div class="text-xs text-gray-500 flex-shrink-0">
              {{ productLogos[product.id] ? '已上传' : '未上传' }}
            </div>
          </div>
        </div>
        <div class="mt-3 p-2 bg-yellow-50 border border-yellow-200 rounded text-xs text-yellow-700">
          <Icon icon="ep:warning" class="mr-1" />
          如需为设备上传Logo，请点击设备卡片上的"二维码"按钮
        </div>
      </div>

      <!-- 预览区域 -->
      <div class="border border-gray-200 rounded-lg p-4 bg-gray-50">
        <div class="text-sm font-medium mb-3 text-gray-700">预览效果</div>
        <div class="flex justify-center">
          <canvas ref="previewCanvasRef" width="128" height="158"
            class="border border-gray-300 rounded shadow-sm"></canvas>
        </div>
        <div class="text-center mt-3">
          <div class="text-xs text-gray-600">实际下载的二维码将包含设备名称和ID</div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer flex justify-between items-center">
        <div class="text-xs text-gray-500">
          <Icon icon="ep:info-filled" class="mr-1" />
          所有二维码将包含设备名称和ID信息
        </div>
        <div class="space-x-2">
          <el-button @click="batchQrDialogVisible = false">取消</el-button>
          <el-button type="primary" :disabled="!canBatchDownload" @click="handleBatchDownload">
            <Icon class="mr-1" icon="ep:download" />
            批量下载 ({{ list.length }}个)
          </el-button>
        </div>
      </div>
    </template>
  </el-dialog>

  <!-- 绑定采集卡弹窗 -->
  <el-dialog v-model="bindDialogVisible" title="绑定设备到采集卡" width="420px" :close-on-click-modal="false">
    <el-form ref="bindFormRef" :model="bindForm" :rules="bindFormRules" label-width="96px">
      <el-form-item label="产品" prop="productId">
        <el-input v-model="bindForm.productName" disabled />
      </el-form-item>
      <el-form-item label="采集卡ID" prop="deviceId">
        <el-input-number v-model="bindForm.deviceId" :min="1" class="!w-full" placeholder="请输入采集卡ID" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="bindDialogVisible = false">取消</el-button>
      <el-button plain type="danger" :disabled="bindForm.deviceId === undefined || bindForm.deviceId === null"
        :loading="unbindLoading" @click="handleUnbindDevice">
        <Icon class="mr-1" icon="ep:close-bold" />
        取消绑定
      </el-button>
      <el-button type="primary" :loading="bindLoading" @click="handleBindDevice">
        <Icon class="mr-1" icon="ep:check" />
        确定
      </el-button>
    </template>
  </el-dialog>

  <!-- 设备二维码弹窗（产品即设备，直接用产品ID） -->
  <el-dialog v-model="qrDialogVisible" title="设备二维码" width="400px" :close-on-click-modal="false">
    <div class="flex flex-col items-center">
      <!-- Logo上传区域 -->
      <div class="w-full mb-4">
        <div class="text-sm text-gray-600 mb-2">二维码中心Logo（可选）</div>
        <el-upload ref="logoUploadRef" :auto-upload="false" :show-file-list="false" accept="image/*"
          :on-change="handleLogoChange" class="w-full">
          <div
            class="border-2 border-dashed border-gray-300 rounded-lg p-4 text-center hover:border-blue-400 transition-colors">
            <div v-if="!logoImageUrl" class="text-gray-500">
              <Icon icon="ep:upload" class="text-2xl mb-2" />
              <div>点击上传Logo图片</div>
              <div class="text-xs text-gray-400 mt-1">建议尺寸：64x64px</div>
            </div>
            <div v-else class="flex items-center justify-center">
              <img :src="logoImageUrl" class="w-16 h-16 object-contain rounded" />
              <div class="ml-3">
                <div class="text-sm text-gray-600">已选择Logo</div>
                <el-button size="small" type="danger" plain @click.stop="clearLogo">清除</el-button>
              </div>
            </div>
          </div>
        </el-upload>
      </div>

      <!-- 二维码显示区域 -->
      <div class="relative">
        <canvas ref="qrCanvasRef"></canvas>
        <div v-if="logoImageUrl" class="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2">
          <img :src="logoImageUrl" class="w-8 h-8 object-contain bg-white rounded" />
        </div>
      </div>

      <div class="mt-2 text-12px text-gray-500">设备：{{ selectedProductName }}（ID：{{ selectedProductId }}）</div>
      <div class="mt-1 text-12px break-all text-gray-500">{{ qrContent }}</div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="qrDialogVisible = false">关闭</el-button>
        <el-button type="primary" :disabled="!selectedProductId" @click="downloadQr">
          <Icon class="mr-1" icon="ep:download" />
          下载二维码
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { dateFormatter } from '@/utils/formatTime'
import { ProductApi, ProductVO } from '@/api/iot/product/product'
import ProductForm from './ProductForm.vue'
import { DICT_TYPE } from '@/utils/dict'
import download from '@/utils/download'
import defaultPicUrl from '@/assets/imgs/iot/device.png'
import defaultIconUrl from '@/assets/svgs/iot/cube.svg'
import QRCode from 'qrcode'

/** iot 产品列表 */
defineOptions({ name: 'IoTProduct' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const { push } = useRouter()
const route = useRoute()

const loading = ref(true) // 列表的加载中
const activeName = ref('info') // 当前激活的标签页
const list = ref<ProductVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  productKey: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出加载中
const viewMode = ref<'card' | 'list'>('card') // 视图模式状态

// 二维码相关（产品即设备）
const qrDialogVisible = ref(false)
const qrCanvasRef = ref<HTMLCanvasElement | null>(null)
const selectedProductId = ref<number | undefined>(undefined)
const selectedProductName = ref<string>('')
const logoImageUrl = ref<string>('')
const logoUploadRef = ref()
const qrContent = computed(() => {
  return `${selectedProductId.value || ''}`
})

// 批量二维码相关
const batchQrDialogVisible = ref(false)
const batchMode = ref<'individual' | 'shared'>('shared')
const batchLogoImageUrl = ref<string>('')
const batchLogoUploadRef = ref()
const previewCanvasRef = ref<HTMLCanvasElement | null>(null)

// 绑定采集卡
const bindDialogVisible = ref(false)
const bindLoading = ref(false)
const unbindLoading = ref(false)
const bindFormRef = ref()
const bindForm = reactive({
  productId: undefined as number | undefined,
  productName: '',
  deviceId: undefined as number | undefined
})
const bindFormRules = {
  productId: [{ required: true, message: '缺少产品信息', trigger: 'change' }],
  deviceId: [{ required: true, message: '请输入采集卡ID', trigger: 'blur' }]
}

// 计算已上传Logo的设备数量
const devicesWithLogo = computed(() => {
  return list.value.filter(product => productLogos.value[product.id]).length
})

// 存储每个设备的Logo（从单个二维码弹窗上传的）
const productLogos = ref<Record<number, string>>({})

// 计算是否可以批量下载
const canBatchDownload = computed(() => {
  if (batchMode.value === 'shared') {
    return !!batchLogoImageUrl.value
  } else {
    return true // 单独模式总是可以下载，即使没有Logo
  }
})

const openQr = async (product: ProductVO) => {
  selectedProductId.value = product.id
  selectedProductName.value = product.name
  // 加载已保存的Logo
  logoImageUrl.value = productLogos.value[product.id] || ''
  qrDialogVisible.value = true
  await nextTick()
  await renderQr()
}

const openBindDialog = (product: ProductVO) => {
  bindForm.productId = product.id
  bindForm.productName = product.name
  bindForm.deviceId = (product as any).deviceId ?? undefined
  bindDialogVisible.value = true
  nextTick(() => {
    bindFormRef.value?.clearValidate()
  })
}

const handleBindDevice = async () => {
  if (!bindFormRef.value) return
  await bindFormRef.value.validate(async (valid: boolean) => {
    if (!valid || !bindForm.productId) return
    bindLoading.value = true
    try {
      const productRes = await ProductApi.getProduct(bindForm.productId)
      const productData = (productRes as any)?.data ?? (productRes as any)
      await ProductApi.updateProduct({
        ...productData,
        deviceId: bindForm.deviceId
      })
      message.success('绑定成功')
      bindDialogVisible.value = false
      await getList()
    } catch (error) {
      message.error('绑定失败')
    } finally {
      bindLoading.value = false
    }
  })
}

const handleUnbindDevice = async () => {
  if (!bindForm.productId) return
  unbindLoading.value = true
  try {
    const productRes = await ProductApi.getProduct(bindForm.productId)
    const productData = (productRes as any)?.data ?? (productRes as any)
    await ProductApi.updateProduct({
      ...productData,
      deviceId: null
    })
    bindForm.deviceId = undefined
    message.success('已取消绑定')
    bindDialogVisible.value = false
    await getList()
  } catch (error) {
    message.error('取消绑定失败')
  } finally {
    unbindLoading.value = false
  }
}

const renderQr = async () => {
  if (!qrCanvasRef.value || !selectedProductId.value) return

  // 生成基础二维码
  await QRCode.toCanvas(qrCanvasRef.value, qrContent.value, { width: 256 })

  // 如果有logo，在中心绘制
  if (logoImageUrl.value) {
    const ctx = qrCanvasRef.value.getContext('2d')
    if (ctx) {
      const logoSize = 32
      const logoX = (256 - logoSize) / 2
      const logoY = (256 - logoSize) / 2

      // 绘制白色背景
      ctx.fillStyle = 'white'
      ctx.fillRect(logoX - 2, logoY - 2, logoSize + 4, logoSize + 4)

      // 绘制Logo
      const logoImg = new Image()
      logoImg.onload = () => {
        ctx.drawImage(logoImg, logoX, logoY, logoSize, logoSize)
      }
      logoImg.src = logoImageUrl.value
    }
  }
}

// Logo处理
const handleLogoChange = (file: any) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    logoImageUrl.value = e.target?.result as string
    // 保存到productLogos中，用于批量下载
    if (selectedProductId.value) {
      productLogos.value[selectedProductId.value] = logoImageUrl.value
    }
    // 重新渲染二维码
    nextTick(() => {
      renderQr()
    })
  }
  reader.readAsDataURL(file.raw)
}

const clearLogo = () => {
  logoImageUrl.value = ''
  // 从productLogos中移除
  if (selectedProductId.value) {
    delete productLogos.value[selectedProductId.value]
  }
  logoUploadRef.value?.clearFiles()
  // 重新渲染二维码
  nextTick(() => {
    renderQr()
  })
}

// 创建带Logo和文字的二维码
const createQrWithLogoAndText = async (content: string, logoUrl?: string, deviceName?: string, deviceId?: string): Promise<HTMLCanvasElement> => {
  const qrSize = 256
  const textHeight = 60 // 文字区域高度
  const canvas = document.createElement('canvas')
  canvas.width = qrSize
  canvas.height = qrSize + textHeight

  const ctx = canvas.getContext('2d')
  if (!ctx) return canvas

  // 生成二维码到临时canvas
  const qrCanvas = document.createElement('canvas')
  qrCanvas.width = qrSize
  qrCanvas.height = qrSize
  await QRCode.toCanvas(qrCanvas, content, { width: qrSize })

  // 绘制二维码到主canvas
  ctx.drawImage(qrCanvas, 0, 0)

  // 如果有Logo，在二维码中心绘制
  if (logoUrl) {
    const logoSize = 32
    const logoX = (qrSize - logoSize) / 2
    const logoY = (qrSize - logoSize) / 2

    // 绘制白色背景
    ctx.fillStyle = 'white'
    ctx.fillRect(logoX - 2, logoY - 2, logoSize + 4, logoSize + 4)

    // 绘制Logo
    const logoImg = new Image()
    await new Promise((resolve) => {
      logoImg.onload = () => {
        ctx.drawImage(logoImg, logoX, logoY, logoSize, logoSize)
        resolve(true)
      }
      logoImg.src = logoUrl
    })
  }

  // 绘制文字信息
  if (deviceName || deviceId) {
    // 设置文字样式
    ctx.fillStyle = '#333333'
    ctx.textAlign = 'center'
    ctx.textBaseline = 'middle'

    // 绘制设备名称
    if (deviceName) {
      ctx.font = 'bold 16px Arial'
      ctx.fillText(deviceName, qrSize / 2, qrSize + 20)
    }

    // 绘制设备ID
    if (deviceId) {
      ctx.font = '14px Arial'
      ctx.fillStyle = '#666666'
      ctx.fillText(`ID: ${deviceId}`, qrSize / 2, qrSize + 40)
    }
  }

  return canvas
}

const downloadQr = async () => {
  if (!selectedProductId.value) return

  try {
    const canvas = await createQrWithLogoAndText(
      qrContent.value,
      logoImageUrl.value,
      selectedProductName.value,
      selectedProductId.value.toString()
    )
    const link = document.createElement('a')
    link.download = `device-${selectedProductId.value}-${selectedProductName.value}-qrcode.png`
    link.href = canvas.toDataURL('image/png')
    link.click()
  } catch (error) {
    console.error('下载二维码失败:', error)
    message.error('下载二维码失败')
  }
}

// 打开批量二维码弹窗
const openBatchQrDialog = () => {
  batchQrDialogVisible.value = true
  // 重置状态
  batchMode.value = 'shared'
  batchLogoImageUrl.value = ''
  // 生成预览
  nextTick(() => {
    generatePreview()
  })
}

// 批量Logo处理
const handleBatchLogoChange = (file: any) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    batchLogoImageUrl.value = e.target?.result as string
    // 生成预览
    nextTick(() => {
      generatePreview()
    })
  }
  reader.readAsDataURL(file.raw)
}

const clearBatchLogo = () => {
  batchLogoImageUrl.value = ''
  batchLogoUploadRef.value?.clearFiles()
  // 重新生成预览
  nextTick(() => {
    generatePreview()
  })
}

// 生成预览
const generatePreview = async () => {
  if (!previewCanvasRef.value) return

  const canvas = previewCanvasRef.value
  const ctx = canvas.getContext('2d')
  if (!ctx) return

  // 设置canvas尺寸
  canvas.width = 128
  canvas.height = 158 // 包含文字区域

  // 生成小尺寸二维码到临时canvas
  const qrCanvas = document.createElement('canvas')
  qrCanvas.width = 128
  qrCanvas.height = 128
  await QRCode.toCanvas(qrCanvas, '123456', { width: 128 })

  // 绘制二维码
  ctx.drawImage(qrCanvas, 0, 0)

  // 根据模式绘制Logo
  if (batchMode.value === 'shared' && batchLogoImageUrl.value) {
    // 共享模式：绘制统一Logo
    const logoSize = 16
    const logoX = (128 - logoSize) / 2
    const logoY = (128 - logoSize) / 2

    // 绘制白色背景
    ctx.fillStyle = 'white'
    ctx.fillRect(logoX - 1, logoY - 1, logoSize + 2, logoSize + 2)

    // 绘制Logo
    const logoImg = new Image()
    logoImg.onload = () => {
      ctx.drawImage(logoImg, logoX, logoY, logoSize, logoSize)
    }
    logoImg.src = batchLogoImageUrl.value
  }

  // 绘制预览文字
  ctx.fillStyle = '#333333'
  ctx.textAlign = 'center'
  ctx.textBaseline = 'middle'
  ctx.font = 'bold 10px Arial'
  ctx.fillText('设备名称', 64, 128 + 15)

  ctx.font = '8px Arial'
  ctx.fillStyle = '#666666'
  ctx.fillText('ID: 123456', 64, 128 + 30)
}

// 批量下载二维码
const handleBatchDownload = async () => {
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '正在生成二维码，请稍候...',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  try {
    // 创建ZIP文件
    const JSZip = (await import('jszip')).default
    const zip = new JSZip()

    if (batchMode.value === 'shared') {
      // 共享模式：所有二维码使用同一个Logo
      for (const product of list.value) {
        const canvas = await createQrWithLogoAndText(
          `${product.id}`,
          batchLogoImageUrl.value,
          product.name,
          product.id.toString()
        )
        const dataUrl = canvas.toDataURL('image/png')
        const base64Data = dataUrl.split(',')[1]

        zip.file(`device-${product.id}-${product.name}-qrcode.png`, base64Data, { base64: true })
      }
    } else {
      // 单独模式：每个二维码使用各自的Logo
      for (const product of list.value) {
        const logoUrl = productLogos.value[product.id] // 获取该设备已上传的Logo
        const canvas = await createQrWithLogoAndText(
          `${product.id}`,
          logoUrl, // 如果有Logo就使用，没有就是undefined
          product.name,
          product.id.toString()
        )
        const dataUrl = canvas.toDataURL('image/png')
        const base64Data = dataUrl.split(',')[1]

        zip.file(`device-${product.id}-${product.name}-qrcode.png`, base64Data, { base64: true })
      }
    }

    // 生成并下载ZIP文件
    const zipBlob = await zip.generateAsync({ type: 'blob' })
    const link = document.createElement('a')
    link.download = `devices-qrcodes-${new Date().getTime()}.zip`
    link.href = URL.createObjectURL(zipBlob)
    link.click()

    const modeText = batchMode.value === 'shared' ? '统一Logo' : '单独Logo'
    message.success(`批量下载完成，共${list.value.length}个设备二维码（${modeText}模式）`)
    batchQrDialogVisible.value = false
  } catch (error) {
    console.error('批量下载失败:', error)
    message.error('批量下载失败')
  } finally {
    loadingInstance.close()
  }
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ProductApi.getProductPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 打开详情 */
const openDetail = (id: number) => {
  push({ name: 'IoTProductDetail', params: { id } })
}


/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ProductApi.deleteProduct(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch { }
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ProductApi.exportProduct(queryParams)
    download.excel(data, '物联网产品.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
  // 处理 tab 参数
  const { tab } = route.query
  if (tab) {
    activeName.value = tab as string
  }
})
</script>
