<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="年份" prop="year">
        <el-input
          v-model="queryParams.year"
          placeholder="请输入年份"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="学校编码" prop="collegeCode">
        <el-input
          v-model="queryParams.collegeCode"
          placeholder="请输入学校编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="学校名称" prop="collegeName">
        <el-input
          v-model="queryParams.collegeName"
          placeholder="请输入学校名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="编辑" prop="editor">-->
<!--        <el-input-->
<!--          v-model="queryParams.editor"-->
<!--          placeholder="请输入编辑"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="summary" prop="summary">-->
<!--        <el-input-->
<!--          v-model="queryParams.summary"-->
<!--          placeholder="请输入summary"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="标题" prop="title">-->
<!--        <el-input-->
<!--          v-model="queryParams.title"-->
<!--          placeholder="请输入标题"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="isArt" prop="isArt">-->
<!--        <el-input-->
<!--          v-model="queryParams.isArt"-->
<!--          placeholder="请输入isArt"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="元数据描述" prop="metaDescription">-->
<!--        <el-input-->
<!--          v-model="queryParams.metaDescription"-->
<!--          placeholder="请输入元数据描述"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="tags" prop="tags">-->
<!--        <el-input-->
<!--          v-model="queryParams.tags"-->
<!--          placeholder="请输入tags"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="是否显示" prop="isShow">
        <el-select v-model="queryParams.isShow" placeholder="请选择是否显示" clearable style="width: 160px">
          <el-option
            v-for="dict in bool_values"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
<!--      <el-form-item label="点击量" prop="hits">-->
<!--        <el-input-->
<!--          v-model="queryParams.hits"-->
<!--          placeholder="请输入点击量"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="元数据关键词" prop="metaKeywords">-->
<!--        <el-input-->
<!--          v-model="queryParams.metaKeywords"-->
<!--          placeholder="请输入元数据关键词"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="排名" prop="rank">-->
<!--        <el-input-->
<!--          v-model="queryParams.rank"-->
<!--          placeholder="请输入排名"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择类型" clearable style="width: 170px;">
          <el-option
            v-for="typeItem in brochureTypeList"
            :key="typeItem.type"
            :label="typeItem.typeName"
            :value="typeItem.type"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:bBusiWishUniversitiesEnrollBrochure:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:bBusiWishUniversitiesEnrollBrochure:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:bBusiWishUniversitiesEnrollBrochure:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:bBusiWishUniversitiesEnrollBrochure:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Upload"
          @click="handleImport"
          v-hasPermi="['system:bBusiWishUniversitiesEnrollBrochure:import']"
        >导入</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bBusiWishUniversitiesEnrollBrochureList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="年份" align="center" prop="year" />
      <el-table-column label="学校编码" align="center" prop="collegeCode" />
      <el-table-column label="学校名称" align="center" prop="collegeName" />
<!--      <el-table-column label="编辑" align="center" prop="editor" />-->
<!--      <el-table-column label="summary" align="center" prop="summary" />-->
      <el-table-column label="标题" align="center" prop="title" />
