<template>
  <div class="app-container">
    <div class="container">
      <!-- 查询表单 -->
      <el-form :model="queryParams"
        inline
        label-position="left"
        v-show="showSearch">
        <el-form-item label="商品料号/名称"
          prop="prdCN">
          <el-input v-model="queryParams.prdCN"
            placeholder="请输入商品料号/名称"
            clearable
            @input="getList" />
        </el-form-item>
        <el-form-item label="批号"
          prop="manufactureBatchNoLike">
          <el-input v-model="queryParams.manufactureBatchNoLike"
            placeholder="请输入批号"
            clearable
            @input="getList" />
        </el-form-item>
        <el-form-item label="厂家名称"
          prop="manufacturersNameLike">
          <el-input v-model="queryParams.manufacturersNameLike"
            placeholder="请输入厂家名称"
            clearable
            @input="getList" />
        </el-form-item>
        <el-form-item label="发货日期"
          prop="shipDate">
          <el-date-picker v-model="queryParams.shipDate"
            placeholder="请选择发货日期"
            clearable
            type="date"
            @change="getList" />
        </el-form-item>
      </el-form>
      <!-- 功能按钮 -->
      <el-row justify="space-between">
        <el-col :span="12">
          <el-button type="primary"
            plain
            icon="Plus"
            @click="createClick">
            新增
          </el-button>
        </el-col>
        <el-col :span="12"
          class="right-col">
          <!-- 右边right-tool工具 -->
          <right-toolbar v-model:showSearch="showSearch"
            @queryTable="getList" />
        </el-col>
      </el-row>
      <!-- 表格列表 -->
      <el-table :data="tableList"
        style="width: 100%;"
        v-loading="loading">
        <el-table-column prop="prdCode"
          label="料号"
          width="140" />
        <el-table-column prop="prdName"
          label="产品名称"
          width="240" />
        <el-table-column prop="manufactureBatchNo"
          label="批号"
          width="160" />
        <el-table-column prop="manufacturersName"
          label="厂家" />
        <el-table-column prop="qualityUrl"
          label="质量检测报告">
          <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="发货时间" />
        <el-table-column prop="createTime"
          label="创建时间">
          <template #default="{ row }">
            {{ parseTime(row.createTime) }}
          </template>
        </el-table-column>
        <!-- 创建人 -->
        <el-table-column prop="createBy"
          label="创建人" />
        <!-- 修改者 -->
        <el-table-column prop="updateBy"
          label="修改人" />
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button type="primary"
              text
              @click="handleEditClick(row)">
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList" />
      <!-- 新增弹窗 -->
      <el-dialog :title="edit ? '编辑' : '新增'"
        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="fileList">
            <el-upload :file-list="formData.fileList"
              ref="uploadRef"
              class="upload-demo"
              action="#"
              accept="application/pdf, .jpg, .jpeg, .png, .webp, .zip, .rar, .7z"
              :http-request="httpRequestFn"
              :limit="1"
              :on-exceed="handleExceed"
              @remove="handleRemove">
              <el-button size="small"
                type="primary">
                点击上传
              </el-button>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="cancelForm">
            取消
          </el-button>
          <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, putQualityIns } 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 showSearch = ref(true)

const tableList = ref([])
const total = ref(0)
const loading = ref(false)
const getList = async () => {
  loading.value = true
  // 日期格式化
  if (queryParams.shipDate) {
    queryParams.shipDate = parseTime(queryParams.shipDate, `{y}/{m}/{d}`)
  }
  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
  loading.value = false
}
getList()

