<template>
  <div class="archive-list">
    <div v-if="activeTab == 'list'">
      <!-- 搜索表单 -->
      <div class="search-panel">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="年度:" prop="projectYear">
            <el-date-picker
              v-model="searchForm.projectYear"
              type="year"
              placeholder="选择年"
              format="yyyy"
              value-format="yyyy"
            ></el-date-picker>
          </el-form-item>

          <el-form-item label="地区:" prop="areaCode">
            <el-cascader
              v-model="searchForm.areaCode"
              :options="districtTree"
              :props="districtTreeCascaderProps"
              :show-all-levels="false"
              clearable
              placeholder="请选择地区"
              style="width: 200px"
            ></el-cascader>
          </el-form-item>

          <el-form-item label="卷宗号:" prop="archiveNo">
            <el-input
              v-model="searchForm.archiveNo"
              placeholder="请输入卷宗号"
              clearable
              style="width: 200px"
            ></el-input>
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              @click="handleSearch"
            >
              查询
            </el-button>
            <el-button
              plain
              type="primary"
              icon="el-icon-refresh"
              @click="handleReset"
            >
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        border
        row-key="id"
      >
        <el-table-column
          type="index"
          label="序号"
          width="60"
          header-align="center"
          align="center"
        />
        <el-table-column
          prop="year"
          label="立项年度"
          width="100"
          header-align="center"
          align="center"
        />
        <el-table-column
          prop="areaName"
          label="立项地区"
          width="100"
          header-align="center"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="archiveNo"
          label="卷宗号"
          width="150"
          header-align="center"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          prop="projectName"
          label="成本监审项目名称"
          show-overflow-tooltip
          header-align="center"
          align="left"
          min-width="170"
        >
          <template slot-scope="scope">
            <div class="cell-content cell-content--left">
              <span class="project-link" @click="handleDetail(scope.row)">
                {{ scope.row.projectName }}
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="auditedUnitName"
          label="监审对象"
          header-align="center"
          align="left"
          min-width="150"
        />
        <el-table-column
          prop="auditPeriod"
          label="监审期间"
          header-align="center"
          align="center"
          width="150"
        />
        <el-table-column
          prop="archiveUser"
          label="归档人"
          width="100"
          header-align="center"
          align="center"
        />
        <el-table-column label="操作" align="center" width="250" fixed="right">
          <template slot-scope="scope">
            <span class="action-buttons">
              <el-button
                type="text"
                size="small"
                @click="handleView(scope.row)"
              >
                任务详情
              </el-button>
              <el-button
                type="text"
                size="small"
                @click="handleArchivePreview(scope.row)"
              >
                档案详情
              </el-button>
              <el-button
                type="text"
                size="small"
                @click="handleDownload(scope.row)"
              >
                下载
              </el-button>
            </span>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin-top: 10px"
        background
        layout="total, sizes, prev, pager, next"
        :current-page="pagination.currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pagination.pageSize"
        :total="pagination.total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </div>
    <!-- 任务详情弹窗 -->
    <taskDetail ref="taskDetail" />

    <!-- 档案详情预览弹窗 -->
    <el-dialog
      :visible.sync="previewDialogVisible"
      width="65%"
      title="档案详情预览"
      :close-on-click-modal="false"
    >
      <div class="preview-container">
        <iframe
          v-if="previewUrl"
          :src="previewUrl"
          frameborder="0"
          class="preview-iframe"
        ></iframe>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import taskDetail from '@/components/task/taskDetail.vue'
  import { getArchiveList } from '@/api/audit/archive'
  import { getSysPropertiesAlias } from '@/api/properties'
  import { regionMixin } from '@/mixins/useDict'
  export default {
    name: 'ArchiveList',
    components: {
      taskDetail,
    },
    mixins: [regionMixin],
    data() {
      return {
        searchForm: {
          projectYear: '2025',
          areaCode: [],
          archiveNo: '',
        },
        loading: false,
        tableData: [],
        // 分页配置
        pagination: {
          currentPage: 1,
          pageSize: 10,
          total: 0,
        },
        activeTab: 'list',
        // 系统属性值
        sysKkUrl: '',
        // 预览对话框
        previewDialogVisible: false,
        previewUrl:
          'http://1.71.9.215:8012/onlinePreview?url=aHR0cDovLzEuNzEuOS4yMTU6ODAxMi9kZW1vL%2BWNt%2BWul18xOTk5MzA5NDM3MzY2NTQyMzM2XzIwMjUxMjEyMTQwNjI4XzM5MygxKS5kb2N4',
      }
    },
    created() {
      this.fetchData()
      this.getSysKkUrl()
    },
    methods: {
      // 获取数据
      async fetchData() {
        try {
          this.loading = true
          const params = {
            currentPage: this.pagination.currentPage,
            pageSize: this.pagination.pageSize,
            projectYear: this.searchForm.projectYear,
            areaCode:
              this.searchForm.areaCode && this.searchForm.areaCode.length > 0
                ? this.searchForm.areaCode[this.searchForm.areaCode.length - 1]
                : '',
            archiveNo: this.searchForm.archiveNo,
            isGd: 1, // 已归档
          }
          const response = await getArchiveList(params)

          // 根据API返回格式处理数据
          if (response && response.value) {
            // 获取记录列表
            const records = response.value.records || []

            // 转换数据格式
            this.tableData = records
            // 设置总数
            this.pagination.total = response.value.total || 0
            // 批量获取区域名称
            this.fetchRegionNames(this.tableData, 'region')
          } else {
            this.tableData = []
            this.pagination.total = 0
          }
        } catch (error) {
          // this.$message.error('加载列表失败')
          console.error('加载列表失败:', error)
          this.tableData = []
          this.pagination.total = 0
        } finally {
          this.loading = false
        }
      },
      handleSearch() {
        this.pagination.currentPage = 1
        this.fetchData()
      },
      handleReset() {
        this.searchForm = {
          projectYear: '2025',
          areaCode: [],
          archiveNo: '',
        }
        this.pagination.currentPage = 1
        this.fetchData()
      },
      // 处理分页变化
      handleCurrentChange(current) {
        this.pagination.currentPage = current
        this.fetchData()
      },
      handleSizeChange(size) {
        this.pagination.pageSize = size
        this.pagination.currentPage = 1
        this.fetchData()
      },
      handleDetail(row) {
        // 打开任务详情弹窗
        this.$refs.taskDetail.open(row, 'chengben')
      },
      // 获取系统属性值 sys.kk.url
      async getSysKkUrl() {
        try {
          const response = await getSysPropertiesAlias('sys_kk_url')
          if (response) {
            this.sysKkUrl = response
          }
        } catch (error) {
          console.error('获取系统属性值失败:', error)
        }
      },
      handleView(row) {
        // 打开任务详情弹窗
        this.$refs.taskDetail.open(row, 'chengben')
      },
      handleDownload(row) {
        // 下载操作
        if (!row.archiveUrl) {
          this.$message.error('文件下载地址不存在')
          return
        }
        try {
          // 创建a标签进行下载
          const link = document.createElement('a')
          link.style.display = 'none'
          link.href = row.archiveUrl
          // 从URL中提取文件名或使用默认文件名
          const fileName =
            row.archiveUrl.split('/').pop() || `archive_${new Date().getTime()}`
          link.download = fileName
          document.body.appendChild(link)
          link.click()
          // 移除a标签
          document.body.removeChild(link)
          this.$message.success('文件下载成功')
        } catch (error) {
          console.error('下载失败:', error)
          this.$message.error('文件下载失败')
        }
      },
      // 档案详情预览
      handleArchivePreview(row) {
        if (!row.archiveUrl) {
          this.$message.error('文件预览地址不存在')
          return
        }
        console.log('http://1.71.9.215:9506' + row.archiveUrl)
        // 拼接预览URL
        this.previewUrl =
          this.sysKkUrl +
          encodeURIComponent(
            Base64.encode(
              'http://1.71.9.215:9506/profile/upload/20251211/1111、中止定价成本监审通知书_20251211091528_49.docx'
            )
          )
        alert(this.previewUrl)
        // 打开预览弹窗
        this.previewDialogVisible = true
      },
      backToList() {
        this.activeTab = 'list'
      },
    },
  }
</script>

<style scoped lang="scss">
  .archive-list {
    padding: 20px;
  }

  .action-buttons {
    display: inline-flex;
    gap: 8px;
  }

  .action-link {
    color: #409eff;
    cursor: pointer;
    text-decoration: none;
    transition: color 0.3s;

    &:hover {
      color: #66b1ff;
      text-decoration: underline;
    }
  }

  .project-link {
    color: #409eff;
    cursor: pointer;
    text-decoration: none;
    transition: color 0.3s;

    &:hover {
      color: #66b1ff;
      text-decoration: underline;
    }
  }

  .preview-container {
    width: 100%;
    height: 600px;
  }

  .preview-iframe {
    width: 100%;
    height: 100%;
  }
</style>