<!--      <el-table-column label="isArt" align="center" prop="isArt" />-->
      <el-table-column label="类型名称" align="center" prop="typeName" />
      <!--      <el-table-column label="元数据描述" align="center" prop="metaDescription" />-->
      <el-table-column label="内容" align="center">
        <template #default="{ row }">
          <el-link v-if="!row.url" type="primary" @click="showContentDetail(row.id)" :underline="false" style="cursor: pointer;">详情</el-link>
          <span v-else>{{ row.content }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="tags" align="center" prop="tags" />-->
      <el-table-column label="是否显示" align="center" prop="isShow">
        <template #default="scope">
          <dict-tag :options="bool_values" :value="scope.row.isShow"/>
        </template>
      </el-table-column>
<!--      <el-table-column label="点击量" align="center" prop="hits" />-->
      <el-table-column label="链接" align="center" prop="url" show-overflow-tooltip>
        <template #default="scope">
          <div v-if="scope.row.url" style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
            <el-link type="primary" @click="handlePreview(scope.row.url)" :underline="false" style="cursor: pointer;">
              {{ scope.row.url }}
            </el-link>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="元数据关键词" align="center" prop="metaKeywords" />-->
<!--      <el-table-column label="排名" align="center" prop="rank" />-->
      <el-table-column label="创建日期" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="创建日期" align="center" prop="updateTime" width="180">-->
<!--        <template #default="scope">-->
<!--          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="数据库创建日期" align="center" prop="createTime2" width="180">-->
<!--        <template #default="scope">-->
<!--          <span>{{ parseTime(scope.row.createTime2, '{y}-{m}-{d}') }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:bBusiWishUniversitiesEnrollBrochure:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:bBusiWishUniversitiesEnrollBrochure:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 添加或修改院校简章大纲对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="bBusiWishUniversitiesEnrollBrochureRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="年份" prop="year">
          <el-input v-model="form.year" placeholder="请输入年份" />
        </el-form-item>
        <el-form-item label="学校" prop="collegeCode">
          <el-select
            v-model="form.collegeCode"
            placeholder="请选择学校"
            filterable
            clearable
            @change="handleCollegeChange"
            style="width: 100%"
          >
            <el-option
              v-for="college in collegeList"
              :key="college.code"
              :label="college.name"
              :value="college.code"
            >
              <span style="float: left">{{ college.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ college.code }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学校编码" prop="collegeCode" v-if="false">
          <el-input v-model="form.collegeCode" placeholder="请输入学校编码" disabled/>
        </el-form-item>
        <el-form-item label="学校名称" prop="collegeName" v-if="false">
          <el-input v-model="form.collegeName" placeholder="请输入学校名称" />
        </el-form-item>
<!--        <el-form-item label="编辑" prop="editor">-->
<!--          <el-input v-model="form.editor" placeholder="请输入编辑" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="summary" prop="summary">-->
<!--          <el-input v-model="form.summary" placeholder="请输入summary" />-->
<!--        </el-form-item>-->
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="类型" prop="typeName">
          <el-select
                  v-model="form.typeName"
                  placeholder="请选择类型"
                  filterable
                  clearable
                  @change="handleTypeNameChange"
                  style="width: 100%"
          >
            <el-option
                    v-for="typeItem in brochureTypeList"
                    :key="typeItem.type"
                    :label="typeItem.typeName"
                    :value="typeItem.typeName"
            >
              <span style="float: left">{{ typeItem.typeName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ typeItem.type }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否显示" prop="isShow">
          <el-select v-model="form.isShow" placeholder="请选择是否显示">
            <el-option
                    v-for="dict in bool_values"
                    :key="dict.value"
                    :label="dict.label"
                    :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
<!--        <el-form-item label="isArt" prop="isArt">-->
<!--          <el-input v-model="form.isArt" placeholder="请输入isArt" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="元数据描述" prop="metaDescription">-->
<!--          <el-input v-model="form.metaDescription" placeholder="请输入元数据描述" />-->
<!--        </el-form-item>-->
        <el-form-item label="内容">
          <div style="width: 100%;">
            <div style="margin-bottom: 10px;">
              <el-radio-group v-model="editorMode" size="small">
                <el-radio-button label="rich">富文本编辑</el-radio-button>
                <el-radio-button label="source">源代码编辑</el-radio-button>
              </el-radio-group>
              <span style="margin-left: 10px; color: #909399; font-size: 12px;">
                {{ editorMode === 'source' ? '源代码模式可保持原始HTML格式' : '富文本模式可能改变HTML格式' }}
              </span>
            </div>
            <editor v-if="editorMode === 'rich'" v-model="form.content" :min-height="192"/>
            <el-input 
              v-else 
              v-model="form.content" 
              type="textarea" 
              :autosize="{ minRows: 10, maxRows: 30 }" 
              placeholder="请输入HTML内容"
              style="font-family: monospace;"
            />
          </div>
        </el-form-item>
<!--        <el-form-item label="tags" prop="tags">-->
<!--          <el-input v-model="form.tags" placeholder="请输入tags" />-->
<!--        </el-form-item>-->

<!--        <el-form-item label="点击量" prop="hits">-->
<!--          <el-input v-model="form.hits" placeholder="请输入点击量" />-->
<!--        </el-form-item>-->
        <el-form-item label="链接" prop="url">
          <el-input v-model="form.url" type="textarea" :autosize="{ minRows: 2, maxRows: 6 }" placeholder="请输入内容" />
        </el-form-item>
<!--&lt;!&ndash;        <el-form-item label="元数据关键词" prop="metaKeywords">&ndash;&gt;-->
<!--&lt;!&ndash;          <el-input v-model="form.metaKeywords" placeholder="请输入元数据关键词" />&ndash;&gt;-->
<!--&lt;!&ndash;        </el-form-item>&ndash;&gt;-->
<!--        <el-form-item label="排名" prop="rank">-->
<!--          <el-input v-model="form.rank" placeholder="请输入排名" />-->
<!--        </el-form-item>-->


<!--        <el-form-item label="数据库创建日期" prop="createTime2">-->
<!--          <el-date-picker clearable-->
<!--            v-model="form.createTime2"-->
<!--            type="date"-->
<!--            value-format="YYYY-MM-DD"-->
<!--            placeholder="请选择数据库创建日期">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :on-change="handleFileChange" :on-remove="handleFileRemove" :auto-upload="false" drag>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="BBusiWishUniversitiesEnrollBrochure">
import { listBBusiWishUniversitiesEnrollBrochure, getBBusiWishUniversitiesEnrollBrochure, delBBusiWishUniversitiesEnrollBrochure, addBBusiWishUniversitiesEnrollBrochure, updateBBusiWishUniversitiesEnrollBrochure, getBrochureTypes } from "@/api/system/bBusiWishUniversitiesEnrollBrochure"
import { listAllBBusiWishUniversities } from "@/api/system/bBusiWishUniversities"
import { ElMessageBox } from "element-plus/es"
import { UploadFilled } from "@element-plus/icons-vue"
import { getToken } from "@/utils/auth"


const { proxy } = getCurrentInstance()
const { bool_values } = proxy.useDict('bool_values')

const bBusiWishUniversitiesEnrollBrochureList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const collegeList = ref([])
const brochureTypeList = ref([])
const editorMode = ref("source") // 默认使用源代码模式，保持原始格式

/** 导入参数 */
const upload = reactive({
  // 是否显示弹出层（导入）
  open: false,
  // 弹出层标题（导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/system/bBusiWishUniversitiesEnrollBrochure/importUniversityBrochure",
  // 选中的文件
  selectedFile: null
})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    year: null,
    collegeCode: null,
    collegeName: null,
    editor: null,
    summary: null,
    title: null,
    isArt: null,
    type: null,
    metaDescription: null,
    content: null,
    tags: null,
    isShow: null,
    hits: null,
    url: null,
    metaKeywords: null,
    rank: null,
    typeName: null,
    createTime: null,
    updateTime: null,
    createTime2: null
  },
  rules: {
    collegeCode: [
      { required: true, message: "学校编码不能为空", trigger: "blur" }
    ],
    collegeName: [
      { required: true, message: "学校名称不能为空", trigger: "blur" }
    ],
    editor: [
      { required: true, message: "编辑不能为空", trigger: "blur" }
    ],
    summary: [
      { required: true, message: "summary不能为空", trigger: "blur" }
    ],
    title: [
      { required: true, message: "标题不能为空", trigger: "blur" }
    ],
    type: [
      { required: true, message: "类型不能为空", trigger: "change" }
    ],
    typeName: [
      { required: true, message: "类型名称不能为空", trigger: "change" }
    ],
    isShow: [
      { required: true, message: "是否显示不能为空", trigger: "change" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询院校简章大纲列表 */
function getList() {
  loading.value = true
  listBBusiWishUniversitiesEnrollBrochure(queryParams.value).then(response => {
    bBusiWishUniversitiesEnrollBrochureList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 加载学校列表 */
function loadCollegeList() {
  listAllBBusiWishUniversities({}).then(response => {
    // 假设接口返回的数据格式为 { code, name } 或 { collegeCode, collegeName }
    // 根据实际接口返回格式调整
    if (response.data && Array.isArray(response.data)) {
      collegeList.value = response.data.map(item => ({
        code: item.code || item.collegeCode,
        name: item.name || item.collegeName
      }))
    } else if (response.rows && Array.isArray(response.rows)) {
      collegeList.value = response.rows.map(item => ({
        code: item.code || item.collegeCode,
        name: item.name || item.collegeName
      }))
    }
  }).catch(error => {
    console.error('加载学校列表失败:', error)
  })
}

/** 学校选择变化 */
function handleCollegeChange(collegeCode) {
  if (collegeCode) {
    const selectedCollege = collegeList.value.find(item => item.code === collegeCode)
    if (selectedCollege) {
      form.value.collegeCode = selectedCollege.code
      form.value.collegeName = selectedCollege.name
    }
  } else {
    form.value.collegeCode = null
    form.value.collegeName = null
  }
}

/** 加载简章类型列表 */
function loadBrochureTypeList() {
  getBrochureTypes().then(response => {
    // 处理接口返回的数据
    if (response.data && Array.isArray(response.data)) {
      brochureTypeList.value = response.data
    } else if (Array.isArray(response)) {
      brochureTypeList.value = response
    }
  }).catch(error => {
    console.error('加载简章类型列表失败:', error)
  })
}

/** 类型选择变化 */
function handleTypeChange(type) {
  if (type) {
    const selectedType = brochureTypeList.value.find(item => item.type === type)
    if (selectedType) {
      form.value.type = selectedType.type
      form.value.typeName = selectedType.typeName
    }
  } else {
    form.value.type = null
    form.value.typeName = null
  }
}

/** 类型名称选择变化 */
function handleTypeNameChange(typeName) {
  if (typeName) {
    const selectedType = brochureTypeList.value.find(item => item.typeName === typeName)
    if (selectedType) {
      form.value.type = selectedType.type
      form.value.typeName = selectedType.typeName
    }
  } else {
    form.value.type = null
    form.value.typeName = null
  }
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    year: null,
    collegeCode: null,
    collegeName: null,
    editor: null,
    summary: null,
    title: null,
    isArt: null,
    type: null,
    metaDescription: null,
    content: null,
    tags: null,
    isShow: null,
    hits: null,
    url: null,
    metaKeywords: null,
    rank: null,
    typeName: null,
    createTime: null,
    updateTime: null,
    createTime2: null
  }
  proxy.resetForm("bBusiWishUniversitiesEnrollBrochureRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

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

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加院校简章大纲"
  // 如果学校列表为空，则加载
  if (collegeList.value.length === 0) {
    loadCollegeList()
  }
  // 如果类型列表为空，则加载
  if (brochureTypeList.value.length === 0) {
    loadBrochureTypeList()
  }
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getBBusiWishUniversitiesEnrollBrochure(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改院校简章大纲"
    // 如果学校列表为空，则加载
    if (collegeList.value.length === 0) {
      loadCollegeList()
    }
    // 如果类型列表为空，则加载
    if (brochureTypeList.value.length === 0) {
      loadBrochureTypeList()
    }
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["bBusiWishUniversitiesEnrollBrochureRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateBBusiWishUniversitiesEnrollBrochure(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addBBusiWishUniversitiesEnrollBrochure(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除院校简章大纲编号为"' + _ids + '"的数据项？').then(function() {
    return delBBusiWishUniversitiesEnrollBrochure(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导入按钮操作 */
function handleImport() {
  upload.title = "院校简章导入"
  upload.open = true
  upload.selectedFile = null
}

/** 下载模板操作 */
function importTemplate() {
  proxy.download("system/bBusiWishUniversitiesEnrollBrochure/importTemplate", {
  }, `university_brochure_template_${new Date().getTime()}.xlsx`)
}

/** 文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true
}

/** 文件选择处理 */
const handleFileChange = (file, fileList) => {
  upload.selectedFile = file
}

/** 文件删除处理 */
const handleFileRemove = (file, fileList) => {
  upload.selectedFile = null
}

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false
  upload.isUploading = false
  proxy.$refs["uploadRef"].handleRemove(file)
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true })
  getList()
}

/** 提交上传文件 */
function submitFileForm() {
  const file = upload.selectedFile
  if (!file || file.length === 0 || (!file.name.toLowerCase().endsWith('.xls') && !file.name.toLowerCase().endsWith('.xlsx'))) {
    proxy.$modal.msgError('请选择后缀为 "xls"或"xlsx" 的文件。')
    return
  }
  proxy.$refs["uploadRef"].submit()
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/bBusiWishUniversitiesEnrollBrochure/export', {
    ...queryParams.value
  }, `bBusiWishUniversitiesEnrollBrochure_${new Date().getTime()}.xlsx`)
}

/** 预览文件 */
function handlePreview(url) {
  if (!url) return

  // 判断是否为Word文件
  const isWord = /\.(doc|docx)$/i.test(url)

  if (isWord) {
    // Word文件使用微软在线预览服务
    const previewUrl = `https://view.officeapps.live.com/op/view.aspx?src=${encodeURIComponent(url)}`
    window.open(previewUrl, '_blank')
  } else {
    // PDF或其他文件直接打开
    window.open(url, '_blank')
  }
}

/** 显示内容详情 */
function showContentDetail(id) {
  getBBusiWishUniversitiesEnrollBrochure(id).then(response => {
    const content = response.data?.content || ''
    const title = response.data?.title || '内容详情'
    // 创建弹窗显示内容
    proxy.$alert(content, title, {
      dangerouslyUseHTMLString: true,
      confirmButtonText: '确定',
      customClass: 'content-detail-alert',
      callback: action => {}
    })
  }).catch(error => {
    console.error('获取内容失败:', error)
    proxy.$modal.msgError('获取内容失败')
  })
}

// 组件挂载时加载学校列表和类型列表
loadCollegeList()
loadBrochureTypeList()
getList()
</script>
<style>
.content-detail-alert {
  min-width: 400px;
  width: auto;
  max-width: 90vw;
  max-height: 80vh;
  overflow-y: auto;
}

.content-detail-alert .el-message-box__message {
  max-height: 60vh;
  overflow-y: auto;
  text-align: left;
  padding-right: 10px;
  word-wrap: break-word;
  white-space: normal;
}
</style>
