<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="资料名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入资料名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="分类名称" prop="categoryName">
        <el-input v-model="queryParams.categoryName" placeholder="请输入分类名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
<!--      <el-form-item label="共享范围" prop="shareDeptName" v-if="hasSameDepartment()">
        <el-input v-model="queryParams.shareDeptName" placeholder="请输入共享范围" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>-->
      <!-- 过期状态搜索 -->
      <el-form-item label="期限状态" prop="expireStatus" v-if="hasSameDepartment()">
        <el-select v-model="queryParams.expireStatus" placeholder="请选择期限状态" clearable>
          <el-option label="未过期" value="valid" />
          <el-option label="已过期" value="expired" />
          <el-option label="全部" value="all" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @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="openForm(undefined)"
                   v-hasPermi="['server:material-info:create']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" :loading="exportLoading"
                   v-hasPermi="['server:material-info:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 使用 filteredList 进行前端过滤 -->
    <el-table v-loading="loading" :data="filteredList" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="资料名称" align="center" prop="name" min-width="150"/>
      <el-table-column label="分类名称" align="center" prop="categoryName" min-width="150"/>

      <el-table-column label="生效日期" align="center" prop="startTime" min-width="100">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="失效日期" align="center" prop="expireTime" min-width="100">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.expireTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!-- 新增：快过期提醒列 -->
      <el-table-column label="快过期提醒" align="center" min-width="120" v-if="hasSameDepartment()">
        <template v-slot="scope">
                        <span :class="getExpiringReminderClass(scope.row)">
                            {{ getExpiringReminderText(scope.row) }}
                        </span>
        </template>
      </el-table-column>
      <!-- 过期提醒列 -->
      <el-table-column label="期限状态" align="center" min-width="90" v-if="hasSameDepartment()">
        <template v-slot="scope">
          <span :class="{ 'expired-text': isExpired(scope.row) }">
            {{ getExpireStatusText(scope.row) }}
          </span>
        </template>
      </el-table-column>

<!--      <el-table-column label="共享范围" align="center" min-width="90">
        <template v-slot="scope">
          <span>{{ getShareUsersDisplay(scope.row) }}</span>
        </template>
      </el-table-column>-->

      <el-table-column label="下载次数" align="center" prop="downloadCount"  min-width="80"/>
      <el-table-column label="下载" align="center" min-width="80">
        <template v-slot="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleDownload(scope.row)"
          >
            下载
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" min-width="100">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="150">
        <template v-slot="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetail(scope.row.id)">查看</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="openForm(scope.row.id)"
                     v-hasPermi="['server:material-info:update']" v-if="hasSameDepartment(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['server:material-info:delete']" v-if="hasSameDepartment(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <!-- 对话框 -->
    <MaterialInfoForm ref="formRef" @success="getList" />
    <MaterialInfoDetail ref="detailRef" />
  </div>
</template>

<script>
import * as MaterialInfoApi from '@/api/server/materialinfo';
import MaterialInfoForm from './MaterialInfoForm.vue';
import MaterialInfoDetail from './MaterialInfoDetail.vue';

