<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="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" />
      <el-table-column label="真实姓名" align="center" prop="realName" />
      <el-table-column label="擅长领域" align="center" prop="specialty" :show-overflow-tooltip="true" />
      <el-table-column label="职称" align="center" prop="title" />
      <el-table-column label="专家类型" align="center" prop="expertType" />
      <el-table-column label="所属医院" align="center" prop="hospital" :show-overflow-tooltip="true" />
      <el-table-column label="个人简介" align="center" prop="introduction" :show-overflow-tooltip="true" />
      <el-table-column label="审核状态" align="center" prop="auditStatus" width="100" class-name="audit-status-column">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.audit_status" :value="scope.row.auditStatus" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
        <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 v-if="scope.row.auditStatus != 1" 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" @close="closeAuditDialog" :destroy-on-close="true">
      <el-tabs v-model="activeAuditTab" type="border-card">
        <!-- 基本信息审核标签页 -->
        <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="当前审核状态">
                  <dict-tag :options="dict.type.audit_status" :value="basicInfo.auditStatus" />
                </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" @change="handleBasicAuditChange">
                    <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">
                    <dict-tag :options="dict.type.audit_status" :value="basicInfo.auditStatus" />
                  </span>
                </el-form-item>
                <el-form-item label="审核意见" prop="auditDesc" v-if="basicAuditForm.auditStatus === '2'">
                  <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">
          <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">
                <el-alert :title="`共 ${certificateList.length} 个资质证书待审核`" type="info" :closable="false" show-icon />
              </div>

              <!-- 证书列表展示 -->
              <div class="cert-list-section">
                <h3>证书列表</h3>
                <div v-for="(cert, index) in certificateList" :key="cert.qualificationId + '_' + index"
                  class="certificate-item-wrapper">
                  <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>
                        <dict-tag v-if="cert.auditStatus && cert.auditStatus !== '0'" :options="dict.type.audit_status"
                          :value="cert.auditStatus" class="cert-status-tag" />
                        <el-tag v-else 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>
                          <dict-tag :options="dict.type.qualification_type" :value="cert.qualificationType" />
                        </span>
                        <span><strong>经营范围：</strong>
                          <div class="jyfw">
                            <dict-tag style="display: grid;grid-template-columns: 1fr 1fr; row-gap: 5px;"
                              :options="dict.type.scope_names" :value="cert.scopeIds" />
                          </div>
                        </span>
                        <span><strong>颁发日期：</strong>{{ parseTime(cert.issueDate, '{y}-{m}-{d}') || '-' }}</span>
                        <span><strong>到期日期：</strong>{{ parseTime(cert.expireDate, '{y}-{m}-{d}') || '-' }}</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>
                </div>
              </div>

              <!-- 统一审核表单 -->
              <div class="cert-unified-audit-section">
                <div class="audit-form-section">
                  <h3>资质证书统一审核</h3>
                  <el-form ref="certAuditForm" :model="certAuditForm" :rules="certAuditRules" label-width="100px">
                    <el-form-item label="审核结果" prop="auditStatus">
                      <el-radio-group v-model="certAuditForm.auditStatus" @change="handleCertAuditChange">
                        <el-radio label="1">全部审核通过</el-radio>
                        <el-radio label="2">审核不通过</el-radio>
                      </el-radio-group>
                    </el-form-item>
                    <el-form-item label="审核意见" prop="auditOpinion" v-if="certAuditForm.auditStatus === '2'">
                      <el-input v-model="certAuditForm.auditOpinion" type="textarea" :rows="4"
                        placeholder="请输入审核意见（将应用于所有证书）" :maxlength="500" show-word-limit />
                    </el-form-item>
                  </el-form>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAllAudit" :loading="submittingAll" :disabled="!isAllAuditSelected || 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 :destroy-on-close="true">
      <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="当前审核状态">
                  <dict-tag :options="dict.type.audit_status" :value="detailData.auditStatus" />
                </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>

              <div v-for="(cert, index) in detailCertificates" :key="cert.qualificationId + '_detail_' + index"
                class="certificate-item-wrapper">
                <div class="certificate-item view-only">
                  <div class="cert-header">
                    <div class="cert-title">
                      <span>{{ cert.certName || cert.qualificationType || `证书${index + 1}` }}</span>
                      <dict-tag :options="dict.type.audit_status" :value="cert.auditStatus" class="cert-status-tag" />
                    </div>
                    <div class="cert-info">
                      <span><strong>证书编号：</strong>{{ cert.certificateNo || '-' }}</span>
                      <span><strong>发证机构：</strong>{{ cert.issueOrg || '-' }}</span>
                      <span><strong>资质类型：</strong>
                        <dict-tag :options="dict.type.qualification_type" :value="cert.qualificationType" />
                      </span>
                      <span><strong>经营范围：</strong>
                        <div class="jyfw">
                          <dict-tag style="display: grid;grid-template-columns: 1fr 1fr; row-gap: 5px;"
                            :options="dict.type.scope_names" :value="cert.scopeIds" />
                        </div>
                      </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.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>
              </div>
            </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, delvetInfo } from "@/api/system/vetAduit"
