<template>
  <div class="app-container">
    <!-- 搜索部分 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="真实姓名" prop="realName">
        <el-input
          v-model="queryParams.realName"
          placeholder="请输入真实姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-input
          v-model="queryParams.gender"
          placeholder="请输入性别"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="身份证号" prop="idCard">
        <el-input
          v-model="queryParams.idCard"
          placeholder="请输入身份证号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工作经验" prop="workExperience">
        <el-input
          v-model="queryParams.workExperience"
          placeholder="请输入工作经验"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属医院" prop="hospital">
        <el-input
          v-model="queryParams.hospital"
          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="handleAdd"
          v-hasPermi="['vet:info:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['vet:info:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['vet:info:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-check"
          size="mini"
          :disabled="single"
          @click="handleAudit"
          v-hasPermi="['sys:vetAudit:audit']"
        >审核</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格部分 -->
    <el-table v-loading="loading" :data="infoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="用户昵称" align="center" prop="nickName" width="200px"/>
      <el-table-column label="真实姓名" align="center" prop="realName" width="200px"/>
      <el-table-column label="性别" align="center" prop="gender" width="100px"/>
      <el-table-column label="出生日期" align="center" prop="birthday" width="200px">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.birthday, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="身份证号" align="center" prop="idCard" width="200px"/>
      <!--      <el-table-column label="擅长领域" align="center" prop="specialty" width="300px" :show-overflow-tooltip="true"/>-->
      <!--      <el-table-column label="工作经验" align="center" prop="workExperience" width="100px"/>-->
      <el-table-column label="职称" align="center" prop="title" width="200px"/>
      <el-table-column label="联系电话" align="center" prop="phone" width="200px"/>
      <!--      <el-table-column label="电子邮箱" align="center" prop="email"/>-->
      <el-table-column label="专家类型" align="center" prop="expertType" width="200px"/>
      <el-table-column label="所属医院" align="center" prop="hospital" width="300px" :show-overflow-tooltip="true"/>
      <!--      <el-table-column label="联系地址" align="center" prop="address" />-->
      <!--      <el-table-column label="个人简介" align="center" prop="introduction" />-->
      <el-table-column label="审核状态" align="center" prop="auditStatus" width="100" class-name="audit-status-column">
        <template slot-scope="scope">
          <el-tag :type="getAuditStatusTagType(scope.row.auditStatus)" size="small">
            {{ getAuditStatusText(scope.row.auditStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="220">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            class="info-btn view-btn"
            @click="handleView(scope.row)"
            v-hasPermi="['sys:vetAudit:view']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-check"
            style="color: #072eed"
            class="info-btn audit-btn"
            @click="handleAudit(scope.row)"
            v-hasPermi="['sys:vetAudit:auditVetPersonalInfo']"
          >审核</el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 审核对话框 -->
    <el-dialog
      :title="auditTitle"
      :visible.sync="auditVisible"
      width="80%"
      append-to-body
      :close-on-click-modal="false"
      class="audit-dialog"
    >
      <el-tabs v-model="activeAuditTab" type="border-card" @tab-click="handleTabClick">
        <!-- 基本信息审核标签页 -->
        <el-tab-pane label="基本信息审核" name="basic">
          <div v-if="loadingBasicData" class="tab-loading">
            <i class="el-icon-loading"></i>
            <div>加载基本信息...</div>
          </div>

          <div v-else>
            <div class="info-section">
              <h3>兽医基本信息</h3>
              <el-descriptions :column="2" border>
                <el-descriptions-item label="真实姓名">{{ basicInfo.realName || '-' }}</el-descriptions-item>
                <el-descriptions-item label="性别">{{ basicInfo.gender || '-' }}</el-descriptions-item>
                <el-descriptions-item label="出生日期">{{ parseTime(basicInfo.birthday, '{y}-{m}-{d}') || '-' }}</el-descriptions-item>
                <el-descriptions-item label="身份证号">{{ basicInfo.idCard || '-' }}</el-descriptions-item>
                <el-descriptions-item label="职称">{{ basicInfo.title || '-' }}</el-descriptions-item>
                <el-descriptions-item label="联系电话">{{ basicInfo.phone || '-' }}</el-descriptions-item>
                <el-descriptions-item label="电子邮箱">{{ basicInfo.email || '-' }}</el-descriptions-item>
                <el-descriptions-item label="专家类型">
                  <dict-tag :options="dict.type.expert_type" :value="basicInfo.expertType"/>
                </el-descriptions-item>
                <el-descriptions-item label="所属医院">{{ basicInfo.hospital || '-' }}</el-descriptions-item>
                <el-descriptions-item label="联系地址" :span="2">{{ basicInfo.address || '-' }}</el-descriptions-item>
                <el-descriptions-item label="个人简介" :span="2">{{ basicInfo.introduction || '-' }}</el-descriptions-item>
                <el-descriptions-item label="当前审核状态">
                  <el-tag :type="getAuditStatusTagType(basicInfo.auditStatus)" size="small">
                    {{ getAuditStatusText(basicInfo.auditStatus) }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="审核人">{{ basicInfo.auditor || '-' }}</el-descriptions-item>
                <el-descriptions-item label="审核时间">{{ parseTime(basicInfo.auditTime) || '-' }}</el-descriptions-item>
                <el-descriptions-item label="审核意见" :span="2">{{ basicInfo.auditDesc || '-' }}</el-descriptions-item>
              </el-descriptions>
            </div>

            <div class="audit-form-section">
              <h3>基本信息审核</h3>
              <el-form ref="basicAuditForm" :model="basicAuditForm" :rules="basicAuditRules" label-width="100px">
                <el-form-item label="审核结果" prop="auditStatus">
                  <el-radio-group v-model="basicAuditForm.auditStatus">
                    <el-radio label="1">审核通过</el-radio>
                    <el-radio label="2">审核不通过</el-radio>
                  </el-radio-group>
                  <span v-if="basicInfo.auditStatus && basicInfo.auditStatus !== '0'" class="audit-status-tag">
                    <el-tag :type="getAuditStatusTagType(basicInfo.auditStatus)" size="small">
                      {{ getAuditStatusText(basicInfo.auditStatus) }}
                    </el-tag>
                  </span>
                </el-form-item>
                <el-form-item label="审核意见" prop="auditDesc">
                  <el-input
                    v-model="basicAuditForm.auditDesc"
                    type="textarea"
                    :rows="4"
                    placeholder="请输入审核意见"
                    :maxlength="500"
                    show-word-limit
                  />
                </el-form-item>
              </el-form>
            </div>
          </div>
        </el-tab-pane>

        <!-- 资质证书审核标签页 -->
        <el-tab-pane label="资质证书审核" name="certificate" v-if="showCertificateTab">
          <div v-if="loadingCertData" class="tab-loading">
            <i class="el-icon-loading"></i>
            <div>加载证书信息...</div>
          </div>

          <div v-else>
            <div v-if="!certificateList || certificateList.length === 0" class="no-data">
              <el-alert
                title="该兽医暂无资质证书"
                type="info"
                :closable="false"
                show-icon
              />
            </div>

            <div v-else>
              <div class="cert-summary" v-if="certificateList.length > 0">
                <el-alert
                  :title="getCertSummaryText()"
                  type="info"
                  :closable="false"
                  show-icon
                />
              </div>

              <el-tabs v-model="activeCertTab" type="card" class="cert-tabs">
                <el-tab-pane
                  v-for="(cert, index) in certificateList"
                  :key="cert.qualificationId"
                  :label="cert.certName || cert.qualificationType || `证书${index + 1}`"
                  :name="'cert' + cert.qualificationId"
                >
                  <div class="certificate-item" :class="{'cert-audited': cert.auditStatus && cert.auditStatus !== '0'}">
                    <div class="cert-header">
                      <div class="cert-title">
                        <span>{{ cert.certName || cert.qualificationType || '未命名证书' }}</span>
                        <el-tag
                          v-if="cert.auditStatus === '1'"
                          type="success"
                          size="small"
                          class="cert-status-tag"
                          effect="dark"
                        >
                          <i class="el-icon-success"></i> 已通过
                        </el-tag>
                        <el-tag
                          v-if="cert.auditStatus === '2'"
                          type="danger"
                          size="small"
                          class="cert-status-tag"
                          effect="dark"
                        >
                          <i class="el-icon-error"></i> 未通过
                        </el-tag>
                        <el-tag
                          v-if="!cert.auditStatus || cert.auditStatus === '0'"
                          type="warning"
                          size="small"
                          class="cert-status-tag"
                          effect="dark"
                        >
                          <i class="el-icon-time"></i> 待审核
                        </el-tag>
                      </div>
                      <div class="cert-info">
                        <span><strong>证书编号：</strong>{{ cert.certificateNo || '-' }}</span>
                        <span><strong>发证机构：</strong>{{ cert.issueOrg || '-' }}</span>
                        <span><strong>资质类型：</strong>{{ cert.qualificationType || '-' }}</span>
                        <span><strong>证书类型：</strong>{{ cert.certType || '-' }}</span>
                        <span><strong>颁发日期：</strong>{{ parseTime(cert.issueDate, '{y}-{m}-{d}') || '-' }}</span>
                        <span><strong>到期日期：</strong>{{ parseTime(cert.expireDate, '{y}-{m}-{d}') || '-' }}</span>
                        <span><strong>证书状态：</strong>{{ cert.certStatus || '-' }}</span>
                      </div>

                      <div v-if="cert.certImage" class="cert-image-section">
                        <div class="image-title">
                          <strong>证书图片：</strong>
                        </div>
                        <div class="image-preview">
                          <el-image
                            style="width: 200px; height: 150px;"
                            :src="baseUrl + cert.certImage"
                            :preview-src-list="[baseUrl + cert.certImage]"
                            fit="contain"
                          >
                            <div slot="error" class="image-slot">
                              <i class="el-icon-picture-outline"></i>
                              <div>图片加载失败</div>
                            </div>
                          </el-image>
                        </div>
                      </div>

                      <div v-if="cert.certificateFiles" class="cert-files-section">
                        <div class="files-title">
                          <strong>其他附件：</strong>
                        </div>
                        <div class="files-list">
                          <el-button
                            type="text"
                            icon="el-icon-download"
                            @click="downloadFile(cert.certificateFiles)"
                            class="download-btn"
                          >
                            {{ getFileName(cert.certificateFiles) }}
                          </el-button>
                        </div>
                      </div>
                    </div>

                    <div class="cert-audit-form">
                      <el-form :ref="'certForm' + cert.qualificationId"
                               :model="certAuditForms[cert.qualificationId]"
                               :rules="certAuditRules"
                               label-width="100px">
                        <el-form-item label="审核结果" prop="auditStatus">
                          <el-radio-group v-model="certAuditForms[cert.qualificationId].auditStatus"
                                          @change="handleCertAuditChange(cert.qualificationId)">
                            <el-radio label="1">审核通过</el-radio>
                            <el-radio label="2">审核不通过</el-radio>
                          </el-radio-group>
                          <span v-if="certAuditForms[cert.qualificationId].submitted" class="audit-saved-tag">
                            <el-tag type="success" size="small">已保存</el-tag>
                          </span>
                        </el-form-item>
                        <el-form-item label="审核意见" prop="auditOpinion">
                          <el-input
                            v-model="certAuditForms[cert.qualificationId].auditOpinion"
                            type="textarea"
                            :rows="4"
                            placeholder="请输入审核意见"
                            :maxlength="200"
                            show-word-limit
                            @blur="saveCertificateAudit(cert.qualificationId)"
                          />
                        </el-form-item>
                        <el-form-item>
                          <el-button
                            type="primary"
                            @click="saveCertificateAudit(cert.qualificationId)"
                            :loading="certAuditForms[cert.qualificationId] && certAuditForms[cert.qualificationId].saving"
                          >
                            保存审核
                          </el-button>
                          <el-button @click="resetCertAudit(cert.qualificationId)">重置</el-button>
                        </el-form-item>
                      </el-form>
                    </div>
                  </div>
                </el-tab-pane>
              </el-tabs>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAllAudit" :loading="submittingAll">
          {{ submittingAll ? '提交中...' : '提交审核' }}
        </el-button>
        <el-button @click="auditVisible = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      :title="detailTitle"
      :visible.sync="detailVisible"
      width="80%"
      append-to-body
    >
      <div v-if="loadingDetail" class="tab-loading">
        <i class="el-icon-loading"></i>
        <div>加载详情信息...</div>
      </div>

      <div v-else-if="detailData">
        <el-tabs v-model="detailActiveTab" type="border-card">
          <el-tab-pane label="基本信息" name="basicInfo">
            <div class="info-section">
              <h3>兽医详细信息</h3>
              <el-descriptions :column="2" border>
                <el-descriptions-item label="用户昵称">{{ detailData.nickName || '-' }}</el-descriptions-item>
                <el-descriptions-item label="真实姓名">{{ detailData.realName || '-' }}</el-descriptions-item>
                <el-descriptions-item label="性别">{{ detailData.gender || '-' }}</el-descriptions-item>
                <el-descriptions-item label="出生日期">{{ parseTime(detailData.birthday, '{y}-{m}-{d}') || '-' }}</el-descriptions-item>
                <el-descriptions-item label="身份证号">{{ detailData.idCard || '-' }}</el-descriptions-item>
                <el-descriptions-item label="职称">{{ detailData.title || '-' }}</el-descriptions-item>
                <el-descriptions-item label="联系电话">{{ detailData.phone || '-' }}</el-descriptions-item>
                <el-descriptions-item label="电子邮箱">{{ detailData.email || '-' }}</el-descriptions-item>
                <el-descriptions-item label="专家类型">
                  <dict-tag :options="dict.type.expert_type" :value="detailData.expertType"/>
                </el-descriptions-item>
                <el-descriptions-item label="所属医院">{{ detailData.hospital || '-' }}</el-descriptions-item>
                <el-descriptions-item label="联系地址">{{ detailData.address || '-' }}</el-descriptions-item>
                <el-descriptions-item label="擅长领域">{{ detailData.specialty || '-' }}</el-descriptions-item>
                <el-descriptions-item label="工作经验">{{ detailData.workExperience || '-' }}</el-descriptions-item>
                <el-descriptions-item label="个人简介" :span="2">{{ detailData.introduction || '-' }}</el-descriptions-item>
                <el-descriptions-item label="当前审核状态">
                  <el-tag :type="getAuditStatusTagType(detailData.auditStatus)" size="small">
                    {{ getAuditStatusText(detailData.auditStatus) }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="审核人">{{ detailData.auditor || '-' }}</el-descriptions-item>
                <el-descriptions-item label="审核时间">{{ parseTime(detailData.auditTime) || '-' }}</el-descriptions-item>
                <el-descriptions-item label="审核意见" :span="2">{{ detailData.auditDesc || '-' }}</el-descriptions-item>
              </el-descriptions>
            </div>
          </el-tab-pane>

          <el-tab-pane label="资质证书" name="certificates" v-if="detailCertificates && detailCertificates.length > 0">
            <div class="certificate-section">
              <h3>资质证书列表（共 {{ detailCertificates.length }} 个证书）</h3>

              <el-tabs v-model="detailCertActiveTab" type="card" class="cert-tabs">
                <el-tab-pane
                  v-for="(cert, index) in detailCertificates"
                  :key="cert.qualificationId"
                  :label="cert.certName || cert.qualificationType || `证书${index + 1}`"
                  :name="'detailCert' + cert.qualificationId"
                >
                  <div class="certificate-item view-only">
                    <div class="cert-header">
                      <div class="cert-title">
                        <span>{{ cert.certName || cert.qualificationType || '未命名证书' }}</span>
                        <el-tag
                          v-if="cert.auditStatus === '1'"
                          type="success"
                          size="small"
                          class="cert-status-tag"
                          effect="dark"
                        >
                          <i class="el-icon-success"></i> 已通过
                        </el-tag>
                        <el-tag
                          v-if="cert.auditStatus === '2'"
                          type="danger"
                          size="small"
                          class="cert-status-tag"
                          effect="dark"
                        >
                          <i class="el-icon-error"></i> 未通过
                        </el-tag>
                        <el-tag
                          v-if="!cert.auditStatus || cert.auditStatus === '0'"
                          type="warning"
                          size="small"
                          class="cert-status-tag"
                          effect="dark"
                        >
                          <i class="el-icon-time"></i> 待审核
                        </el-tag>
                      </div>
                      <div class="cert-info">
                        <span><strong>证书编号：</strong>{{ cert.certificateNo || '-' }}</span>
                        <span><strong>发证机构：</strong>{{ cert.issueOrg || '-' }}</span>
                        <span><strong>资质类型：</strong>{{ cert.qualificationType || '-' }}</span>
                        <span><strong>证书类型：</strong>{{ cert.certType || '-' }}</span>
                        <span><strong>颁发日期：</strong>{{ parseTime(cert.issueDate, '{y}-{m}-{d}') || '-' }}</span>
                        <span><strong>到期日期：</strong>{{ parseTime(cert.expireDate, '{y}-{m}-{d}') || '-' }}</span>
                        <span><strong>证书状态：</strong>{{ cert.certStatus || '-' }}</span>
                        <span><strong>审核状态：</strong>
                          <el-tag :type="getAuditStatusTagType(cert.auditStatus)" size="small">
                            {{ getAuditStatusText(cert.auditStatus) }}
                          </el-tag>
                        </span>
                        <span><strong>审核意见：</strong>{{ cert.auditOpinion || '-' }}</span>
                        <span><strong>审核时间：</strong>{{ parseTime(cert.auditTime) || '-' }}</span>
                      </div>

                      <div v-if="cert.certImage" class="cert-image-section">
                        <div class="image-title">
                          <strong>证书图片：</strong>
                        </div>
                        <div class="image-preview">
                          <el-image
                            style="width: 200px; height: 150px;"
                            :src="baseUrl + cert.certImage"
                            :preview-src-list="[baseUrl + cert.certImage]"
                            fit="contain"
                          >
                            <div slot="error" class="image-slot">
                              <i class="el-icon-picture-outline"></i>
                              <div>图片加载失败</div>
                            </div>
                          </el-image>
                        </div>
                      </div>

                      <div v-if="cert.certificateFiles" class="cert-files-section">
                        <div class="files-title">
                          <strong>其他附件：</strong>
                        </div>
                        <div class="files-list">
                          <el-button
                            type="text"
                            icon="el-icon-download"
                            @click="downloadFile(cert.certificateFiles)"
                            class="download-btn"
                          >
                            {{ getFileName(cert.certificateFiles) }}
                          </el-button>
                        </div>
                      </div>
                    </div>
                  </div>
                </el-tab-pane>
              </el-tabs>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="detailVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { listInfo, getInfo, auditBasicInfo, auditCertificate, listQualification } from "@/api/system/vetAduit"
import axios from 'axios'

export default {
  name: "Info",
  dicts: ['expert_type'],
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      infoList: [],
      baseUrl: process.env.VUE_APP_BASE_API,

      detailTitle: "",
      detailVisible: false,
      detailData: null,
      loadingDetail: false,
      detailActiveTab: "basicInfo",
      detailCertificates: [],
      loadingCertDetail: false,
      detailCertActiveTab: null,

      auditTitle: "",
      auditVisible: false,
      activeAuditTab: "basic",
      activeCertTab: null,
      currentVetId: null,
      currentUserId: null,
      showCertificateTab: true,

      loadingBasicData: false,
      submittingAll: false,
      basicInfo: {},
      basicAuditForm: {
        auditStatus: "",
        auditDesc: ""
      },
      basicAuditRules: {
        auditStatus: [
          { required: true, message: "请选择审核结果", trigger: "change" }
        ]
      },

      loadingCertData: false,
      certificateList: [],
      certAuditForms: {},
      certAuditRules: {
        auditStatus: [
          { required: true, message: "请选择审核结果", trigger: "change" }
        ]
      },

      imagePreviewVisible: false,
      previewImageUrl: "",

      certAuditTimer: null,

      queryParams: {
        pageNum: 1,
        pageSize: 10,
        realName: null,
        gender: null,
        idCard: null,
        workExperience: null,
        hospital: null,
      },

      title: "",
      open: false,
      form: {},
      rules: {
        realName: [
          { required: true, message: "真实姓名不能为空", trigger: "blur" }
        ],
        gender: [
          { required: true, message: "性别不能为空", trigger: "change" }
        ],
        idCard: [
          { required: true, message: "身份证号不能为空", trigger: "blur" }
        ]
      }
    }
  },
  computed: {
    canCompleteAudit() {
      if (this.basicInfo.auditStatus && this.basicInfo.auditStatus !== '0') {
        return true
      }
      if (this.basicAuditForm.auditStatus) {
        return true
      }
      return false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      listInfo(this.queryParams).then(response => {
        this.infoList = response.rows
        this.total = response.total
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },

    handleAudit(row) {
      this.resetAuditData()

      const id = row.id || this.ids[0]
      const vetName = row.realName || ''

      this.currentVetId = id
      this.auditTitle = `兽医信息审核 - ${vetName}`
      this.auditVisible = true
      this.activeAuditTab = "basic"

      this.loadBasicData(id)
    },

    handleTabClick(tab) {
      if (tab.name === 'certificate' && (!this.certificateList || this.certificateList.length === 0)) {
        if (this.basicInfo && this.basicInfo.userId) {
          this.loadCertificateData(this.basicInfo.userId)
        } else {
          this.$message.warning('无法获取用户信息')
        }
      }
    },

    loadBasicData(id) {
      this.loadingBasicData = true

      getInfo(id).then(response => {
        if (response.code === 200) {
          this.basicInfo = response.data || {}
          this.currentUserId = this.basicInfo.userId

          this.basicAuditForm = {
            auditStatus: this.basicInfo.auditStatus || "",
            auditDesc: this.basicInfo.auditDesc || ""
          }

        } else {
          this.$message.error(response.msg || '加载失败')
        }
      }).catch(error => {
        console.error('加载失败:', error)
        this.$message.error('加载失败')
      }).finally(() => {
        this.loadingBasicData = false
      })
    },

    loadCertificateData(userId) {
      this.loadingCertData = true

      const queryParams = {
        userId: userId,
        pageNum: 1,
        pageSize: 1000
      }

      listQualification(queryParams).then(response => {
        if (response.code === 200) {
          this.certificateList = response.rows || []

          if (this.certificateList.length === 0) {
            this.$message.info('该兽医暂无资质证书')
          } else {
            if (this.certificateList.length > 0) {
              this.activeCertTab = 'cert' + this.certificateList[0].qualificationId
            }
          }

          const forms = {}
          this.certificateList.forEach(cert => {
            forms[cert.qualificationId] = {
              qualificationId: cert.qualificationId,
              auditStatus: cert.auditStatus || "",
              auditOpinion: cert.auditOpinion || "",
              submitted: !!cert.auditStatus && cert.auditStatus !== '0',
              saving: false
            }
          })
          this.certAuditForms = forms

        } else {
          this.$message.error(response.msg || '加载证书列表失败')
        }
      }).catch(error => {
        console.error('加载证书列表失败:', error)
        this.$message.error('加载证书列表失败')
      }).finally(() => {
        this.loadingCertData = false
      })
    },

    handleCertAuditChange(qualificationId) {
      if (this.certAuditForms[qualificationId]) {
        this.certAuditForms[qualificationId].submitted = false
      }
    },

    saveCertificateAudit(qualificationId) {
      const formRef = this.$refs['certForm' + qualificationId]
      if (!formRef || !formRef[0]) return

      formRef[0].validate(valid => {
        if (valid) {
          const form = this.certAuditForms[qualificationId]
          if (!form.auditStatus) {
            this.$message.warning('请选择审核结果')
            return
          }

          form.saving = true

          const auditData = {
            qualificationId: qualificationId,
            auditStatus: form.auditStatus,
            auditOpinion: form.auditOpinion || ''
          }

          auditCertificate(auditData).then(response => {
            if (response.code === 200) {
              form.submitted = true

              const certIndex = this.certificateList.findIndex(c => c.qualificationId === qualificationId)
              if (certIndex !== -1) {
                this.certificateList[certIndex].auditStatus = form.auditStatus
                this.certificateList[certIndex].auditOpinion = form.auditOpinion
              }

              this.$message.success('证书审核已保存')
            } else {
              this.$message.error(response.msg || '保存失败')
            }
          }).catch(error => {
            console.error('保存证书审核失败:', error)
            this.$message.error('保存失败')
          }).finally(() => {
            form.saving = false
          })
        }
      })
    },

    resetCertAudit(qualificationId) {
      const cert = this.certificateList.find(c => c.qualificationId === qualificationId)
      if (cert) {
        this.certAuditForms[qualificationId] = {
          qualificationId: cert.qualificationId,
          auditStatus: cert.auditStatus || "",
          auditOpinion: cert.auditOpinion || "",
          submitted: !!cert.auditStatus && cert.auditStatus !== '0',
          saving: false
        }
        this.$message.info('已重置审核表单')
      }
    },

    submitAllAudit() {
      this.$refs.basicAuditForm.validate(valid => {
        if (!valid) {
          this.$message.warning('请完成基本信息审核')
          this.activeAuditTab = 'basic'
          return
        }

        let allCertAudited = true
        if (this.certificateList.length > 0) {
          for (let i = 0; i < this.certificateList.length; i++) {
            const cert = this.certificateList[i]
            const form = this.certAuditForms[cert.qualificationId]
            if (!form || !form.submitted) {
              allCertAudited = false
              break
            }
          }

          if (!allCertAudited) {
            this.$message.warning('请完成所有证书的审核')
            this.activeAuditTab = 'certificate'
            return
          }
        }

        this.submittingAll = true

        const auditData = {
          id: this.currentVetId,
          auditStatus: this.basicAuditForm.auditStatus,
          auditDesc: this.basicAuditForm.auditDesc
        }

        auditBasicInfo(auditData).then(response => {
          if (response.code === 200) {
            this.$message.success('审核提交成功')
            this.auditVisible = false
            this.getList()
          } else {
            this.$message.error(response.msg || '提交失败')
          }
        }).catch(error => {
          console.error('提交失败:', error)
          this.$message.error('提交失败')
        }).finally(() => {
          this.submittingAll = false
        })
      })
    },

    getCertSummaryText() {
      if (this.certificateList.length === 0) {
        return '暂无资质证书'
      }

      const total = this.certificateList.length
      const audited = Object.values(this.certAuditForms).filter(f => f.submitted).length
      const passed = this.certificateList.filter(c => c.auditStatus === '1').length
      const failed = this.certificateList.filter(c => c.auditStatus === '2').length

      return `共 ${total} 个证书，已审核 ${audited} 个，其中通过 ${passed} 个，不通过 ${failed} 个`
    },

    resetAuditData() {
      this.basicInfo = {}
      this.basicAuditForm = {
        auditStatus: "",
        auditDesc: ""
      }
      this.certificateList = []
      this.certAuditForms = {}
      this.currentVetId = null
      this.currentUserId = null
      this.activeCertTab = null
      if (this.certAuditTimer) {
        clearTimeout(this.certAuditTimer)
        this.certAuditTimer = null
      }
    },

    handleView(row) {
      this.detailVisible = true
      this.detailTitle = "兽医详情信息"
      this.loadingDetail = true
      this.detailActiveTab = "basicInfo"
      this.detailCertificates = []

      const id = row.id || this.ids[0]
      getInfo(id).then(response => {
        if (response.code === 200) {
          this.detailData = response.data

          if (response.data.userId) {
            const queryParams = {
              userId: response.data.userId,
              pageNum: 1,
              pageSize: 1000
            }

            listQualification(queryParams).then(certResponse => {
              if (certResponse.code === 200) {
                this.detailCertificates = certResponse.rows || []
                if (this.detailCertificates.length > 0) {
                  this.detailCertActiveTab = 'detailCert' + this.detailCertificates[0].qualificationId
                }
              }
            }).catch(error => {
              console.error('加载证书详情失败:', error)
            }).finally(() => {
              this.loadingDetail = false
            })
          } else {
            this.loadingDetail = false
          }
        } else {
          this.$message.error(response.msg || '获取详情失败')
          this.loadingDetail = false
        }
      }).catch(error => {
        console.error('获取详情失败:', error)
        this.$message.error('获取详情失败')
        this.loadingDetail = false
      })
    },

    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
    },

    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加兽医个人信息"
    },

    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids[0]
      getInfo(id).then(response => {
        if (response.code === 200) {
          this.form = response.data
          this.open = true
          this.title = "修改兽医个人信息"
        }
      })
    },

    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const api = this.form.id ?
            (data) => this.$axios.put('/system/vetInfo', data) :
            (data) => this.$axios.post('/system/vetInfo', data)

          api(this.form).then(response => {
            this.$modal.msgSuccess(this.form.id ? "修改成功" : "新增成功")
            this.open = false
            this.getList()
          }).catch(error => {
            this.$modal.msgError("操作失败")
          })
        }
      })
    },

    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除兽医个人信息编号为"' + ids + '"的数据项？').then(() => {
        this.$axios.delete('/system/vetInfo/' + ids).then(response => {
          this.getList()
          this.$modal.msgSuccess("删除成功")
        })
      }).catch(() => {})
    },

    getAuditStatusText(status) {
      if (!status || status === 'null' || status === 'undefined') {
        return '未审核'
      }
      const statusMap = {
        '0': '待审核',
        '1': '审核通过',
        '2': '审核不通过'
      }
      return statusMap[status] || '未审核'
    },

    getAuditStatusTagType(status) {
      if (!status || status === 'null' || status === 'undefined') {
        return 'info'
      }
      const typeMap = {
        '0': 'warning',
        '1': 'success',
        '2': 'danger'
      }
      return typeMap[status] || 'info'
    },

    cancel() {
      this.open = false
      this.reset()
    },

    closeDetail() {
      this.detailVisible = false
      this.detailData = null
      this.detailCertificates = []
    },

    reset() {
      this.form = {
        id: null,
        userId: null,
        realName: null,
        gender: null,
        birthday: null,
        idCard: null,
        specialty: null,
        workExperience: null,
        hospital: null,
        address: null,
        introduction: null,
        title: null,
        phone: null,
        email: null,
        expertType: null,
      }
      this.resetForm("form")
    },

    // 文件下载方法
    downloadFile(filePath) {
      if (!filePath) {
        this.$message.warning('文件路径为空，无法下载')
        return
      }

      const loading = this.$loading({
        lock: true,
        text: '正在下载文件...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      const fullUrl = this.baseUrl + filePath

      axios({
        method: 'get',
        url: fullUrl,
        responseType: 'blob', // 关键：设置响应类型为blob
        headers: {
        }
      }).then(response => {
        const blob = new Blob([response.data])
        const downloadUrl = window.URL.createObjectURL(blob)
        const a = document.createElement('a')

        a.download = this.getFileName(filePath)
        a.href = downloadUrl
        document.body.appendChild(a)
        a.click()

        window.URL.revokeObjectURL(downloadUrl)
        document.body.removeChild(a)

        this.$message.success('文件下载成功')
      }).catch(error => {
        console.error('文件下载失败:', error)
        this.$message.error('文件下载失败，请重试')
      }).finally(() => {
        loading.close()
      })
    },

    getFileName(filePath) {
      if (!filePath) return '未知文件'
      const parts = filePath.split(/[\\/]/)
      const fileName = parts.pop() || '未知文件'
      return fileName
    }
  }
}
</script>

