<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="productCode" size="small" placeholder="模糊查询" clearable style="width: 160px"/>
        <span style="margin-left: 10px">备注：</span>
        <el-input v-model="remark" size="small" placeholder="模糊查询" clearable style="width: 160px"/>
        <span style="margin-left: 10px">图片名称：</span>
        <el-input v-model="imageName" 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>
        <el-button type="info" plain size="small" icon="el-icon-refresh" style="margin-left: 4px" @click="resetFilter">重置</el-button>
      </div>

      <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="备注" min-width="180" show-overflow-tooltip/>
        <el-table-column prop="图片名称" label="图片名称" min-width="200" show-overflow-tooltip/>
        <el-table-column prop="操作时间" label="操作时间" width="170" align="center"/>
        <el-table-column label="操作" width="140" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="preview(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-card>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'CheckImageSearch',
  data() {
    return {
      loading: false,
      tableData: [],
      total: 0,
      pageSize: 50,
      pageCurrent: 1,
      dateRange: [],
      productCode: '',
      remark: '',
      imageName: '',
      // 图片接口（CheckImageController）
      imageApiBase: window.g.webAPIURL + '/api/checkimage/'
    }
  },
  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.productCode = ''
      this.remark = ''
      this.imageName = ''
      this.pageCurrent = 1
      this.searchTable()
    },
    // 列表分页查询（XD_检测图片上传_分页查询）
    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.productCode || '']
      param[3] = ['备注', this.remark || '']
      param[4] = ['图片名称', this.imageName || '']
      param[5] = ['PageCurrent', this.pageCurrent]
      param[6] = ['PageSize', this.pageSize]
      param[7] = ['PageCount', '1111', 'int', '1']
      param[8] = ['ItemCount', '1111', 'int', '1']
      const Data = this.CreateData('11', 'XD_检测图片上传_分页查询', 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()
    },
    // 图片预览（新窗口打开）
    preview(row) {
      if (!row || !row.图片路径) {
        this.$message.warning('无效的图片路径')
        return
      }
      const body = { Path: row.图片路径 }
      axios.post(this.imageApiBase + 'download', body, { responseType: 'blob' })
        .then(resp => {
          const contentType = resp.headers && (resp.headers['content-type'] || resp.headers['Content-Type'])
          const blob = new Blob([resp.data], { type: contentType || 'image/jpeg' })
          const url = window.URL.createObjectURL(blob)
          window.open(url, '_blank')
          // 不立即 revoke，交给浏览器回收，避免新窗口还未读取
        }).catch(() => this.$message.error('预览失败'))
    },
    // 图片下载
    download(row) {
      if (!row || !row.图片路径) {
        this.$message.warning('无效的图片路径')
        return
      }
      const body = { Path: row.图片路径 }
      axios.post(this.imageApiBase + '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>

