<template>
  <div class="app-container">
    <el-form ref="queryForm" :model="queryParams" size="small" :inline="true" label-width="140px">
      <el-form-item label="学号" prop="stuNo">
        <el-input v-model="queryParams.stuNo" placeholder="请输入学号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="姓名" prop="stuName">
        <el-input v-model="queryParams.stuName" placeholder="请输入姓名" clearable
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="班级" prop="className">
        <el-input v-model="queryParams.className" placeholder="请输入班级" clearable
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <!-- <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="">批量通过</el-button> -->
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出execl</el-button>
      </el-col>
    </el-row>
    <el-table v-loading="loading" :data="tableData">
      <el-table-column label="#" align="center" prop="id" />
      <el-table-column label="学年" align="center" prop="stuYearName" />
      <el-table-column label="班级" align="center" prop="className" />
      <el-table-column label="学号" align="center" prop="stuNo" />
      <el-table-column label="姓名" align="center" prop="stuName" />
      <el-table-column label="审核状态" align="center" prop="applyStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.knzz_tufa_apply_status" :value="scope.row.applyStatus" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="lookVClick(scope.row)">查看</el-button>
          <el-button v-if="scope.row.applyStatus != 1" size="mini" type="text" icon="el-icon-refresh-left" @click="handleRevoke(scope.row)">撤回</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize" @pagination="getList"
    />

    <el-dialog title="查看" :visible.sync="lookV" :fullscreen="true" :destroy-on-close="true" @close="getList">
      <el-row>
        <el-col :span="12">
          <TufaLook v-if="lookV" id="printDiv" :form-data="lookForm" />
        </el-col>
        <el-col :span="12">
          <el-form v-if="lookForm.applyFile" label-width="120px">
            <el-form-item label="证明材料">
              <el-button type="primary" size="mini" icon="el-icon-download" @click="downloadDiploma">下载文件</el-button>
            </el-form-item>
            <FileUpload v-model="lookForm.applyFile" />
          </el-form>
          <el-button v-print="printContent">打印</el-button>
          <hr>
          <el-timeline>
            <el-timeline-item v-if="lookForm.fdyCmt && lookForm.fdyDate" :timestamp="lookForm.fdyDate"
                              color="green" placement="top"
            >
              <el-card>
                <div>
                  <strong>辅导员审核</strong>
                  <div>{{ lookForm.fdyCmt }}</div>
                  <img v-if="lookForm.fdySign" :src="baseurl + lookForm.fdySign" alt="辅导员签名"
                       style="max-width:100px;margin-top:8px;"
                  >
                </div>
              </el-card>
            </el-timeline-item>
            <el-timeline-item v-if="lookForm.xwCmt && lookForm.xwDate" :timestamp="lookForm.xwDate"
                              color="green" placement="top"
            >
              <el-card>
                <div>
                  <strong>院系审核</strong>
                  <div>{{ lookForm.xwCmt }}</div>
                  <img v-if="lookForm.xwSign" :src="baseurl + lookForm.xwSign" alt="院系签名"
                       style="max-width:100px;margin-top:8px;"
                  >
                </div>
              </el-card>
            </el-timeline-item>
            <el-timeline-item v-if="lookForm.xgCmt && lookForm.xgDate" :timestamp="lookForm.xgDate"
                              color="green" placement="top"
            >
              <el-card>
                <div>
                  <strong>学工审核</strong>
                  <div>{{ lookForm.xgCmt }}</div>
                  <img v-if="lookForm.xgSign" :src="baseurl + lookForm.xgSign" alt="学工签名"
                       style="max-width:100px;margin-top:8px;"
                  >
                </div>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </el-col>
      </el-row>

    </el-dialog>


  </div>
</template>
<script>

import {boolImg, CheckImgExists, isEmpty, fullLoading} from '@/api/helpFunc'
import {getTokenKeySessionStorage as getToken} from '@/utils/auth'