/*************** 新增/编辑 ***************/
const dialogVisible = ref(false)
const formData = reactive({
  fileList: [],
})
// 根据料号获取品名
const getPrdName = async () => {
  const { data } = await getProductNameByCode(formData.prdCode)
  formData.prdName = data?.prdName || ''
  proxy.$refs.formRef.validateField('prdName')
}
const rules = reactive({
  prdCode: [
    { required: true, message: '请输入料号', trigger: 'blur' },
  ],
  prdName: [
    { required: true, message: '请输入料号查询品名', trigger: 'blur' },
  ],
  manufactureBatchNo: [
    { required: true, message: '请输入批号', trigger: 'blur' },
  ],
  shipDate: [
    { required: true, message: '请选择发货时间', trigger: 'blur' },
  ],
  fileList: [
    { required: true, message: '请上传质量检测报告', trigger: 'change' },
  ]
})
// 取消
const cancelForm = () => {
  dialogVisible.value = false
  // 清空表单
  formData.fileList = []
  proxy.$refs.formRef.resetFields()
}
// 重置表单
const resetForm = () => {
  formData.fileList = []
  edit.value = false
  formData.zpqId = ''
  formData.prdCode = ''
  formData.prdName = ''
  formData.manufactureBatchNo = ''
  formData.shipDate = ''
}
// 新增-按钮
const createClick = () => {
  resetForm()
  edit.value = false
  dialogVisible.value = true
  nextTick(() => {
    // 清除校验信息
    proxy.$refs.formRef.clearValidate()
  })
}
// 提交
const submitForm = async () => {
  proxy.$refs.formRef.validate(async (valid) => {
    if (valid) {
      dialogVisible.value = false
      // 提交表单
      const formDataToSubmit = {
        ...formData,
        qualityUrl: formData.fileList[0]?.url,
      }
      // 编辑
      if (edit.value) {
        await putQualityIns(formDataToSubmit)
      } else {
        await postQualityIns(formDataToSubmit)
      }
      proxy.$message({
        message: edit.value ? '修改成功' : '新增成功',
        type: 'success',
      })
      getList()
      // 清空表单
      formData.fileList = []
      proxy.$refs.formRef.resetFields()
      edit.value = false
    }
  })
}

// 上传文件
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] = {
    name: file.file.name,
    url,
  }
  // 重新校验表单
  proxy.$refs.formRef.validateField('fileList')
}

// 替换文件
const uploadRef = ref(null)
const handleExceed = async (files) => {
  const file = files[0]
  uploadRef.value.clearFiles()
  formData.fileList = []
  httpRequestFn({ file })
}

// 编辑状态
const edit = ref(false)
// 编辑-点击
const handleEditClick = (row) => {
  edit.value = true
  formData.zpqId = row.zpqId
  formData.prdCode = row.prdCode
  formData.prdName = row.prdName
  formData.manufactureBatchNo = row.manufactureBatchNo
  formData.shipDate = row.shipDate
  formData.fileList = [{
    name: row.qualityUrl.split('/').pop(),
    url: row.qualityUrl
  }]

  dialogVisible.value = true
  nextTick(() => {
    proxy.$refs.formRef.validateField('fileList')
  })
}

// 删除文件
const handleRemove = (file, fileList) => {
  formData.fileList = fileList
}

/*************** 附件类型/预览 ***************/
// 图片预览相关状态
const imagePreviewVisible = ref(false)
const previewImageUrl = ref('')
// 判断文件类型
const isImageFile = (url) => {
  if (!url) return false
  const imageExtensions = ['.png', '.jpg', '.jpeg', '.webp']
  return imageExtensions.some(ext => url.toLowerCase().includes(ext))
}
const isPdfFile = (url) => {
  if (!url) return false
  return url.toLowerCase().includes('.pdf')
}
const isZipFile = (url) => {
  if (!url) return false
  const zipExtensions = ['.zip', '.rar', '.7z']
  return zipExtensions.some(ext => url.toLowerCase().includes(ext))
}
// 获取链接文本
const getReportLinkText = (url) => {
  if (isImageFile(url)) {
    return '预览图片'
  } else if (isPdfFile(url)) {
    return '查看报告'
  } else if (isZipFile(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
}
</script>

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

  ::v-deep(.el-upload-list__item-info) {
    width: auto !important;

    /* 覆盖el-upload文件名称样式，让宽度由内容撑开 */
    ::v-deep(.el-upload-list__item-file-name) {
      text-overflow: initial !important;
      overflow: visible !important;
      white-space: normal !important;
      white-space: nowrap !important;
      /* 关键：不换行 */
      max-width: none !important;
      width: auto !important;
      display: inline-block !important;
    }
  }

  /* 完成提示按钮 */
  ::v-deep(.el-upload-list__item-status-label) {
    right: auto !important;
  }

  /* 清除按钮 */
  ::v-deep(.el-icon--close) {
    right: auto !important;
  }

  /* 右侧工具按钮 */
  .right-col {
    display: flex;
    justify-content: flex-end;
  }
</style>