<style scoped>
::v-deep .pagestyle .el-input{
  width: auto !important;
}
</style>

<style scoped lang="scss">
.audit-dialog {
  :deep(.el-dialog__body) {
    max-height: 70vh;
    overflow-y: auto;
    padding: 20px;
  }
}

.cert-tabs {
  margin-top: 15px;

  :deep(.el-tabs__header) {
    margin-bottom: 10px;
  }

  :deep(.el-tabs__item) {
    font-weight: 500;
    padding: 0 15px;
    height: 36px;
    line-height: 36px;

    &.is-active {
      background-color: #ecf5ff;
      border-bottom-color: #ecf5ff;
    }
  }
}

.tab-loading {
  text-align: center;
  padding: 60px 0;

  .el-icon-loading {
    font-size: 32px;
    color: #409EFF;
    margin-bottom: 15px;
  }

  div {
    color: #606266;
    font-size: 14px;
  }
}

.info-section {
  margin-bottom: 25px;

  h3 {
    margin-bottom: 15px;
    color: #303133;
    font-size: 16px;
    font-weight: 600;
    padding-bottom: 8px;
    border-bottom: 2px solid #409EFF;
  }
}

.audit-form-section {
  margin-top: 20px;

  h3 {
    margin-bottom: 15px;
    color: #303133;
    font-size: 16px;
    font-weight: 600;
  }
}