export default {
  name: "MaterialInfo",
  components: {
    MaterialInfoForm,
    MaterialInfoDetail
  },
  data() {
    return {
      loading: true,
      exportLoading: false,
      showSearch: true,
      total: 0,
      list: [], // 原始数据
      currentUserDepartmentId: null,
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        categoryName: null,
        name: null,
        shareDeptName: null,
        expireStatus: null, // 过期状态查询参数
      },
    };
  },
  computed: {
    /** 根据过期状态过滤后的列表 */
    filteredList() {
      if (!this.queryParams.expireStatus || this.queryParams.expireStatus === 'all') {
        return this.list;
      }

      return this.list.filter(item => {
        const isExpired = this.isExpired(item);
        return this.queryParams.expireStatus === 'expired' ? isExpired : !isExpired;
      });
    }
  },
  created() {
    this.getList();
    this.getCurrentUserDepartment();
  },
  methods: {
    /** 获取当前用户部门信息 */
    async getCurrentUserDepartment() {
      const userInfo = this.$store.state.user;
      this.currentUserDepartmentId = userInfo.deptId;
    },

    /** 检查当前用户是否与数据创建人同部门 */
    hasSameDepartment() {
      const userInfo = this.$store.state.user;
      const roles = userInfo.roles || [];
      if (roles.includes("super_admin") || roles.includes("trs_material_admin")) {
        return true;
      }else{
        return false;
      }
    },

    /** 判断资料是否过期 - 基于失效日期 */
    isExpired(row) {
      if (!row.expireTime) return false;
      // 获取当前日期（只比较日期部分，忽略时间）
      const now = new Date();
      // const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
      // 解析失效日期
      const expireDate = new Date(row.expireTime);
      // 直接比较完整日期和时间（包含时分秒）
      return expireDate < now;
    },

    /** 获取过期状态文本 */
    getExpireStatusText(row) {
      return this.isExpired(row) ? '已过期' : '未过期';
    },


    /** 计算距离过期的天数 */
    getDaysUntilExpire(row) {
      if (!row.expireTime) return null;
      const now = new Date();
      const expireDate = new Date(row.expireTime);
      // 计算天数差异
      const diffTime = expireDate - now;
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
      return diffDays;
    },

    /** 获取快过期提醒文本 */
    getExpiringReminderText(row) {
      if (!row.expireTime) return '';

      if (this.isExpired(row)) {
        const daysAgo = -this.getDaysUntilExpire(row);
        return `${daysAgo}天前过期`;
      }
      const daysUntilExpire = this.getDaysUntilExpire(row);
      const dayleft = row.dayleft || 30; // 默认提前30天提醒

      if (daysUntilExpire <= dayleft) {
        return `${daysUntilExpire}天后过期`;
      }
      return '';
    },

    /** 获取快过期提醒样式类 */
    getExpiringReminderClass(row) {
      if (!row.expireTime) return '';

      if (this.isExpired(row)) {
        return 'expired-text';
      }
      const daysUntilExpire = this.getDaysUntilExpire(row);
      const dayleft = row.dayleft || 30; // 默认提前30天提醒

      if (daysUntilExpire <= dayleft) {
        return 'expired-text'; // 修改为与过期相同的样式
      }
      return '';
    },


    /** 查询列表 */
    async getList() {
      try {
        this.loading = true;
        // 只传递后端支持的查询参数
        const params = {
          pageNo: this.queryParams.pageNo,
          pageSize: this.queryParams.pageSize,
          categoryName: this.queryParams.categoryName,
          name: this.queryParams.name,
          shareDeptName: this.queryParams.shareDeptName
        };

        const res = await MaterialInfoApi.getMaterialInfoPage(params);
        this.list = res.data.list;
        this.total = res.data.total;
      } finally {
        this.loading = false;
      }
    },

    /** 格式化共享用户显示 */
    getShareUsersDisplay(row) {
      if (row.shareType === 1) {
        return '全部组织';
      } else if (row.shareType === 2 && row.shareUsers && row.shareUsers.length > 0) {
        return row.shareUsers.map(user => user.deptName).join('、');
      } else {
        return '未设置共享用户';
      }
    },

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

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.expireStatus = null;
      this.handleQuery();
    },

    /** 添加/修改操作 */
    openForm(id) {
      this.$refs["formRef"].open(id);
    },

    handleDetail(id) {
      this.$refs["detailRef"].open(id);
    },

    /** 删除按钮操作 */
    async handleDelete(row) {
      const id = row.id;
      await this.$modal.confirm('是否确认删除资料库编号为"' + id + '"的数据项?')
      try {
        await MaterialInfoApi.deleteMaterialInfo(id);
        await this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch {}
    },

    /** 导出按钮操作 */
    async handleExport() {
      await this.$modal.confirm('是否确认导出所有资料库数据项?');
      try {
        this.exportLoading = true;
        const data = await MaterialInfoApi.exportMaterialInfoExcel(this.queryParams);
        this.$download.excel(data, '资料库.xls');
      } catch {
      } finally {
        this.exportLoading = false;
      }
    },

    /** 下载按钮操作 */
    handleDownload(row) {
      // 检查是否过期
      if (this.isExpired(row)) {
        this.$message.warning('该资料已过期，无法下载');
        return;
      }

      if (!row.attachment) {
        this.$message.warning('该资料没有附件');
        return;
      }

      try {
        const link = document.createElement('a');
        link.href = row.attachment;
        link.target = '_blank';

        let fileName = row.attachment.substring(row.attachment.lastIndexOf('/') + 1) || '资料下载';
        fileName = this.getFileName(fileName);
        link.download = fileName;

        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);

        // 更新下载次数
        MaterialInfoApi.getMaterialInfo2(row.id);
        this.$message.success('开始下载');
      } catch (error) {
        console.error('下载失败:', error);
        this.$message.error('下载失败');
      }
    },

    getFileName(name) {
      let fileName = name;
      if (name.lastIndexOf("/") > -1) {
        fileName = name.slice(name.lastIndexOf("/") + 1);
      }
      fileName = fileName.replace(/_\d{13}(?=\.\w+$)/, '');
      return fileName;
    },
  }
};
</script>

<style scoped>
.expired-text {
  color: #f56c6c;
  font-weight: bold;
}

.el-button.is-disabled {
  cursor: not-allowed;
}
</style>
