<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="真实姓名" prop="realName">
        <el-input
          v-model="queryParams.realName"
          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="qualificationType">
        <el-select
          v-model="queryParams.qualificationType"
          placeholder="请选择资质类型"
          style="width: 100%;"
          @keyup.enter.native="handleQuery"
        >
          <el-option
            v-for="dict in dict.type.qualification_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
<!--      <el-form-item label="资质类型" prop="qualificationType">-->
<!--        <el-input-->
<!--          v-model="queryParams.qualificationType"-->
<!--          placeholder="请输入资质类型"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="证书编号" prop="certificateNo">-->
<!--        <el-input-->
<!--          v-model="queryParams.certificateNo"-->
<!--          placeholder="请输入证书编号"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="审核状态" prop="auditStatus">
        <el-select v-model="queryParams.auditStatus" placeholder="审核状态" clearable style="width: 100px">
          <el-option
            v-for="dict in dict.type.qualification_shenhe"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </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:qualification: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:qualification: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:qualification:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="warning"-->
      <!--          plain-->
      <!--          icon="el-icon-download"-->
      <!--          size="mini"-->
      <!--          @click="handleExport"-->
      <!--          v-hasPermi="['vet:qualification:export']"-->
      <!--        >导出</el-button>-->
      <!--      </el-col>-->