.audit-status-tag {
  margin-left: 15px;

  .el-tag {
    font-weight: 500;
  }
}

.certificate-section {
  h3 {
    margin-bottom: 15px;
    color: #303133;
    font-size: 16px;
    font-weight: 600;
    padding-bottom: 8px;
    border-bottom: 2px solid #67C23A;
  }
}

.certificate-item {
  border: 1px solid #ebeef5;
  border-radius: 6px;
  margin-bottom: 15px;
  padding: 20px;
  background-color: #fff;
  transition: all 0.3s ease;

  &:hover {
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }

  &.cert-audited {
    background-color: #f8f9fa;
    border-left: 4px solid #67C23A;
  }

  &.view-only {
    background-color: #fafafa;

    &:hover {
      box-shadow: none;
    }
  }
}

.cert-header {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px dashed #ebeef5;
}

.cert-title {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 15px;

  span {
    font-size: 13px;
    font-weight: 600;
    color: #303133;
    //flex: 1;
  }

  //.el-tag {
  //  font-weight: 500;
  //
  //  &.el-tag--success {
  //    background-color: rgba(103, 194, 58, 0.1);
  //    border-color: rgba(103, 194, 58, 0.2);
  //  }
  //
  //  &.el-tag--danger {
  //    background-color: rgba(245, 108, 108, 0.1);
  //    border-color: rgba(245, 108, 108, 0.2);
  //  }
  //
  //  &.el-tag--warning {
  //    background-color: rgba(230, 162, 60, 0.1);
  //    border-color: rgba(230, 162, 60, 0.2);
  //  }
  //}
}