import TufaApply from '@/views/comprehensive/knzzZzqApply/cpnt/TufaApply.vue'
import TufaLook from '@/views/comprehensive/knzzZzqApply/cpnt/TufaLook.vue'

import {listFdyAll as listView, doEdit} from '@/api/comprehensive/knzzZzqApply'

import {getOwnSign} from '@/api/workstudy/post'

export default {
  name: 'TufaFdy',
  dicts: ['knzz_tufa_apply_status'],
  components: {
    TufaApply,
    TufaLook
  },
  data() {
    return {
      loading: true,
      tableData: [],
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,

      },

      lookForm: {},
      lookV: false,

      upload: {
        headers: {Authorization: 'Bearer ' + getToken()},
        url: process.env.VUE_APP_BASE_API + '/common/upload',
        fileList: []
      },
      baseurl: process.env.VUE_APP_BASE_API + '/',
      boolImg,

      printContent: {
        id: 'printDiv',
        extraCss: '',
        extraHead: '<meta http-equiv="Content-Language"content="zh-cn"/>',
        previewBeforeOpenCallback() {
          console.log('正在加载预览窗口')
        },
        previewOpenCallback() {
          console.log('已经加载完预览窗口')
        },
        beforeOpenCallback(vue) {
          vue.printLoading = true
          console.log('打开之前')
        },
        openCallback(vue) {
          vue.printLoading = false
          console.log('执行了打印')
        },
        closeCallback() {
          console.log('关闭了打印工具')
        },
        clickMounted(vue) {
          console.log('点击了打印按钮')
        }
      },

    }
  },
  created() {
    this.getList()
  },
  methods: {
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },

    async getList() {
      this.loading = true
      let res = await listView(this.queryParams)
      this.loading = false
      if (res.code == 200) {
        this.tableData = [...res.rows]
        this.total = res.total
      }

    },
    async lookVClick(row) {
      console.log(row)
      this.lookForm = {}
      this.lookForm = {...row}

      this.lookV = true
    },
    // 撤回到“已提交审核”（applyStatus=1）
    async handleRevoke(row) {
      try {
        await this.$confirm('确定撤回该申请至“已提交审核”状态吗？', '提示', { type: 'warning' })
      } catch (e) {
        return
      }
      const loading = this.$loading({ lock: true, text: '撤回中…' })
      try {
        const payload = { id: row.id, applyStatus: 1 }
        const res = await doEdit(payload)
        if (res.code === 200) {
          this.$message.success('撤回成功，状态已变更为：已提交审核')
          this.getList()
        } else {
          this.$message.error(res.msg || '撤回失败')
        }
      } catch (err) {
        this.$message.error(`撤回失败：${err?.message || '网络错误'}`)
      } finally {
        loading.close && loading.close()
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('/comprehensive/knzzZzqApply/export', {
        ...this.queryParams
      }, `apply_${new Date().getTime()}.xlsx`)
    },
    downloadDiploma() {
      const raw = this.lookForm.applyFile
      if (!raw) return
      // 支持逗号分隔的多个文件
      const files = String(raw)
        .split(',')
        .map((s) => s.trim())
        .filter(Boolean)

      const triggerDownload = (href, filename) => {
        const link = document.createElement('a')
        link.href = href
        // 设置下载文件名（跨域时可能被浏览器忽略，但不影响触发下载/打开）
        link.download = filename || ''
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      }

      files.forEach((file, idx) => {
        const isAbsoluteUrl = /^https?:\/\//i.test(file)
        const url = isAbsoluteUrl ? file : `${this.baseurl}${file}`
        const name = this.getFileName(file)
        // 轻微延时，避免浏览器对一次事件同时触发多个下载的限制
        setTimeout(() => triggerDownload(url, name), idx * 200)
      })
    },
  }
}

</script>
<style scoped lang="scss">
.lookForm {
  .el-form-item {
    margin-bottom: 5px;
  }
}
</style>
