<template>
  <div class="app-container">
    <el-card class="topCard">
      <div class="topDiv">
        <span>时间：</span>
        <el-date-picker
          v-model="dateRange"
          :clearable="false"
          align="center"
          end-placeholder="结束日期"
          format="yyyy-MM-dd"
          range-separator="～"
          size="small"
          start-placeholder="开始日期"
          style="width: 260px;"
          type="daterange"
          value-format="yyyy-MM-dd"/>
        <span style="margin-left: 10px">工序：</span>
        <el-input v-model="processName" size="small" placeholder="工序名称(可空)" clearable style="width: 160px"/>
        <span style="margin-left: 10px">文件名称：</span>
        <el-input v-model="fileName" size="small" placeholder="模糊查询" clearable style="width: 180px"/>
        <el-button type="primary" plain size="small" icon="el-icon-search" style="margin-left: 8px" @click="pageCurrent=1;searchTable()">查询</el-button>
      </div>

      <el-row :gutter="10">
        <el-col :span="18">
          <el-table
            v-loading="loading"
            :data="tableData"
            border
            size="mini"
            height="700"
            style="width: 100%">
            <el-table-column type="index" width="60" label="序号" align="center"/>
            <el-table-column prop="订单号" label="订单号" width="200" align="center"/>
            <el-table-column prop="工位号" label="工位号" width="100" align="center"/>
            <el-table-column prop="工序名称" label="工序名称" width="160" align="center"/>
            <el-table-column prop="文件名称" label="文件名称" min-width="180" show-overflow-tooltip/>
            <el-table-column prop="产品名称" label="产品名称" width="180" align="center"/>
            <el-table-column prop="操作时间" label="操作时间" width="170" align="center"/>
            <el-table-column label="操作" width="100" align="center" fixed="right">
              <template slot-scope="scope">
                <!-- <el-button size="mini" type="text" @click="handleFileClick(scope.row)">
                  <i class="el-icon-view" style="margin-right:4px;"></i>查看文件
                </el-button> -->
                <el-button size="mini" type="text" @click="download(scope.row)">
                  <i class="el-icon-download" style="margin-right:4px;"></i>下载文件
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="block" style="margin-top: 10px;">
            <el-pagination
              v-if="!loading"
              :current-page="pageCurrent"
              :page-sizes="[30, 50, 100, 200]"
              :page-size="pageSize"
              :total="total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"/>
          </div>
        </el-col>
        <!-- <el-col :span="10">
          <div style="padding-left: 10px;">
           Removed FilePreview component 
          </div>
        </el-col> -->
      </el-row>
    </el-card>
  </div>
  </template>

<script>
import axios from 'axios'