.cert-info {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 12px;
  font-size: 14px;
  color: #606266;
  margin-bottom: 15px;

  span {
    display: flex;
    align-items: center;

    strong {
      min-width: 80px;
      color: #303133;
      font-weight: 500;
      margin-right: 8px;
    }

    .el-tag {
      margin-left: 5px;
    }
  }
}

.cert-image-section {
  margin-top: 15px;
  padding: 12px;
  background-color: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e4e7ed;

  .image-title {
    margin-bottom: 10px;
    font-size: 14px;
    color: #303133;
  }

  .image-preview {
    .el-image {
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      overflow: hidden;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

      .image-slot {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 100%;
        background: #f5f7fa;
        color: #909399;

        i {
          font-size: 30px;
          margin-bottom: 5px;
        }

        div {
          font-size: 12px;
        }
      }
    }
  }
}

.cert-files-section {
  margin-top: 15px;
  padding: 12px;
  background-color: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e4e7ed;

  .files-title {
    margin-bottom: 10px;
    font-size: 14px;
    color: #303133;
  }

  .files-list {
    color: #606266;
    font-size: 13px;

    // 新增：下载按钮样式
    .download-btn {
      color: #409EFF;
      padding: 0;
      height: auto;
      line-height: 1;

      &:hover {
        color: #66b1ff;
        text-decoration: underline;
      }

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

.cert-audit-form {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px dashed #ebeef5;
}

.audit-saved-tag {
  margin-left: 15px;

  .el-tag {
    font-weight: 500;
    background-color: rgba(103, 194, 58, 0.1);
    border-color: rgba(103, 194, 58, 0.2);
  }
}

.cert-summary {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 6px;
  border-left: 4px solid #409EFF;
}

.no-data {
  text-align: center;
  padding: 60px 0;

  .el-alert {
    max-width: 400px;
    margin: 0 auto;
  }
}

//.info-btn {
//  padding: 6px 12px;
//  border-radius: 4px;
//  margin: 0 4px;
//  transition: all 0.3s ease;
//  font-weight: 500;
//
//  &:hover {
//    transform: translateY(-2px);
//    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
//  }
//}
//
//.view-btn:hover {
//  background-color: rgba(243, 239, 231, 0.9);
//  border-color: #e6a23c;
//  color: #e6a23c;
//}
//
//.audit-btn:hover {
//  background-color: rgba(64, 158, 255, 0.15);
//  border-color: #409eff;
//  color: #409eff;
//}

:deep(.dialog-footer) {
  .el-button {
    min-width: 100px;

    &:last-child {
      margin-left: 10px;
    }
  }
}

:deep(.el-tabs__header) {
  margin-bottom: 0;
}

:deep(.el-tabs__item) {
  font-weight: 500;

  &.is-active {
    color: #409EFF;
    font-weight: 600;
  }
}

:deep(.el-tag) {
  &.el-tag--success {
    background-color: rgba(103, 194, 58, 0.1);
    border-color: rgba(103, 194, 58, 0.2);
  }

  &.el-tag--danger {
    background-color: rgba(245, 108, 108, 0.1);
    border-color: rgba(245, 108, 108, 0.2);
  }

  &.el-tag--warning {
    background-color: rgba(230, 162, 60, 0.1);
    border-color: rgba(230, 162, 60, 0.2);
  }
}

// 操作按钮样式
.info-btn {
  padding: 6px 10px;
  border-radius: 4px;
  margin: 0 10px;
  transition: all 0.3s ease;
}

.view-btn:hover {
  background-color: rgb(216, 238, 248);
  transform: translateY(-1px);
}

.audit-btn:hover {
  background-color: rgb(215, 223, 246);
  transform: translateY(-1px);
}

// 新增/修改的弹窗
::v-deep .el-dialog {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.12);
  animation: dialogFadeIn 0.3s ease;
}

::v-deep .el-dialog__header {
  background: linear-gradient(135deg, #2c7a4d 0%, #42b983 100%);
  padding: 18px 24px;
  border-bottom: none;
  position: relative;
}

::v-deep .el-dialog__title {
  font-size: 17px;
  font-weight: 600;
  color: white;
  letter-spacing: 0.5px;
}

::v-deep .el-dialog__headerbtn:hover .el-dialog__close {
  color: #ffd04b;
  transform: rotate(90deg);
}

::v-deep .el-dialog__body {
  padding: 28px 24px 20px;
  background-color: #f8fafc;
  max-height: 70vh;
  overflow-y: auto;
}

::v-deep .el-form-item {
  margin-bottom: 20px;
  transition: all 0.3s;
}

::v-deep .el-form-item__label {
  font-weight: 500;
  color: #2d3748;
  font-size: 14px;
  transition: color 0.3s;
}

::v-deep .el-input,
::v-deep .el-textarea,
::v-deep .el-select {
  width: 100%;
}

::v-deep .el-input__inner,
::v-deep .el-textarea__inner {
  border-radius: 8px;
  border: 1px solid #dcdfe6;
  font-size: 14px;
  transition: all 0.3s;
  background-color: #fcfdfe;
}

::v-deep .el-input__inner:focus,
::v-deep .el-textarea__inner:focus {
  border-color: #42B983;
  box-shadow: 0 0 0 3px rgb(230, 255, 238);
  background-color: white;
}

::v-deep .el-select .el-input__inner {
  padding-right: 35px;
}

::v-deep .el-dialog__footer {
  padding: 20px 24px;
  background-color: #f8fafc;
  border-top: 1px solid #eef2f7;
  border-radius: 0 0 12px 12px;
}

// 证书中的状态标签样式
.cert-status-tag {
  min-width: 70px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  border-radius: 16px;
  padding: 0 10px;
  font-weight: 500;
  letter-spacing: 0.3px;
  transition: all 0.3s ease;

  i {
    margin-right: 4px;
    font-size: 12px;
  }

  &:hover {
    transform: translateY(-1px);
    box-shadow: 0 3px 8px rgba(0, 0, 0, 0.15);
  }

  &.el-tag--success {
    background: linear-gradient(135deg, #2c7a4d 0%, #42b983 100%);
    border: none;
    color: white;
  }

  &.el-tag--danger {
    background: linear-gradient(135deg, #d9534f 0%, #f56c6c 100%);
    border: none;
    color: white;
  }

  &.el-tag--warning {
    background: linear-gradient(135deg, #ff8c00 0%, #ffb347 100%);
    border: none;
    color: white;
  }
}
</style>
