<template>
  <!-- 财务库页面 -->
  <el-card class="tool-container">
    <!-- 返回按钮 -->
    <div class="back-container">
      <el-button type="default" size="small" @click="handleBack" class="back-btn">
        返回
      </el-button>
    </div>
    <div class="table-container">
      <TableModel
        :formLabel="formLabel"
        :columnsList="columnsList"
        :request-api="listFinance"
        :sendParams="{ enterpriseId: enterpriseId }"
        :showOperation="true"
        :showRightTools="false"
        ref="financeTableRef"
      >
        <template slot="tableTitle">
          <h3>财务报告列表</h3>
        </template>
        <template slot="tableActions">
          <el-button
            type="primary"
            icon="el-icon-plus"
            @click="handleAdd"
            v-hasPermi="['enterpriseLibrary:finance:add']"
            class="add-btn"
          >
            新增报告
          </el-button>
        </template>
        <!-- 文件名插槽（保持原样） -->
        <template slot="fileName" slot-scope="{ data }">
          <span>{{ data.fileName || '--' }}</span>
        </template>
        <!-- 年份格式化插槽：只显示4位年份 -->
        <template slot="reportYear" slot-scope="{ data }">
          <span>{{ formatYear(data.reportYear) || '--' }}</span>
        </template>
        <!-- 文件状态插槽（保持原样） -->
        <template slot="financeState" slot-scope="{ data }">
          <span :style="getStateStyle(data.financeState)">
            {{ data.financeState || '--' }}
          </span>
        </template>
        <!-- 操作按钮插槽（保持原样） -->
        <template slot="handle" slot-scope="{ data }">
          <el-button
            size="mini"
            type="text"
            @click="handleView(data)"
            v-hasPermi="['enterpriseLibrary:finance:view']"
            class="action-btn"
          >
            查看
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleEdit(data)"
            v-hasPermi="['enterpriseLibrary:finance:edit']"
            class="action-btn"
            style="color: #EAA819;"
          >
            编辑
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleDelete(data)"
            v-hasPermi="['enterpriseLibrary:finance:delete']"
            class="action-btn"
            style="color: #DB3E29;"
          >
            删除
          </el-button>
        </template>
      </TableModel>
    </div>
  </el-card>
</template>

<script>
import TableModel from '@/components/TableModel2'
import { formLabel, columnsList } from './config'
import { encryptWithSM4, decryptWithSM4 } from '@/utils/sm'
import { listFinance, delFinance } from "@/api/enterpriseLibrary/finance/finance";

export default {
  name: 'Finance',
  components: { TableModel },
  data() {
    return {
      formLabel,          // 筛选条件配置
      columnsList,        // 表格列配置
      listFinance,        // 列表请求接口
      enterpriseId: decryptWithSM4(this.$route.query.enterpriseId) || '0'  // 企业ID（解密路由参数）
    }
  },

  created() {
    // 初始化时加载表格数据
    this.$nextTick(() => {
      if (this.$refs.financeTableRef) {
        this.$refs.financeTableRef.queryParams.enterpriseId = this.enterpriseId
        this.$refs.financeTableRef.getTableList()
      }
    })
  },

  methods: {
    /**
     * 格式化年份：将 2025-01-01 或 Date 对象转换为 4位年份（如 2025）
     * @param {String|Date} yearData - 原始年份数据
     * @returns {String} 4位年份字符串
     */
    formatYear(yearData) {
      if (!yearData) return ''

      // 处理字符串格式（如 "2025-01-01" 或 "2025/01/01"）
      if (typeof yearData === 'string') {
        // 截取前4位数字（兼容多种分隔符）
        const yearMatch = yearData.match(/^\d{4}/)
        return yearMatch ? yearMatch[0] : ''
      }

      // 处理 Date 对象
      if (yearData instanceof Date) {
        return yearData.getFullYear().toString()
      }

      // 其他情况（如数字 2025）
      return yearData.toString().slice(0, 4)
    },

    /**
     * 根据文件状态返回样式
     * @param {String} state - 状态字符串
     * @returns {Object} 样式对象
     */
    getStateStyle(state) {
      switch (state) {
        case '解析中':
          return { color: '#409eff' }
        case '可引用':
          return { color: '#67c23a' }
        default:
          return { color: '#606266' }
      }
    },

    /** 新增报告 */
    handleAdd() {
      this.$router.push({
        name: "FinanceForm",
        query: {
          type: encryptWithSM4('add'),
          id: encryptWithSM4(''),
          enterpriseId: encryptWithSM4(this.enterpriseId)
        },
        title: '新增财务报告'
      })
    },

    /** 查看报告详情 */
    handleView(data) {
      this.$router.push({
        name: "FinanceDetail",
        query: {
          id: encryptWithSM4((data.financeId ?? '').toString()),
          enterpriseId: encryptWithSM4(this.enterpriseId)
        },
        title: '财务报告详情'
      })
    },

    /** 编辑报告 */
    handleEdit(data) {
      this.$router.push({
        name: "FinanceEdit",
        query: {
          type: encryptWithSM4('edit'),
          id: encryptWithSM4((data.financeId ?? '').toString()),
          enterpriseId: encryptWithSM4(this.enterpriseId)
        },
        title: '编辑财务报告'
      })
    },

    /** 删除报告 */
    handleDelete(data) {
      this.$confirm(`确定要删除【${data.fileName}】吗？`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$modal.loading("正在删除，请稍候...")
        delFinance({
          financeId: data.financeId,
          enterpriseId: this.enterpriseId
        }).then(res => {
          this.$modal.closeLoading()
          if (res.code === 200) {
            this.$modal.msgSuccess("删除成功")
            this.$refs.financeTableRef.getTableList()  // 重新加载列表
          } else {
            this.$modal.msgError(res.msg || "删除失败")
          }
        }).catch(error => {
          this.$modal.closeLoading()
          this.$modal.msgError(error.message || "删除失败")
        })
      })
    },

    /** 返回上一页 */
    handleBack() {
      const obj = {
        path: "/enterpriseKnowledge/index",
        query: {
          enterpriseId: encryptWithSM4(this.enterpriseId || '0'),
        }
      }
      this.$tab.closeOpenPage(obj)
    }
  }
}
</script>

<style scoped lang="scss">
.tool-container {
  height: calc(100vh - 84px);
  overflow: auto;
  background: linear-gradient(180deg, #F1F6FF 20%, #E5EFFF 100%);
  padding: 20px;
}

::v-deep .table-card {
  height: calc(100vh - 240px) !important;
}


.back-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 20px;

  .back-btn {
    width: 98px;
    height: 36px;
    background: #FFFFFF;
    box-shadow: 0px 4px 8px 0px rgba(76, 76, 76, 0.2);
    border-radius: 4px;
    border: none;
    color: #666;
    font-size: 14px;
    transition: all 0.3s ease;

    &:hover {
      background: #f5f5f5;
      color: #409EFF;
      box-shadow: 0px 6px 12px 0px rgba(76, 76, 76, 0.3);
    }
  }
}

.add-btn {
  width: 121px;
  height: 36px;
  background: #1F72EA;
  box-shadow: 0px 4px 8px 0px rgba(51, 135, 255, 0.5);
  border-radius: 4px;
  color: #fff;
  border: none;
  font-size: 14px;
  transition: all 0.3s;

  &:hover {
    background: #4A8BFF;
    box-shadow: 0px 6px 12px 0px rgba(51, 135, 255, 0.6);
  }
}

.action-btn {
  margin-right: 8px;

  &:last-child {
    margin-right: 0;
  }
}
</style>