export default {
  name: 'CardFileSearch',
  // components: { FilePreview }, // 移除组件注册
  data() {
    return {
      loading: false,
      tableData: [],
      total: 0,
      pageSize: 50,
      pageCurrent: 1,
      dateRange: [],
      processName: '',
      fileName: '',
      // 右侧预览
      // fileInfo: null, // 移除预览文件对象
      // fileLoading: false, // 移除预览加载状态
      // 后端文件接口（CraftFileController）
      fileApiBase: window.g.webAPIURL + '/api/craftfile/'
    }
  },
  created() {
    const end = new Date()
    const start = new Date()
    start.setDate(start.getDate() - 7)
    const fmt = (d) => {
      const y = d.getFullYear()
      const m = (d.getMonth() + 1).toString().padStart(2, '0')
      const da = d.getDate().toString().padStart(2, '0')
      return `${y}-${m}-${da}`
    }
    this.dateRange = [fmt(start), fmt(end)]
    this.searchTable()
  },
  methods: {
    resetFilter() {
      this.processName = ''
      this.fileName = ''
      this.pageCurrent = 1
      this.searchTable()
    },
    // 列表分页查询（MOM_工艺信息_工艺文件_视图）
    searchTable() {
      if (!this.dateRange || this.dateRange.length !== 2) {
        this.$message.warning('请选择时间范围')
        return
      }
      this.loading = true
      this.tableData = []
      const param = []
      param[0] = ['开始时间', this.dateRange[0] + ' 00:00:00']
      param[1] = ['结束时间', this.dateRange[1] + ' 23:59:59']
      param[2] = ['工序名称', this.processName || '']
      param[3] = ['文件名称', this.fileName || '']
      param[4] = ['PageCurrent', this.pageCurrent]
      param[5] = ['PageSize', this.pageSize]
      param[6] = ['PageCount', '1111', 'int', '1']
      param[7] = ['ItemCount', '1111', 'int', '1']
      const Data = this.CreateData('11', 'MOM_工艺信息_工艺文件_视图_分页查询', param)
      this.ExecDatabase(Data).then(res => {
        let rows = []
        if (res && res.data) {
          if (Array.isArray(res.data)) rows = res.data
          else if (res.data.result && Array.isArray(res.data.result)) rows = res.data.result
        }
        this.tableData = rows || []
        let total = 0
        if (res && res.data && Array.isArray(res.data.output) && res.data.output.length > 0) {
          total = parseInt(res.data.output[0].ItemCount || 0)
        }
        this.total = total
      }).finally(() => {
        this.loading = false
      })
    },
    handleSizeChange(val) {
      this.pageCurrent = 1
      this.pageSize = val
      this.searchTable()
    },
    handleCurrentChange(val) {
      this.pageCurrent = val
      this.searchTable()
    },
    // 处理文件点击事件 - 优先预览
    handleFileClick(row) {
      this.preview(row)
    },
    // 预览文件（优先使用后端browse返回的dataUrl/base64），否则走流式预览
    preview(row) {
      if (!row || !row.文件地址) {
        this.$message.warning('无效的文件路径')
        return
      }
      const body = { RelativePath: row.文件地址 }
      axios.post(this.fileApiBase + 'browse', body).then(resp => {
        const data = resp && resp.data ? resp.data : null
        if (!data || data.success === false) {
          // 降级为流式预览
          const url = this.fileApiBase + 'preview?path=' + encodeURIComponent(row.文件地址)
          window.open(url, '_blank')
          return
        }
        const contentType = (data.contentType || '').toLowerCase()
        const isPdf = contentType.indexOf('pdf') !== -1 || (row.文件名称 || '').toLowerCase().endsWith('.pdf')
        // 有直链 dataUrl 则直接打开
        if (data.dataUrl) {
          window.open(data.dataUrl, '_blank')
          return
        }
        // 有 base64 时，转 Blob 再打开（参考 PdfCardMaintenance 的实现）
        if (data.base64Data && contentType) {
          try {
            const url = this.buildBlobUrlFromBase64(data.base64Data, contentType)
            window.open(url, '_blank')
            // 不 revoke，避免新窗口读取失败，交给浏览器回收
            return
          } catch (e) {
            // 失败则继续降级
          }
        }
        // 最后降级：直连流式预览（支持 Range）
        const url = this.fileApiBase + 'preview?path=' + encodeURIComponent(row.文件地址)
        window.open(url, '_blank')
      }).catch(() => {
        const url = this.fileApiBase + 'preview?path=' + encodeURIComponent(row.文件地址)
        window.open(url, '_blank')
      })
    },
    buildBlobUrlFromBase64(base64, contentType) {
      const binary = atob(base64)
      const len = binary.length
      const bytes = new Uint8Array(len)
      for (let i = 0; i < len; i++) bytes[i] = binary.charCodeAt(i)
      const blob = new Blob([bytes], { type: contentType || 'application/octet-stream' })
      return window.URL.createObjectURL(blob)
    },
    // 处理文件下载
    handleDownload(row) {
      const fileName = row.文件名称
      const filePath = row.文件地址
      const url = `${this.fileApiBase}download?path=${encodeURIComponent(filePath)}`
      window.open(url, '_blank')
    },
    // 下载（POST，保留原有逻辑）
    download(row) {
      const body = { RelativePath: row.文件地址 }
      axios.post(this.fileApiBase + 'download', body, { responseType: 'blob' })
        .then(resp => {
          const contentDisposition = resp.headers && (resp.headers['content-disposition'] || resp.headers['Content-Disposition'])
          let filename = (row.文件名称 || '文件')
          if (contentDisposition) {
            const match = /filename\*=UTF-8''([^;]+)|filename="?([^";]+)"?/i.exec(contentDisposition)
            if (match) filename = decodeURIComponent(match[1] || match[2] || filename)
          }
          const blob = new Blob([resp.data])
          const url = window.URL.createObjectURL(blob)
          const a = document.createElement('a')
          a.href = url
          a.download = filename
          document.body.appendChild(a)
          a.click()
          document.body.removeChild(a)
          window.URL.revokeObjectURL(url)
        }).catch(() => this.$message.error('下载失败'))
    }
  }
}
</script>

<style scoped>
.topCard {
  margin: 5px;
}

.topDiv {
  margin-bottom: 10px;
}
</style>
