<template>
  <div class="app-container">
    <!-- 返回按钮 -->
    <div class="back-container">
      <el-button type="default" @click="handleBack" class="back-btn">
        返回
      </el-button>
    </div>

    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item prop="certificateName">
          <el-input
            v-model="queryParams.certificateName"
            placeholder="请输入证书名称查询"
            clearable
            maxlength="50"
            class="search-input"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item prop="qualificationType">
          <el-select
            v-model="queryParams.qualificationType"
            placeholder="请选择资质类型"
            clearable
            class="search-select"
          >
            <el-option
              v-for="item in qualificationTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="handleQuery" class="search-btn">查询</el-button>
          <el-button size="small" @click="resetQuery" class="reset-btn">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 资质卡片网格 -->
    <div class="qualification-grid">
      <!-- 新增资质卡片 -->
      <div class="qualification-card-wrapper">
        <div
          class="qualification-card create-card"
          @click="handleAdd"
          v-hasPermi="['enterpriseLibrary:qualification:add']"
        >
          <div class="create-icon">
            <i class="el-icon-plus"></i>
          </div>
          <div class="create-text">新增资质证书</div>
        </div>
      </div>

      <!-- 资质信息卡片及下方的过期提示 -->
      <div class="qualification-card-wrapper" v-for="item in qualificationList" :key="item.qualificationId">
        <!-- 卡片本身 -->
        <div class="qualification-card">
          <div class="qualification-header">
            <h3 class="certificate-name">{{ item.certificateName || '未命名证书' }}</h3>
          </div>

          <div class="qualification-info">
            <div class="info-item">
              <span class="label">证书编号</span>
              <span class="value">{{ item.certificateCode || '-' }}</span>
            </div>
            <div class="info-item">
              <span class="label">发证机构</span>
              <span class="value">{{ item.certificateInstitution || '-' }}</span>
            </div>
            <div class="info-item">
              <span class="label">有效期</span>
              <span class="value">
                {{ item.certificateDate || '-' }} 至 {{ item.certificateEndDate || '-' }}
              </span>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="qualification-actions">
            <div
              v-hasPermi="['enterpriseLibrary:qualification:detail']"
              @click="handleDetail(item)"
              class="action-btn detail-btn"
            >
              <img :src="QualificationDetail" alt="详情" />
              <span>详情</span>
            </div>
            <div
              v-hasPermi="['enterpriseLibrary:qualification:edit']"
              @click="handleEdit(item)"
              class="action-btn edit-btn"
            >
              <img :src="QualificationEdit" alt="编辑" />
              <span>编辑</span>
            </div>
            <div
              v-hasPermi="['enterpriseLibrary:qualification:del']"
              @click="handleDel(item)"
              class="action-btn delete-btn"
            >
              <img :src="QualificationDelete" alt="删除" />
              <span>删除</span>
            </div>
          </div>
        </div>

        <!-- 过期提示 -->
        <div class="expired-tags" v-if="item.isExpired">
          <span class="expired-text">证书已过期</span>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryParams.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="queryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      />
    </div>

    <!-- 右侧抽屉：新增/编辑表单 -->
    <el-drawer
      :title="drawerType === 'add' ? '新增资质证书' : '编辑资质证书'"
      :visible.sync="drawerVisible"
      direction="rtl"
      size="40%"
      :before-close="handleDrawerClose"
      custom-class="custom-qualification-drawer qualification-drawer"
    >
      <QualificationForm
        ref="qualificationForm"
        :type="drawerType"
        :qualification-id="drawerId"
        :enterprise-id="enterpriseId"
        :drawer-visible="drawerVisible"
        @save-success="handleSaveSuccess"
        @cancel="handleDrawerClose"
      />
    </el-drawer>

    <!-- 详情抽屉 -->
    <el-drawer
      title="资质证书详情"
      :visible.sync="detailDrawerVisible"
      direction="rtl"
      size="40%"
      :before-close="handleDetailDrawerClose"
      custom-class="custom-qualification-drawer qualification-drawer"
      :append-to-body="false"
    >
      <QualificationDetailComp
        ref="qualificationDetail"
        :qualification-id="detailId"
        :enterprise-id="enterpriseId"
        :drawer-visible="detailDrawerVisible"
        @cancel="handleDetailDrawerClose"
      />
    </el-drawer>
  </div>
</template>

<script>
import QualificationDetail from '@/assets/enterpriseLibrary/enterprise/enterprise-detail.png';
import QualificationEdit from '@/assets/enterpriseLibrary/enterprise/enterprise-edit.png';
import QualificationDelete from '@/assets/enterpriseLibrary/enterprise/enterprise-delete.png';
import QualificationForm from './components/QualificationForm.vue';
import QualificationDetailComp from './components/QualificationDetail.vue';
import { listAPI, delDataAPI } from '@/api/enterpriseLibrary/qualification/qualification';
import { encryptWithSM4, decryptWithSM4 } from '@/utils/sm';