import axios from 'axios'

export default {
  name: "Info",
  dicts: ['expert_type', 'audit_status', 'qualification_type', 'scope_names'],
  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: [],

      auditTitle: "",
      auditVisible: false,
      activeAuditTab: "basic",
      currentVetId: null,
      currentUserId: null,

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

      certificateList: [],
      // 统一证书审核表单
      certAuditForm: {
        auditStatus: "",
        auditOpinion: ""
      },
      certAuditRules: {
        auditStatus: [
          { required: true, message: "请选择证书审核结果", trigger: "change" }
        ]
      },

      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: {
    // 判断是否所有审核项都已选择审核结果
    isAllAuditSelected() {
      // 基本信息未选择审核结果（审核状态必须是1或2）
      if (!this.basicAuditForm.auditStatus ||
        (this.basicAuditForm.auditStatus !== '1' && this.basicAuditForm.auditStatus !== '2')) {
        return false
      }

      // 如果有证书，需要统一证书审核已选择结果
      if (this.certificateList && this.certificateList.length > 0) {
        if (!this.certAuditForm.auditStatus ||
          (this.certAuditForm.auditStatus !== '1' && this.certAuditForm.auditStatus !== '2')) {
          return false
        }
      }

      return true
    }
  },
  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) {
      // 防止在提交过程中再次打开审核对话框
      if (this.submittingAll) {
        this.$message.warning('正在提交审核，请稍后...')
        return
      }
      
      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.loadAllData(id)
    },

    // 同时加载基本信息和证书数据
    async loadAllData(vetId) {
      this.loadingBasicData = true
      this.loadingCertData = true

      try {
        // 加载基本信息
        const basicResponse = await getInfo(vetId)
        if (basicResponse.code === 200) {
          this.basicInfo = basicResponse.data || {}
          this.currentUserId = this.basicInfo.userId

          // 如果基本信息已经有审核状态（1或2），则回显
          if (this.basicInfo.auditStatus && this.basicInfo.auditStatus !== '0') {
            this.basicAuditForm = {
              auditStatus: this.basicInfo.auditStatus,
              auditDesc: this.basicInfo.auditDesc || ""
            }
          } else {
            this.basicAuditForm = {
              auditStatus: "",
              auditDesc: ""
            }
          }
        } else {
          this.$message.error(basicResponse.msg || '加载基本信息失败')
        }

        // 加载证书数据
        if (this.currentUserId) {
          const queryParams = {
            userId: this.currentUserId,
            pageNum: 1,
            pageSize: 1000
          }

          const certResponse = await listQualification(queryParams)
          if (certResponse.code === 200) {
            this.certificateList = certResponse.rows || []

            // 检查所有证书的审核状态是否一致
            const allCertAudited = this.certificateList.every(cert =>
              cert.auditStatus && cert.auditStatus !== '0'
            )
            const allCertSameStatus = this.certificateList.length > 0 &&
              this.certificateList.every(cert => cert.auditStatus === this.certificateList[0].auditStatus)

            // 如果所有证书都已审核且状态一致，则回显
            if (allCertAudited && allCertSameStatus && this.certificateList.length > 0) {
              this.certAuditForm = {
                auditStatus: this.certificateList[0].auditStatus,
                auditOpinion: this.certificateList[0].auditOpinion || ""
              }
            } else {
              this.certAuditForm = {
                auditStatus: "",
                auditOpinion: ""
              }
            }
          } else {
            this.$message.error(certResponse.msg || '加载证书列表失败')
          }
        }
      } catch (error) {
        console.error('加载数据失败:', error)
        this.$message.error('加载数据失败')
      } finally {
        this.loadingBasicData = false
        this.loadingCertData = false
      }
    },

    handleBasicAuditChange(e) {
      console.log(e);
      // 如果选择审核通过，清空审核意见
      if (this.basicAuditForm.auditStatus === '1') {
        this.basicAuditForm.auditDesc = ''
      }
    },

    handleCertAuditChange(e) {
      console.log(e);
      // 如果选择审核通过，清空审核意见
      if (this.certAuditForm.auditStatus === '1') {
        this.certAuditForm.auditOpinion = ''
      }
    },

    // 提交所有审核
    async submitAllAudit() {
      // 防止重复提交
      if (this.submittingAll) {
        // this.$message.warning('数据正在处理中，请勿重复提交')
        return
      }

      // 验证基本信息审核结果
      if (!this.basicAuditForm.auditStatus ||
        (this.basicAuditForm.auditStatus !== '1' && this.basicAuditForm.auditStatus !== '2')) {
        this.$message.warning('请选择基本信息审核结果')
        this.activeAuditTab = 'basic'
        return
      }

      // 验证基本信息审核意见（不通过时必须填写）
      if (this.basicAuditForm.auditStatus === '2' && (!this.basicAuditForm.auditDesc || this.basicAuditForm.auditDesc.trim() === '')) {
        this.$message.warning('审核不通过时，请填写审核意见')
        this.activeAuditTab = 'basic'
        return
      }

      // 验证证书统一审核
      if (this.certificateList && this.certificateList.length > 0) {
        if (!this.certAuditForm.auditStatus ||
          (this.certAuditForm.auditStatus !== '1' && this.certAuditForm.auditStatus !== '2')) {
          this.$message.warning('请选择证书审核结果')
          this.activeAuditTab = 'certificate'
          return
        }

        // 审核不通过时必须填写审核意见
        if (this.certAuditForm.auditStatus === '2' && (!this.certAuditForm.auditOpinion || this.certAuditForm.auditOpinion.trim() === '')) {
          this.$message.warning('证书审核不通过时，请填写审核意见')
          this.activeAuditTab = 'certificate'
          return
        }
      }

      this.submittingAll = true

      try {
        // 提交基本信息审核
        const basicAuditData = {
          id: this.currentVetId,
          auditStatus: this.basicAuditForm.auditStatus,
          auditDesc: this.basicAuditForm.auditDesc || ''
        }

        const basicResult = await auditBasicInfo(basicAuditData)
        
        if (basicResult.code !== 200) {
          throw new Error(basicResult.msg || '基本信息审核提交失败')
        }

        // 提交证书审核（如果有证书）
        if (this.certificateList && this.certificateList.length > 0) {
          // 使用 Promise.all 并发提交所有证书审核
          const certPromises = this.certificateList.map(cert => {
            const certAuditData = {
              qualificationId: cert.qualificationId,
              auditStatus: this.certAuditForm.auditStatus,
              auditOpinion: this.certAuditForm.auditOpinion || ''
            }
            return auditCertificate(certAuditData)
          })

          const certResults = await Promise.all(certPromises)
          
          // 检查是否有失败的证书审核
          const failedCert = certResults.find(result => result.code !== 200)
          if (failedCert) {
            throw new Error(failedCert.msg || '部分证书审核提交失败')
          }
        }

        // 所有审核提交成功
        this.$modal.msgSuccess('审核提交成功')
        this.auditVisible = false
        this.getList()
        
      } catch (error) {
        console.error('提交失败:', error)
        this.$modal.msgError(error.message || '提交失败')
      } finally {
        this.submittingAll = false
      }
    },

    resetAuditData() {
      this.basicInfo = {}
      this.basicAuditForm = {
        auditStatus: "",
        auditDesc: ""
      }
      this.certificateList = []
      this.certAuditForm = {
        auditStatus: "",
        auditOpinion: ""
      }
      this.currentVetId = null
      this.currentUserId = null
      this.loadingBasicData = false
      this.loadingCertData = false
    },

    closeAuditDialog() {
      // 如果正在提交，不允许关闭
      if (this.submittingAll) {
        this.$message.warning('正在提交审核，请稍后...')
        return
      }
      this.resetAuditData()
    },

    handleView(row) {
      // 防止在提交过程中打开详情
      if (this.submittingAll) {
        this.$message.warning('请等待当前操作完成')
        return
      }
      
      this.detailVisible = true
      this.detailTitle = "兽医详情信息"
      this.loadingDetail = true
      this.detailActiveTab = "basicInfo"
      this.detailCertificates = []

      const id = row.id
      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 || []
              }
            }).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(() => {
        return delvetInfo(ids)
      }).then(() => {
        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',
        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>
.el-tooltip__popper {
  width: 300px !important;
}
</style>

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

::v-deep .jyfw .el-tag:nth-child(1) {
  width: 70px !important;
  margin-left: 10px;
}
</style>

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

.certificate-item-wrapper {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

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

.cert-list-section {
  margin-top: 30px;

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

.cert-unified-audit-section {
  margin-top: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

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

.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-summary {
  margin-bottom: 20px;

  .el-alert {
    border-radius: 6px;
  }
}

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

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

: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>