<!--      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
<!--    </el-row>-->

    <!-- 表格 -->
    <el-table v-loading="loading" :data="qualificationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!--      <el-table-column label="资质ID" align="center" prop="qualificationId" v-if="false" />-->
      <!--      <el-table-column label="真实姓名" align="center" prop="realName" />-->
      <!--      <el-table-column label="身份证号" align="center" prop="idCard" />-->
      <el-table-column label="真实姓名" align="center" prop="realName" width="150" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span v-if="scope.row.realName">{{ scope.row.realName }}</span>
          <span v-else style="color: #909399">-</span>
        </template>
      </el-table-column>
      <el-table-column label="身份证号" align="center" prop="idCard" width="200">
        <template slot-scope="scope">
          <span v-if="scope.row.idCard">{{ scope.row.idCard }}</span>
          <span v-else style="color: #909399">-</span>
        </template>
      </el-table-column>
      <el-table-column label="资质类型" align="center" prop="qualificationType" width="150">
        <template slot-scope="scope">
          <span>{{ formatQualificationType(scope.row.qualificationType) }}</span>
        </template>
      </el-table-column>
      <!--      <el-table-column label="证书编号" align="center" prop="certificateNo" />-->
      <!--      <el-table-column label="证书编号" align="center" prop="certificateNo" width="150">-->
      <!--        <template slot-scope="scope">-->
      <!--          <span v-if="scope.row.certificateNo">{{ scope.row.certificateNo }}</span>-->
      <!--          <span v-else style="color: #909399">-</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--      &lt;!&ndash; 新增的证书字段 &ndash;&gt;-->
      <!--      <el-table-column label="证书名称" align="center" prop="certName" width="150">-->
      <!--        <template slot-scope="scope">-->
      <!--          <span v-if="scope.row.certName">{{ scope.row.certName }}</span>-->
      <!--          <span v-else style="color: #909399">-</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--      <el-table-column label="发证机构" align="center" prop="issueOrg" width="150">-->
      <!--        <template slot-scope="scope">-->
      <!--          <span v-if="scope.row.issueOrg">{{ scope.row.issueOrg }}</span>-->
      <!--          <span v-else style="color: #909399">-</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--      <el-table-column label="证书文件" prop="certificateFiles">-->
      <!--        <template slot-scope="scope">-->
      <!--&lt;!&ndash;          <span v-if="scope.row.certificateFiles">{{ scope.row.certificateFiles }}</span>&ndash;&gt;-->
      <!--          <span v-if="scope.row.certificateFiles">{{ getImageUrl(scope.row.certificateFiles) }}</span>-->
      <!--          <span v-else style="color: #909399">-</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--      <el-table-column label="到期日期" align="center" prop="expireDate" width="180">-->
      <!--        <template slot-scope="scope">-->
      <!--          <span v-if="scope.row.expireDate">{{ parseTime(scope.row.expireDate, '{y}-{m}-{d}') }}</span>-->
      <!--          <span v-else style="color: #909399">-</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--      <el-table-column label="证书状态" align="center" prop="certStatus" width="100">-->
      <!--        <template slot-scope="scope">-->
      <!--          <el-tag :type="getCertStatusType(scope.row.certStatus)" size="small">-->
      <!--            {{ getCertStatusLabel(scope.row.certStatus) }}-->
      <!--          </el-tag>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="申请时间" align="center" prop="applyTime" width="180">
        <template slot-scope="scope">
          <span v-if="scope.row.applyTime">{{ parseTime(scope.row.applyTime, '{y}-{m}-{d}') }}</span>
          <span v-else style="color: #909399">-</span>
        </template>
      </el-table-column>
      <el-table-column label="审核时间" align="center" prop="auditTime" width="180">
        <template slot-scope="scope">
          <span v-if="scope.row.auditTime">{{ parseTime(scope.row.auditTime, '{y}-{m}-{d}') }}</span>
          <span v-else style="color: #909399">-</span>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="auditStatus" width="100">
        <template slot-scope="scope">
          <el-tag :type="getAuditStatusType(scope.row.auditStatus)" size="small">
            {{ getDictLabel('qualification_shenhe', scope.row.auditStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" width="150" :show-overflow-tooltip="true"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="300">
        <template slot-scope="scope">
          <!-- 查看按钮 -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['vet:qualification:query']"
            class="info-btn view-btn"
          >详情</el-button>

          <!-- 修改按钮 -->
          <!--          <el-button-->
          <!--            v-if="!scope.row.auditStatus || scope.row.auditStatus === '0' || scope.row.auditStatus === '2'"-->
          <!--            size="mini"-->
          <!--            type="text"-->
          <!--            icon="el-icon-edit"-->
          <!--            style="color: #42B983"-->
          <!--            @click="handleUpdate(scope.row)"-->
          <!--            v-hasPermi="['vet:qualification:edit']"-->
          <!--          >修改</el-button>-->

          <!-- 提交/重新提交按钮 -->
          <!--          <el-button-->
          <!--            v-if="!scope.row.auditStatus || scope.row.auditStatus === '2'"-->
          <!--            size="mini"-->
          <!--            type="text"-->
          <!--            icon="el-icon-s-check"-->
          <!--            style="color: #409EFF"-->
          <!--            @click="handleSubmitAudit(scope.row)"-->
          <!--            v-hasPermi="['vet:qualification:edit']"-->
          <!--          >{{ !scope.row.auditStatus ? '提交审核' : '重新提交' }}</el-button>-->

          <!-- 下架按钮：已上架状态显示 -->
          <!--          <el-button-->
          <!--            v-if="scope.row.auditStatus === '1'"-->
          <!--            size="mini"-->
          <!--            type="text"-->
          <!--            icon="el-icon-bottom"-->
          <!--            style="color: #E6A23C"-->
          <!--            @click="handleUnshelf(scope.row)"-->
          <!--            v-hasPermi="['vet:qualification:unshelf']"-->
          <!--          >下架</el-button>-->

          <!-- 上架按钮：已下架状态显示 -->
          <!--          <el-button-->
          <!--            v-if="scope.row.auditStatus === '3'"-->
          <!--            size="mini"-->
          <!--            type="text"-->
          <!--            icon="el-icon-top"-->
          <!--            style="color: #67C23A"-->
          <!--            @click="handleShelf(scope.row)"-->
          <!--            v-hasPermi="['vet:qualification:shelf']"-->
          <!--          >上架</el-button>-->

          <!-- 删除按钮 -->
          <!--          <el-button-->
          <!--            v-if="!scope.row.auditStatus || scope.row.auditStatus === '2'"-->
          <!--            size="mini"-->
          <!--            type="text"-->
          <!--            icon="el-icon-delete"-->
          <!--            style="color: #f56c6c"-->
          <!--            @click="handleDelete(scope.row)"-->
          <!--            v-hasPermi="['vet:qualification:remove']"-->
          <!--          >删除</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="title" :visible.sync="openDetail" width="80%" append-to-body>
      <div v-if="detailData" style="padding: 20px;">
        <div>
          <el-alert
            v-if="!certificateList || certificateList.length === 0"
            title="暂无资质证书"
            type="info"
            :closable="false"
            style="margin-bottom: 20px;"
          />
          <el-table v-else :data="certificateList" border style="width: 100%">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column prop="certificateNo" label="证书编号" align="center" width="150" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <span>{{ scope.row.certificateNo }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="certName" label="证书名称" align="center" width="150" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <span>{{ scope.row.certName }}</span>
              </template>
            </el-table-column>
            <el-table-column label="发证机构" align="center" prop="issueOrg" width="150" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <span v-if="scope.row.issueOrg">{{ scope.row.issueOrg }}</span>
                <span v-else style="color: #909399">-</span>
              </template>
            </el-table-column>
            <el-table-column label="证书文件" prop="certificateFiles">
              <template slot-scope="scope">
                <span v-if="scope.row.certificateFiles">
                  <template v-if="isImageFile(scope.row.certificateFiles)">
                    <el-button
                      type="text"
                      icon="el-icon-view"
                      @click="previewCertificate(scope.row.certificateFiles)"
                      style="color: #409EFF;"
                    >
                    </el-button>
                  </template>
                  <template v-else-if="isPdfFile(scope.row.certificateFiles)">
                    <el-button
                      type="text"
                      icon="el-icon-download"
                      @click="downloadFile(scope.row.certificateFiles)"
                      style="color: #287c07;"
                    >
                    </el-button>
                  </template>
                  <template v-else>
                    {{ getImageUrl(scope.row.certificateFiles) }}
                  </template>
                </span>
                <span v-else style="color: #909399">-</span>
              </template>
            </el-table-column>
            <el-table-column prop="issueDate" label="发证日期" align="center" width="150">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.issueDate, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="expireDate" label="到期日期" align="center" width="150">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.expireDate, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="证书状态" align="center" prop="certStatus" width="100">
              <template slot-scope="scope">
                <el-tag :type="getCertStatusType(scope.row.certStatus)" size="small">
                  {{ getCertStatusLabel(scope.row.certStatus) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="300">
              <template slot-scope="scope">
                <el-button
                  v-if="!detailData.auditStatus || detailData.auditStatus === '0' || detailData.auditStatus === '2'"
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  style="color: #42B983"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['vet:qualification:edit']"
                  class = "info-btn alter-btn"
                >修改</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDetail">关 闭</el-button>
      </div>

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

    <!-- 图片预览弹窗 -->
    <el-dialog :visible.sync="previewDialogVisible" width="80%" append-to-body>
      <div style="text-align: center; padding: 20px;">
        <img
          :src="getImageUrl(previewFileUrl)"
          style="max-width: 100%; max-height: 70vh; height: auto;"
          preview-teleported
          :preview-src-list="[getImageUrl(previewFileUrl)]"
        />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeimage">关 闭</el-button>
      </div>
    </el-dialog>

    <!--     添加或修改兽医资质弹窗-->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!--        <el-form-item label="真实姓名" prop="realName">-->
        <!--          <el-input v-model="form.realName" placeholder="请输入真实姓名" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="身份证号" prop="idCard">-->
        <!--          <el-input v-model="form.idCard" placeholder="请输入身份证号" />-->
        <!--        </el-form-item>-->
<!--        <el-form-item label="资质类型" prop="qualificationType">-->
<!--          <el-select-->
<!--            v-model="form.qualificationType"-->
<!--            placeholder="请选择资质类型"-->
<!--            style="width: 100%;"-->
<!--          >-->
<!--            <el-option-->
<!--              v-for="dict in dict.type.qualification_type"-->
<!--              :key="dict.value"-->
<!--              :label="dict.label"-->
<!--              :value="dict.value"-->
<!--            />-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <el-form-item label="证书编号" prop="certificateNo">
          <el-input v-model="form.certificateNo" placeholder="请输入证书编号" />
        </el-form-item>
        <el-form-item label="证书名称" prop="certName">
          <el-input v-model="form.certName" placeholder="请输入证书名称" />
        </el-form-item>
        <el-form-item label="发证机构" prop="issueOrg">
          <el-input v-model="form.issueOrg" placeholder="请输入发证机构" />
        </el-form-item>
        <el-form-item label="发证日期" prop="issueDate">
          <el-date-picker clearable
                          v-model="form.issueDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择发证日期"
                          style="width: 100%">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="到期日期" prop="expireDate">
          <el-date-picker clearable
                          v-model="form.expireDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择到期日期"
                          style="width: 100%">
          </el-date-picker>
        </el-form-item>
<!--        <el-form-item label="证书图片" prop="certImage">-->
<!--          <image-upload v-model="form.certImage"/>-->
<!--        </el-form-item>-->
        <el-form-item label="证书文件" prop="certificateFiles">
<!--&lt;!&ndash;          <el-input v-model="form.certificateFiles" type="textarea" placeholder="请输入内容" />&ndash;&gt;-->
          <file-upload
            v-model="form.certificateFiles"
            :limit="1"
            :file-type="['pdf','png','jpg','jpeg']"
          />
        </el-form-item>
<!--        <el-form-item label="提前提醒天数" prop="remindDays">-->
<!--          <el-input v-model="form.remindDays" placeholder="请输入提前提醒天数" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="备注" prop="remark">-->
<!--          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="resubmitForm">重新提交审核</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listQualification, getQualificationCertificate, delQualification, getQualificationCertificates, updateAndSubmitQualification, listQualificationCertificates} from "@/api/vet/qualification"

export default {
  name: "Qualification",
  dicts: ['qualification_shenhe', 'expert_type', 'qualification_type'],
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      // 待预览的证书文件路径
      previewFileUrl: '',
      // 遮罩层
      loading: true,
      detailLoading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 兽医资质表格数据
      qualificationList: [],
      // 资质证书列表
      certificateList: [],
      // 详情数据
      detailData: null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openDetail: false,
      previewDialogVisible: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        realName: null,
        idCard: null,
        qualificationType: null,
        certificateNo: null,
        auditStatus: null,
        certName: null,
        issueOrg: null,
        expireDate: null,
        certStatus: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // realName: [
        //   { required: true, message: "真实姓名不能为空", trigger: "blur" }
        // ],
        // idCard: [
        //   { required: true, message: "身份证号不能为空", trigger: "blur" }
        // ],
        // qualificationType: [
        //   { required: true, message: "资质类型不能为空", trigger: "change" }
        // ],
        certificateNo: [
          { required: true, message: "证书编号不能为空", trigger: "blur" }
        ],
        certName: [
          { required: true, message: "证书名称不能为空", trigger: "blur" }
        ],
        issueOrg: [
          { required: true, message: "发证机构不能为空", trigger: "blur" }
        ],
        issueDate: [
          { required: true, message: "发证日期不能为空", trigger: "change" }
        ],
        expireDate: [
          { required: true, message: "到期日期不能为空", trigger: "change" }
        ],
        certificateFiles: [
          { required: true, message: "证书文件不能为空", trigger: "blur" }
        ],
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 查询兽医资质列表
    getList() {
      this.loading = true
      listQualification(this.queryParams).then(response => {
        this.qualificationList = response.rows
        this.total = response.total
        this.loading = false
      })
    },

    // 获取证书状态标签
    getCertStatusLabel(status) {
      const map = {
        '0': '正常',
        '1': '即将过期',
        '2': '已过期'
      }
      return map[status] || status || '-'
    },

    // 获取证书状态标签类型
    getCertStatusType(status) {
      const map = {
        '0': 'success',
        '1': 'warning',
        '2': 'danger'
      }
      return map[status] || 'info'
    },

    // 获取审核状态标签类型
    getAuditStatusType(status) {
      const map = {
        '0': 'info',     // 待审核 - 蓝色
        '1': 'success',  // 已上架 - 绿色
        '2': 'danger',   // 已拒绝 - 红色
        '3': 'warning'   // 已下架 - 黄色
      }
      return map[status] || 'info'
    },

    // 格式化资质类型显示
    formatQualificationType(status) {
      const map = {
        '1': '执业兽医师',
        '2': '执业助理兽医',
        '3': '官方兽医',
        '4': '乡村兽医'
      }
      return map[status] || 'info'
    },

    // 获取完整的图片URL
    getImageUrl(filePath) {
      return `${this.baseUrl}${filePath}`
    },

    // 判断是否为图片文件
    isImageFile(filePath) {
      if (!filePath) return false;
      const imageExts = ['.png','.jpg','.jpeg'];
      const ext = filePath.substring(filePath.lastIndexOf('.')).toLowerCase();
      return imageExts.includes(ext);
    },

    // 判断是否为PDF文件
    isPdfFile(filePath) {
      if (!filePath) return false;
      const ext = filePath.substring(filePath.lastIndexOf('.')).toLowerCase();
      return ext === '.pdf';
    },

    // 预览图片
    previewCertificate(filePath) {
      this.previewFileUrl = filePath;
      this.previewDialogVisible = true;
    },

    // 下载文件
    downloadFile(filePath) {
      const fullUrl = this.getImageUrl(filePath);
      const link = document.createElement('a');
      link.href = fullUrl;

      const fileName = filePath.substring(filePath.lastIndexOf('/') + 1);
      link.download = fileName;

      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      this.$modal.msgSuccess('开始下载文件');
    },

    /** 下架操作 */
    // handleUnshelf(row) {
    //   this.$prompt('请输入下架原因', '下架确认', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     inputPlaceholder: '请输入下架原因（如：证书过期、违规操作等）',
    //     inputValidator: (value) => {
    //       if (!value || value.trim().length < 2) {
    //         return '下架原因不能少于2个字'
    //       }
    //       if (value.trim().length > 200) {
    //         return '下架原因不能超过200字'
    //       }
    //       return true
    //     }
    //   }).then(({ value }) => {
    //     this.loading = true
    //     unshelfQualification(row.qualificationId, value).then(response => {
    //       this.loading = false
    //       if (response.code === 200) {
    //         this.$modal.msgSuccess('下架成功')
    //         this.getList() // 刷新列表
    //       } else {
    //         this.$modal.msgError(response.msg || '下架失败')
    //       }
    //     }).catch(error => {
    //       this.loading = false
    //       this.$modal.msgError(error.msg || '下架失败')
    //     })
    //   }).catch(() => {
    //     // 用户取消操作
    //   })
    // },

    /** 上架操作 */
    // handleShelf(row) {
    //   this.$confirm('确认要上架此资质吗？', '上架确认', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   }).then(() => {
    //     this.loading = true
    //     shelfQualification(row.qualificationId).then(response => {
    //       this.loading = false
    //       if (response.code === 200) {
    //         this.$modal.msgSuccess('上架成功')
    //         this.getList() // 刷新列表
    //       } else {
    //         this.$modal.msgError(response.msg || '上架失败')
    //       }
    //     }).catch(error => {
    //       this.loading = false
    //       this.$modal.msgError(error.msg || '上架失败')
    //     })
    //   }).catch(() => {
    //     // 用户取消操作
    //   })
    // },

    /** 提交审核操作 */
    // handleSubmitAudit(row) {
    //   this.$modal.confirm('确认提交 "' + row.realName + '" 的资质进行审核？').then(() => {
    //     // 准备提交数据
    //     const submitData = {
    //       qualificationId: row.qualificationId,
    //       realName: row.realName,
    //       idCard: row.idCard,
    //       qualificationType: row.qualificationType,
    //       certificateNo: row.certificateNo,
    //       certName: row.certName,
    //       issueOrg: row.issueOrg,
    //       issueDate: row.issueDate,
    //       expireDate: row.expireDate,
    //       certImage: row.certImage,
    //       certificateFiles: row.certificateFiles,
    //       remark: row.remark,
    //       // 提交审核时设置审核状态为待审核(0)
    //       auditStatus: '0'
    //     }
    //
    //     return submitQualification(submitData)
    //   }).then(response => {
    //     if (response.code === 200) {
    //       this.$modal.msgSuccess("提交审核成功")
    //       this.getList()
    //     } else {
    //       this.$modal.msgError(response.msg || "提交审核失败")
    //     }
    //   }).catch(() => {
    //   })
    // },

    // 重新提交审核
    resubmitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let certId = this.form.certId || this.form.certificateId || this.form.id
          if (certId && typeof certId === 'object') {
            certId = certId.value || certId.id || certId.certificateId
          }
          certId = String(certId || '')
          if (!certId || certId === 'null' || certId === 'undefined' || certId === 'NaN') {
            this.$modal.msgError("证书ID无效：" + certId)
            return
          }

          const submitData = {
            certId: certId,
            qualificationId: this.form.qualificationId,
            realName: this.form.realName,
            idCard: this.form.idCard,
            qualificationType: this.form.qualificationType,
            certificateNo: this.form.certificateNo,
            certName: this.form.certName,
            issueOrg: this.form.issueOrg,
            issueDate: this.form.issueDate,
            expireDate: this.form.expireDate,
            certificateFiles: this.form.certificateFiles,
            remark: this.form.remark,
            auditStatus: '0',
            auditOpinion: null,
            applyTime: new Date().toISOString(),
          }

          updateAndSubmitQualification(submitData).then(response => {
            if (response.code === 200) {
              this.$modal.msgSuccess("重新提交审核成功")
              this.open = false
              this.getList()

              if (this.openDetail && this.detailData && this.detailData.qualificationId) {
                getQualificationCertificates(this.detailData.qualificationId).then(response => {
                  if (response.code === 200) {
                    this.certificateList = response.rows || [];
                    const updatedCertificate = this.certificateList.find(cert =>
                      cert.certificateId === certId || cert.certId === certId
                    );
                    if (updatedCertificate) {
                      this.certificateList = this.certificateList.map(cert => {
                        if (cert.certificateId === certId || cert.certId === certId) {
                          return {
                            ...cert,
                            auditStatus: '0',
                            applyTime: new Date().toISOString(),
                            auditTime: null,
                            auditOpinion: null
                          }
                        }
                        return cert;
                      });
                    }
                  }
                })
              }
              this.reset()
            } else {
              this.$modal.msgError(response.msg || "重新提交审核失败")
            }
          })
        }
      })
    },

    /** 查看详情 */
    // handleView(row) {
    //   // 构建详情内容
    //   let detailContent = `
    //     <table style="width:100%; border-collapse: collapse;">
    //       <tr>
    //         <td style="padding:8px 5px; border-bottom: 1px solid #eee; color: #666;">姓名：</td>
    //         <td style="padding:8px 5px; border-bottom: 1px solid #eee;">${row.realName || '-'}</td>
    //       </tr>
    //       <tr>
    //         <td style="padding:8px 5px; border-bottom: 1px solid #eee; color: #666;">身份证：</td>
    //         <td style="padding:8px 5px; border-bottom: 1px solid #eee;">${row.idCard || '-'}</td>
    //       </tr>
    //       <tr>
    //         <td style="padding:8px 5px; border-bottom: 1px solid #eee; color: #666;">证书编号：</td>
    //         <td style="padding:8px 5px; border-bottom: 1px solid #eee;">${row.certificateNo || '-'}</td>
    //       </tr>
    //       <tr>
    //         <td style="padding:8px 5px; border-bottom: 1px solid #eee; color: #666;">证书名称：</td>
    //         <td style="padding:8px 5px; border-bottom: 1px solid #eee;">${row.certName || '-'}</td>
    //       </tr>
    //       <tr>
    //         <td style="padding:8px 5px; border-bottom: 1px solid #eee; color: #666;">发证机构：</td>
    //         <td style="padding:8px 5px; border-bottom: 1px solid #eee;">${row.issueOrg || '-'}</td>
    //       </tr>
    //       <tr>
    //         <td style="padding:8px 5px; border-bottom: 1px solid #eee; color: #666;">到期日期：</td>
    //         <td style="padding:8px 5px; border-bottom: 1px solid #eee;">${row.expireDate ? this.parseTime(row.expireDate, '{y}-{m}-{d}') : '-'}</td>
    //       </tr>
    //       <tr>
    //         <td style="padding:8px 5px; border-bottom: 1px solid #eee; color: #666;">证书状态：</td>
    //         <td style="padding:8px 5px; border-bottom: 1px solid #eee;">${this.getCertStatusLabel(row.certStatus)}</td>
    //       </tr>
    //       <tr>
    //         <td style="padding:8px 5px; border-bottom: 1px solid #eee; color: #666;">审核状态：</td>
    //         <td style="padding:8px 5px; border-bottom: 1px solid #eee;">${this.getDictLabel('qualification_shenhe', row.auditStatus) || '-'}</td>
    //       </tr>`
    //
    //   // 如果有审核意见，添加审核意见
    //   if (row.auditOpinion) {
    //     detailContent += `
    //       <tr>
    //         <td style="padding:8px 5px; border-bottom: 1px solid #eee; color: #666;">审核意见：</td>
    //         <td style="padding:8px 5px; border-bottom: 1px solid #eee;">${row.auditOpinion}</td>
    //       </tr>`
    //   }
    //
    //   detailContent += `</table>`
    //
    //   this.$alert(detailContent, '资质详情', {
    //     dangerouslyUseHTMLString: true,
    //     confirmButtonText: '关闭',
    //     width: '550px',
    //     customClass: 'qualification-detail-dialog'
    //   })
    // },

    // 资质证书详情
    handleView(row) {
      this.openDetail = true
      this.detailData = row
      this.title = "资质证书详情"
      this.certificateList = []
      this.detailLoading = true
      listQualificationCertificates(row.qualificationId).then(response => {
        this.detailLoading = false
        if (response.code === 200) {
          this.certificateList = response.rows || [];
        }
      })
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },

    // 关闭按钮
    closeDetail(){
      this.openDetail = false
      this.reset()
    },

    // closeimage
    closeimage(){
      this.previewDialogVisible = false
    },

    // 表单重置
    reset() {
      this.form = {
        qualificationId: null,
        userId: null,
        realName: null,
        idCard: null,
        qualificationType: null,
        certificateNo: null,
        certificateFiles: null,
        applyTime: null,
        auditTime: null,
        auditStatus: null,
        auditOpinion: null,
        auditorId: null,
        remark: null,
        certName: null,
        certType: null,
        issueOrg: null,
        issueDate: null,
        expireDate: null,
        certImage: null,
        certStatus: null,
        remindDays: 30,
        lastRemindTime: null,
        scopeIds: null,
        scopeNames: null
      }
      this.resetForm("form")
    },

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

    // 重置按钮操作
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.qualificationId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    // 新增按钮操作
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加兽医资质"
      this.form.auditStatus = null
    },

    // 修改按钮操作
    handleUpdate(row) {
      this.reset()
      let certId = row.certId || row.certificateId || row.id
      if (certId && typeof certId === 'object') {
        certId = certId.value || certId.id || certId.certificateId
      }
      certId = String(certId || '')

      if (!certId || certId === 'null' || certId === 'undefined' || certId === 'NaN') {
        this.$modal.msgError("证书ID无效：" + certId)
        return
      }

      getQualificationCertificate(certId).then(response => {
        if (response.code === 200 && response.data) {
          this.form = response.data
          this.open = true
          this.title = "修改兽医资质证书信息"
        } else {
          this.$modal.msgError(response.msg || "获取证书信息失败")
        }
      }).catch(error => {
        console.error('获取证书信息失败:', error)
        this.$modal.msgError("获取证书信息失败")
      })
    },

    /** 提交按钮 */
    // submitForm() {
    //   this.$refs["form"].validate(valid => {
    //     if (valid) {
    //       if (this.form.qualificationId != null) {
    //         updateQualification(this.form).then(response => {
    //           this.$modal.msgSuccess("修改成功")
    //           this.open = false
    //           this.getList()
    //         })
    //       } else {
    //         this.form.auditStatus = null
    //         addQualification(this.form).then(response => {
    //           this.$modal.msgSuccess("新增成功")
    //           this.open = false
    //           this.getList()
    //         })
    //       }
    //     }
    //   })
    // },

    // 删除按钮操作
    handleDelete(row) {
      const qualificationIds = row.qualificationId || this.ids
      this.$modal.confirm('是否确认删除兽医资质编号为"' + qualificationIds + '"的数据项？').then(function() {
        return delQualification(qualificationIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },

    // 导出按钮操作
    // handleExport() {
    //   this.download('vet/qualification/export', {
    //     ...this.queryParams
    //   }, `qualification_${new Date().getTime()}.xlsx`)
    // },

    // 根据字典值获取标签
    getDictLabel(dictType, value) {
      const dict = this.dict.type[dictType]
      if (dict && value) {
        const item = dict.find(item => item.value === value)
        return item ? item.label : value
      }
      return value || '-'
    }
  }
}
</script>

<style scoped>
/* 操作按钮样式 */
.el-button--text {
  padding: 6px 10px;
  margin: 0 2px;
  min-width: 50px;
}

/* 状态标签样式 */
.el-tag {
  margin: 2px;
}

::v-deep .pagestyle .el-input{
  width: auto !important;
}
::v-deep .pageway .el-input{
  width: auto !important;
}
::v-deep .pageway .pagination-container{
  background-color: #f8fafc;
}
/* 详情对话框样式 */
::v-deep .qualification-detail-dialog .el-message-box__content {
  max-height: 400px;
  overflow-y: auto;
}

::v-deep .qualification-detail-dialog table {
  width: 100%;
}

::v-deep .qualification-detail-dialog table tr:last-child td {
  border-bottom: none;
}
</style>

<style scoped lang="scss">
// 操作按钮
.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);
}

.alter-btn:hover{
  background-color: rgb(230, 255, 238);
  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, #42b983 0%, #83df92 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;
}
</style>
