<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" size="small" :inline="true" label-width="68px">
      <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-table v-loading="loading" :data="submissionsList" @selection-change="handleSelectionChange">
      <el-table-column label="报表名称" align="center" prop="reportName" />
      <el-table-column label="学期" align="center" prop="term_id">
        <template slot-scope="scope">
          <div v-for="item in yearOptions" :key="item.id">
            <span v-if="scope.row.term_id == item.id">
              {{ item.termName }}
            </span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <el-tag
            :type="getStatusType(scope.row.status)"
            :effect="getStatusEffect(scope.row.status)"
          >
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </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-edit"
            @click="handleFillReport(scope.row)"
          >合格标准填写</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 全屏弹窗 -->
    <el-dialog
      title="合格标准填写"
      :visible.sync="dialogVisible"
      fullscreen
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <!-- 引入诊断报告明细组件 -->
      <DiagnosticDetails
        :report-data="currentReport"
        @submission-success="handleSubmissionSuccess"
      />
    </el-dialog>

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

<script>
import { listSubmissions } from '@/api/diagnostic/submissions'
import { getInfoId } from '@/api/diagnostic/info'
import { getTerm } from '@/api/diagnostic/DiaReportRelease'
import DiagnosticDetails from '@/views/diagnostic/details/index'

export default {
  name: 'Submissions',
  components: {
    DiagnosticDetails
  },
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      submissionsList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        reportName: null,
        term_id: null,
      },
      yearOptions: [],
      dialogVisible: false,
      currentReport: {},
      formData: {
        content: '',
      },
    }
  },
  created() {
    this.getList()
    this.getTermOptions()
  },
  methods: {
    /** 查询学生报提交记录列表 */
    getList() {
      this.loading = true
      listSubmissions(this.queryParams).then(response => {
        this.submissionsList = response.rows
        this.loadSubmittedStatus() // 加载本地保存的提交状态
        this.total = response.total
        this.loading = false
      }).catch(error => {
        console.error('获取提交记录失败', error)
        this.loading = false
        this.$message.error('获取提交记录失败')
      })
    },

    /** 处理分页事件 */
    handlePagination(pagination) {
      this.queryParams.pageNum = pagination.page
      this.queryParams.pageSize = pagination.limit
      this.getList()
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 获取学期选项数据 */
    getTermOptions() {
      getTerm().then(response => {
        this.yearOptions = response.data
      }).catch(error => {
        console.error('获取学期选项失败', error)
        this.$message.error('获取学期数据失败')
      })
    },

    /** 填写报表按钮操作 */
    handleFillReport(row) {
      this.currentReport = row // 存储当前报表数据
      // 调用getInfoId方法
      getInfoId(row.relId).then(response => {
        console.log(response)
      }).catch(error => {
        console.error('获取信息ID失败', error)
        this.$message.error('获取信息ID失败')
      })
      this.dialogVisible = true // 打开全屏弹窗
    },

    /** 提交表单 */
    submitForm() {
      this.$message.success('提交成功!')
      this.dialogVisible = false
    },

    /** 关闭弹窗时重置表单 */
    handleDialogClose() {
      this.formData.content = '' // 清空表单
    },

    // ====================== 新增状态管理逻辑 ======================
    /** 处理子组件提交成功事件 */
    handleSubmissionSuccess(reportId) {
      // 更新内存中的状态
      const index = this.submissionsList.findIndex(item => item.id === reportId)
      if (index !== -1) {
        this.$set(this.submissionsList[index], 'status', '2') // 状态码'2'表示已填写
        this.saveSubmittedStatus(reportId) // 保存到localStorage
        this.$message.success('状态已更新为"已填写"')
      }
    },

    /** 保存提交状态到localStorage */
    saveSubmittedStatus(reportId) {
      try {
        const submittedReports = JSON.parse(localStorage.getItem('submittedReports')) || {}
        submittedReports[reportId] = true
        localStorage.setItem('submittedReports', JSON.stringify(submittedReports))
      } catch (error) {
        console.error('保存提交状态失败:', error)
      }
    },

    /** 从localStorage加载提交状态 */
    loadSubmittedStatus() {
      try {
        const submittedReports = JSON.parse(localStorage.getItem('submittedReports')) || {}
        this.submissionsList = this.submissionsList.map(item => {
          return {
            ...item,
            status: submittedReports[item.id] ? '2' : item.status // 若已提交,设置状态为'2'
          }
        })
      } catch (error) {
        console.error('加载提交状态失败:', error)
      }
    },

    // ====================== 状态显示辅助方法 ======================
    /** 获取状态文本 */
    getStatusText(status) {
      const statusMap = {
        '0': '填写中',
        '1': '停用',
        '2': '已填写'
      }
      return statusMap[status] || '未知状态'
    },

    /** 获取状态标签类型 */
    getStatusType(status) {
      const typeMap = {
        '0': 'success', // 填写中:绿色
        '1': 'danger', // 停用:红色
        '2': 'primary'  // 已填写:蓝色
      }
      return typeMap[status] || 'info'
    },

    /** 获取状态标签效果 */
    getStatusEffect(status) {
      return status === '2' ? 'light' : 'dark' // 已填写使用浅色标签
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}
</style>