<template>
  <div class="app-container">
    <div class="container">
      <!-- 查询表单 -->
      <el-form :model="queryParams"
        inline
        label-width="110px"
        label-position="left">
        <el-form-item label="输入厂家名称"
          prop="manufacturersNameLike">
          <el-input v-model="queryParams.manufacturersNameLike"
            placeholder="请输入厂家名称"
            @input="getList"
             />
        </el-form-item>
      </el-form>
      <!-- 功能按钮 -->
      <el-row>
        <el-col :span="12">
          <el-button type="primary"
            plain
            icon="Plus"
            @click="dialogVisible = true">
            新增
          </el-button>
        </el-col>
      </el-row>
      <!-- 表格列表 -->
      <el-table :data="tableList"
        style="width: 100%;">
        <el-table-column prop="prdCode"
          label="料号"
          width="180" />
        <el-table-column prop="prdName"
          label="产品名称" />
        <el-table-column prop="manufactureBatchNo"
          label="批号" />
        <el-table-column prop="manufacturersName"
          label="厂家" />
        <el-table-column prop="qualityUrl"
          label="质量检测报告"
          width="180">
          <template #default="{ row }">
            <el-link v-if="row.qualityUrl"
              type="primary"
              @click="handleReportClick(row.qualityUrl)">
              {{ getReportLinkText(row.qualityUrl) }}
            </el-link>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="shipDate"
          label="发货时间"
          width="180" />
      </el-table>
      <!-- 分页 -->
      <pagination :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList" />
      <!-- 新增弹窗 -->
      <el-dialog title="新增"
        v-model="dialogVisible"
        draggable
        overflow>
        <el-form :model="formData"
          ref="formRef"
          :rules="rules"
          label-width="130px">
          <el-form-item label="料号"
            prop="prdCode">
            <el-input v-model="formData.prdCode"
              placeholder="请输入料号"
              @input="getPrdName" />
          </el-form-item>
          <!-- 输入完料号显示品名和规格 -->
          <el-form-item label="品名"
            prop="prdName">
            <el-input v-model="formData.prdName"
              placeholder="输入料号后自动获取品名"
              disabled />
          </el-form-item>
          <el-form-item label="批号"
            prop="manufactureBatchNo">
            <el-input v-model="formData.manufactureBatchNo"
              placeholder="请输入批号" />
          </el-form-item>
          <el-form-item label="厂家"
            prop="manufacturersName">
            <el-input v-model="formData.manufacturersName"
              placeholder="请输入厂家" />
          </el-form-item>
          <el-form-item label="发货时间"
            prop="shipDate">
            <el-date-picker v-model="formData.shipDate"
              type="date"
              clearable
              placeholder="请选择发货时间" />
          </el-form-item>
          <!-- 上传 PDF / 图片 -->
          <el-form-item label="上传 PDF / 图片"
            prop="file">
            <el-upload v-model:file-list="formData.fileList"
              class="upload-demo"
              action="#"
              accept="application/pdf, image/*"
              :http-request="httpRequestFn"
              :limit="1">
              <el-button size="small"
                type="primary">
                点击上传
              </el-button>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button type="primary"
            @click="submitForm">
            确定
          </el-button>
        </template>
      </el-dialog>

      <!-- 图片预览弹窗 -->
      <el-dialog v-model="imagePreviewVisible" 
        title="质量检测报告预览" 
        width="60%"
        center>
        <div style="text-align: center;">
          <img :src="previewImageUrl" 
            style="max-width: 100%; max-height: 600px;"
            alt="质量检测报告" />
        </div>
        <template #footer>
          <el-button @click="imagePreviewVisible = false">关闭</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { getQualityInsPageList, uploadFileToOSSAPI, postQualityIns, getProductNameByCode } from '@/api'
import useUserStore from '@/store/modules/user'
import { v4 as uuidv4 } from 'uuid'
import { getFileTypeExt, parseTime } from '@/utils'
const { proxy } = getCurrentInstance()

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
})
// 根据料号获取品名
const getPrdName = async () => {
  const { data } = await getProductNameByCode(formData.prdCode)
  formData.prdName = data?.prdName || ''
}

const tableList = ref([])
const total = ref(0)
const getList = async () => {
  const { data } = await getQualityInsPageList(queryParams)
  // 格式化发货时间
  tableList.value = data?.rows?.map(item => ({
    ...item,
    shipDate: item.shipDate ? parseTime(item.shipDate, `{y}-{m}-{d}`) : '',
  })) || []
  total.value = data.total || 0
}
getList()

const dialogVisible = ref(false)
const formData = reactive({
  fileList: [],
})
const rules = reactive({
  activityDate: [
    { required: true, message: '请选择活动日期', trigger: 'blur' },
  ],
})
// 图片预览相关状态
const imagePreviewVisible = ref(false)
const previewImageUrl = ref('')

// 判断文件类型
const isImageFile = (url) => {
  if (!url) return false
  const imageExtensions = ['.png', '.jpg', '.jpeg', '.gif', '.bmp', '.webp', '.svg']
  return imageExtensions.some(ext => url.toLowerCase().includes(ext))
}

const isPdfFile = (url) => {
  if (!url) return false
  return url.toLowerCase().includes('.pdf')
}

// 获取链接文本
const getReportLinkText = (url) => {
  if (isImageFile(url)) {
    return '预览图片'
  } else if (isPdfFile(url)) {
    return '查看报告'
  } else {
    return '查看报告'
  }
}

// 处理报告点击事件
const handleReportClick = (url) => {
  if (isImageFile(url)) {
    // 图片文件：预览
    previewImage(url)
  } else if (isPdfFile(url)) {
    // PDF文件：打开新链接
    // 把 url 的域名替换掉，改成自己的然后拼接原来的资源路径
    const originDomain = import.meta.env.VITE_APP_OSS_ORIGIN_DOMAIN
    const customDomain = import.meta.env.VITE_APP_OSS_CUSTOM_DOMAIN
    url = url.replace(originDomain, customDomain)
    window.open(url, '_blank')
  } else {
    // 其他文件类型：默认打开新链接
    window.open(url, '_blank')
  }
}

// 预览图片方法
const previewImage = (url) => {
  previewImageUrl.value = url
  imagePreviewVisible.value = true
}

const submitForm = async () => {
  proxy.$refs.formRef.validate(async (valid) => {
    if (valid) {
      dialogVisible.value = false
      // 提交表单
      const formDataToSubmit = {
        ...formData,
        qualityUrl: formData.fileList[0].url,
      }
      await postQualityIns(formDataToSubmit)
      proxy.$message({
        message: '新增成功',
        type: 'success',
      })
      getList()
      // 清空表单
      formData.fileList = []
      proxy.$refs.formRef.resetFields()
    } else {
      console.log('校验失败')
    }
  })
}

const httpRequestFn = async (file) => {
  const date = new Date()
  const month = date.getMonth() + 1
  const url = await uploadFileToOSSAPI(`licenses/qualityIns/${date.getFullYear()}-${month}/${useUserStore().empInfo.empNo}/${uuidv4()}.${getFileTypeExt(file.file.name)}`, file.file)
  formData.fileList[0].url = url
}
</script>

<style scoped
  lang="scss">
  .el-table {
    margin-top: 20px;
  }
</style>