export default {
  name: 'Qualification',
  components: { QualificationForm, QualificationDetailComp },
  data() {
    return {
      // 图标引用
      QualificationDetail,
      QualificationEdit,
      QualificationDelete,
      // 企业ID
      enterpriseId: decryptWithSM4(this.$route.query.enterpriseId) || '0',
      // 查询参数
      queryParams: {
        enterpriseId: decryptWithSM4(this.$route.query.enterpriseId) || '0',
        pageNum: 1,
        pageSize: 10,
        certificateName: '',
        qualificationType: '',
      },
      // 列表数据
      qualificationList: [],
      total: 0,
      // 资质类型选项
      qualificationTypeOptions: [],
      // 抽屉状态
      drawerVisible: false,
      drawerType: 'add', // add/edit
      drawerId: '',
      detailDrawerVisible: false,
      detailId: null
    };
  },
  created() {
    this.getList();
    this.loadQualificationTypeDict();
  },
  methods: {

    loadQualificationTypeDict() {
      // getDicts 的参数是字典类型编码：qualification_type
      this.getDicts('qualification_type').then(response => {
        this.qualificationTypeOptions = response.data.map(item => ({
          label: item.dictLabel,
          value: item.dictValue
        }))
      }).catch(error => {
        console.error('加载电压等级字典失败：', error)
      })
    },

    // 获取资质列表（包含过期判断）
    getList() {
      listAPI(this.queryParams).then(res => {
        if (res.code === 200) {
          this.qualificationList = res.rows.map(item => {
            // 计算证书是否过期
            const now = new Date();
            const endDate = item.certificateEndDate ? new Date(item.certificateEndDate) : null;
            item.isExpired = endDate && endDate < now;

            // 匹配资质类型文本
            const typeItem = this.qualificationTypeOptions.find(
              opt => opt.dictValue === item.qualificationType
            );
            item.qualificationTypeText = typeItem ? typeItem.dictLabel : '未分类';
            return item;
          });
          this.total = res.total;
        }
      });
    },

    // 搜索查询
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    // 重置搜索
    resetQuery() {
      this.queryParams.certificateName = '';
      this.queryParams.qualificationType = '';
      this.handleQuery();
    },

    // 新增资质
    handleAdd() {
      this.drawerType = 'add';
      this.drawerId = '';
      this.$nextTick(() => {
        this.$refs.qualificationForm?.resetForm();
        this.drawerVisible = true;
      });
    },

    // 编辑资质
    handleEdit(item) {
      this.drawerType = 'edit';
      this.drawerId = item.qualificationId;
      this.drawerVisible = true;
    },

    // 删除资质
    handleDel(item) {
      this.$confirm(
        `确定要删除资质"${item.certificateName}"吗？删除后将无法恢复！`,
        '操作提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        delDataAPI({ qualificationId: item.qualificationId }).then(res => {
          if (res.code === 200) {
            this.$message.success('删除成功');
            this.getList();
          } else {
            this.$message.error(res.msg || '删除失败');
          }
        });
      });
    },

    // 查看详情
    handleDetail(item) {
      this.detailId = item.qualificationId;
      this.$nextTick(() => {
        this.detailDrawerVisible = true;
      });
    },

    // 关闭详情抽屉
    handleDetailDrawerClose() {
      this.detailDrawerVisible = false;
      this.$nextTick(() => {
        this.$refs.qualificationDetail?.resetForm();
        this.detailId = null;
      });
    },

    // 分页大小改变
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getList();
    },

    // 当前页改变
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getList();
    },

    // 返回上一页
    handleBack() {
      this.$tab.closeOpenPage({
        path: "/enterpriseKnowledge/index",
        query: { enterpriseId: encryptWithSM4(this.enterpriseId) }
      });
    },

    // 关闭抽屉
    handleDrawerClose() {
      this.$refs.qualificationForm?.resetForm();
      this.drawerVisible = false;
    },

    // 保存成功回调
    handleSaveSuccess() {
      this.drawerVisible = false;
      this.getList();
    }
  }
};
</script>

<style scoped lang="scss">
.app-container {
  padding: 20px;
  background: linear-gradient(180deg, #F1F6FF 20%, #E5EFFF 100%);
  height: calc(100vh - 85px); /* 占满可视区高度，减去顶部导航栏高度 */
  display: flex;
  flex-direction: column;
  overflow: hidden; /* 禁止整体页面滚动 */
}

// 抽屉公共样式（关键修改：让抽屉内容区支持flex布局）
::v-deep .qualification-drawer {
  .el-drawer__header {
    padding: 20px 24px;
    border-bottom: 1px solid #f5f5f5;
    .el-drawer__title {
      font-size: 18px;
      font-weight: 600;
      color: #333;
    }
  }
  .el-drawer__body {
    padding: 0; // 移除默认内边距，由子组件控制
    display: flex;
    flex-direction: column;
    height: 100%; // 占满抽屉高度
    overflow: hidden; // 隐藏溢出内容
  }
}

// 自定义抽屉样式（保持原有其他样式）
::v-deep .custom-qualification-drawer {
  .el-drawer__body {
    background: #fff;
  }
  .el-drawer__header {
    padding: 24px;
    border-bottom: 1px solid #f5f5f5;
  }
}

.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);
    }
  }
}

.search-container {
  padding: 0 20px;
  border-radius: 8px;
  margin-bottom: 20px;

  .search-input {
    width: 300px;
    margin-right: 10px;
  }

  .search-select {
    width: 200px;
    margin-right: 10px;
  }

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

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

  .reset-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);
    }
  }
}

.qualification-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(290px, 1fr));
  gap: 24px;
  margin-bottom: 20px; /* 与分页保持间距 */
  padding: 20px 6px 20px 0px;
  align-items: start;
  flex: 1; /* 自动填充剩余高度 */
  overflow-y: auto; /* 仅纵向滚动 */
  overflow-x: hidden; /* 禁止横向滚动 */

  /* 滚动条样式保持不变 */
  &::-webkit-scrollbar {
    width: 6px;
  }
  &::-webkit-scrollbar-track {
    background: transparent;
  }
  &::-webkit-scrollbar-thumb {
    background: rgba(0, 0, 0, 0.2);
    border-radius: 3px;
    &:hover {
      background: rgba(0, 0, 0, 0.3);
    }
  }
}

// 卡片容器（包含卡片和下方提示）
.qualification-card-wrapper {
  display: flex;
  flex-direction: column;
}

.qualification-card {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  cursor: pointer;
  min-height: 200px;
  display: flex;
  flex-direction: column;
  position: relative;

  &:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    transform: translateY(-2px);
  }

  &.create-card {
    border: 2px dashed #ddd;
    align-items: center;
    justify-content: center;
    height: 250px;

    &:hover {
      border-color: #409EFF;
      background: #f0f8ff;
    }

    .create-icon {
      font-size: 48px;
      color: #999;
      margin-bottom: 10px;
    }

    .create-text {
      font-size: 16px;
      color: #666;
      font-weight: 500;
    }
  }
}

.qualification-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;

  .certificate-name {
    font-size: 18px;
    font-weight: 600;
    color: #333;
    margin: 0;
    max-width: 70%;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .type-tag {
    background: #e6f7ff;
    color: #1890ff;
    font-size: 12px;
    padding: 3px 8px;
    border-radius: 4px;
  }
}

.qualification-info {
  margin-bottom: 15px;
  flex: 1;

  .info-item {
    display: flex;
    margin-bottom: 8px;
    line-height: 1.5;

    .label {
      color: #888;
      font-size: 14px;
      min-width: 80px;
    }

    .value {
      color: #424242;
      font-size: 14px;
      flex: 1;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
}

.qualification-actions {
  display: flex;
  justify-content: space-around;
  padding-top: 10px;
  border-top: 1px solid #f5f5f5;

  .action-btn {
    display: flex;
    flex-direction: column;
    align-items: center;
    cursor: pointer;
    font-size: 12px;
    transition: all 0.3s ease;
    padding: 8px 0;
    min-width: 60px;

    img {
      width: 20px;
      height: 20px;
      margin-bottom: 4px;
    }

    &.detail-btn {
      background: #f0f8ff;
      color: #409EFF;
      border-radius: 6px;

      &:hover {
        background: #e6f3ff;
        color: #66b1ff;
        box-shadow: 0px 2px 8px rgba(64, 158, 255, 0.2);
      }
    }

    &.edit-btn {
      background: #fff7e6;
      color: #ff9500;
      border-radius: 6px;

      &:hover {
        background: #fff2d9;
        color: #ffb84d;
        box-shadow: 0px 2px 8px rgba(255, 149, 0, 0.2);
      }
    }

    &.delete-btn {
      background: #fff1f0;
      color: #ff4d4f;
      border-radius: 6px;

      &:hover {
        background: #ffe7e6;
        color: #ff7875;
        box-shadow: 0px 2px 8px rgba(255, 77, 79, 0.2);
      }
    }
  }
}

// 过期提示样式
.expired-tags {
  padding: 8px 12px;
  flex-shrink: 0;

  .expired-text {
    display: block;
    color: #db3e29;
    font-size: 14px;
    line-height: 1.5;
    word-break: break-all;

    i {
      margin-right: 5px;
      font-size: 14px;
    }
  }
}

.pagination-container {
  display: flex;
  justify-content: flex-end; /* 关键改动：右对齐 */
  padding: 20px;
  border-radius: 8px;
  flex-shrink: 0; /* 关键改动：防止分页栏被压缩 */

  // 以下是从人员库组件复制过来的详细样式
  .el-pagination {
    .el-pagination__total {
      color: #606266;
      font-weight: 500;
    }
    .el-pagination__sizes .el-select .el-input__inner {
      border-color: #dcdfe6;
      border-radius: 4px;
    }
    .el-pager li {
      border-radius: 4px;
      margin: 0 2px;
      &.active {
        background: #409EFF;
        color: #fff;
      }
      &:hover { color: #409EFF; }
    }
    .btn-prev, .btn-next {
      border-radius: 4px;
      margin: 0 2px;
      &:hover { color: #409EFF; }
    }
    .el-pagination__jump .el-input__inner {
      border-color: #dcdfe6;
      border-radius: 4px;
    }
  }
}
</style>
