<!--
 * @Author: Devin
 * @Date: 2021-07-29 11:57:53
 * @LastEditTime: 2021-07-30 17:05:49
 * @LastEditors: Devin
 * @Description:
 * email: das.devin@outlook.com
-->
<template>
  <div class="apaas-custom-page-mydemo custom-page">
    <template v-if="!showModelDetail">
      <div class="page-header">
        <div class="operation"> </div>
      </div>
      <div class="page-search-panel">
        <div class="search-fields">
          <div class="search-field">
            <span class="field-label">模板名称</span>
            <el-select
              v-model="searchPanelValue.templateName"
              :loading="templateSelectLoading"
              placeholder="请选择模板名称"
              clearable
              filterable
              style="width: 220px"
              @change="handleSearch"
            >
              <el-option
                v-for="item in templateOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
          <div class="search-actions">
            <el-button type="primary" @click="handleDownloadImportTemplate">
              下载导入模板
            </el-button>
            <el-button class="import-btn" @click="handleImportTemplate()">
              导入参数模板
            </el-button>
            <el-button type="primary" @click="handleAddTemplate()">
              添加参数模板
            </el-button>
          </div>
        </div>
      </div>
      <div class="page-data-list">
        <x-vxe-table
          ref="vxeTable"
          :border="true"
          :colConfigs="tableConfig.colConfigs"
          :tableData="tableData"
          :rowDraggable="tableConfig.rowDraggable"
          :seqType="tableConfig.seqType"
          :pagination="pagination"
          :layout="tableConfig.layout"
          :autoSize="tableConfig.autoSize"
          :pageConfig="tableConfig.pageConfig"
          class="block-table"
          @table-row-click="rowClickEvent"
          @size-change="pageSizeChange"
          @current-page-change="currentChange"
          @select-data-change="selectDataChange"
        >
          <template
            v-for="(colConfig, index) in tableConfig.colConfigs"
            v-slot:[colConfig.customHeadSlot]="{ column }"
          >
            <div v-if="colConfig.customHeadSlot" :key="index"> {{ column }} {{ colConfig }} </div>
          </template>
          <template
            v-for="(colConfig, index) in tableConfig.colConfigs"
            v-slot:[colConfig.customSlot]="{ row, rowIndex }"
          >
            <div
              v-if="colConfig.customSlot === 'options'"
              :key="index + '' + rowIndex"
              class="operation-links"
            >
              <a
                href="javascript:void(0)"
                class="el-link el-link--primary"
                @click.stop="handleRowDetail(row)"
              >
                查看
              </a>
              <span class="link-separator"></span>
              <a
                href="javascript:void(0)"
                class="el-link el-link--primary"
                @click.stop="handleRowDownload(row)"
              >
                下载
              </a>
              <span class="link-separator"></span>
              <a
                href="javascript:void(0)"
                class="el-link el-link--primary"
                @click.stop="handleRowVersion(row)"
              >
                版本
              </a>
              <span class="link-separator"></span>
              <a
                v-if="row.status === 'DRAFT'"
                href="javascript:void(0)"
                class="el-link el-link--primary"
                @click.stop="handleRowEdit(row)"
              >
                修改
              </a>
            </div>
            <div v-if="colConfig.customSlot === 'version'" :key="index + '' + rowIndex">
              V{{ row[colConfig.prop] || '' }}
            </div>
            <div v-if="colConfig.customSlot === 'status'" :key="index + '' + rowIndex">
              <span
                v-if="
                  getStatusType(row[colConfig.prop]) == '已完成' ||
                    row[colConfig.prop] === 'COMPLETE'
                "
                class="status-tag status-published"
              >
                已发布
              </span>
              <span
                v-else-if="
                  getStatusType(row[colConfig.prop]) == '审核中' ||
                    row[colConfig.prop] === 'APPROVING'
                "
                class="status-tag status-reviewing"
              >
                审核中
              </span>
              <span
                v-else-if="
                  getStatusType(row[colConfig.prop]) == '历史' || row[colConfig.prop] === 'HISTORY)'
                "
                class="status-tag status-history"
              >
                历史
              </span>
              <span
                v-else-if="
                  getStatusType(row[colConfig.prop]) == '草稿' || row[colConfig.prop] === 'DRAFT'
                "
                class="status-tag status-draft"
              >
                草稿
              </span>
            </div>
          </template>
          <template slot="empty">
            <div class="table-empty">
              <x-empty-page></x-empty-page>
            </div>
          </template>
        </x-vxe-table>
      </div>
    </template>

    <detail-drawer ref="detailDrawer"></detail-drawer>
    <edit-modal ref="editModal" @submit="handleTemplateSubmit"></edit-modal>
    <version-modal ref="versionModal" @version-click="handleVersionClick"></version-modal>

    <!-- 模板详情组件 -->
    <model-detail
      v-if="showModelDetail"
      :template-id="currentTemplateId"
      :change-id="currentTemplateRowId"
      :template-name="currentTemplateName"
      :template-version="currentVersion"
      :version-list="versionList"
      :detail="currentDetail"
      :template-management-permissions="templateManagementPermissions"
      class="model-detail-wrapper"
      @back="handleBackFromDetail"
    />

    <el-dialog
      title="导入模板"
      :visible.sync="importDialogVisible"
      width="400px"
      append-to-body
      @close="handleImportDialogClose"
    >
      <el-upload
        class="import-uploader"
        drag
        :auto-upload="false"
        :limit="1"
        accept=".xls,.xlsx,.csv"
        :file-list="importFileList"
        :on-change="handleImportFileChange"
        :on-remove="handleImportFileRemove"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text"> 将文件拖到此处，或<em>点击上传</em> </div>
        <div slot="tip" class="el-upload__tip">
          仅支持Excel或CSV模板文件
        </div>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleImportDialogClose">取消</el-button>
        <el-button type="primary" :loading="importing" @click="handleImportConfirm">
          开始导入
        </el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="错误信息"
      :visible.sync="errorDialogVisible"
      width="400px"
      append-to-body
      @close="handleErrorDialogClose"
    >
      <div class="error-list"> {{ errorList }} </div>
    </el-dialog>
  </div>
</template>

<script>
import api from '@/api'
import { getUserId } from '@/utils'
import DetailDrawer from './detail-drawer.vue'
import EditModal from './edit-modal.vue'
import VersionModal from './version-modal.vue'
import ModelDetail from './modelDetail.vue'

const createDefaultSearch = () => ({
  templateName: ''
})

export default {
  name: 'ApaasCustomMydemo',
  components: {
    DetailDrawer,
    EditModal,
    VersionModal,
    ModelDetail
  },
  data: function() {
    return {
      searchPanelValue: createDefaultSearch(),
      templateOptions: [],
      templateSelectLoading: false,
      tableData: [],
      errorList: '',
      pagination: { currentPage: 1, pageSize: 10, total: 0 },
      showModelDetail: false,
      currentTemplateId: '',
      currentTemplateRowId: '',
      currentTemplateName: '',
      currentVersion: '', // 当前选中的版本
      versionList: [], // 版本列表
      currentDetail: {}, // 当前模板的详情（包含 status）
      importing: false,
      importDialogVisible: false,
      importFileList: [],
      selectedImportFile: null,
      downloadingRowId: '',
      tenantId: '1764149921900',
      userId: getUserId(),
      errorDialogVisible: false,
      templateManagementPermissions: [] // 暂存 menuPath 为 "数据录入/模板管理" 的权限数组
    }
  },
  computed: {
    tableConfig() {
      return {
        rowDraggable: false,
        colConfigs: [
          {
            prop: 'templateName',
            showOverflowTooltip: true,
            label: '模板名称',
            align: 'center'
          },
          {
            prop: 'version',
            label: '版本',
            customSlot: 'version',
            showOverflowTooltip: true,
            minWidth: '150',
            align: 'center'
          },
          {
            prop: 'orderNum',
            label: '排序号',
            showOverflowTooltip: true,
            minWidth: '80',
            align: 'center'
          },
          {
            prop: 'status',
            customSlot: 'status',
            label: '状态',
            showOverflowTooltip: true,
            minWidth: '150',
            align: 'center'
          },
          {
            prop: 'createdTime',
            label: '创建时间',
            showOverflowTooltip: true,
            width: '200',
            align: 'center'
          },
          { prop: 'publishedTime', label: '发布时间', width: '220', align: 'center' },
          { prop: 'createBy', label: '创建人', width: '120', align: 'center' },
          {
            prop: 'options',
            label: '操作',
            customSlot: 'options',
            align: 'center',
            width: '180',
            fixed: 'right'
          }
        ],
        seqType: false,
        layout: 'total, prev, pager, next, sizes, jumper'
      }
    }
  },
  mounted() {
    this.loadUserSelfRole()
    this.loadTemplateOptions()
    this.loadData()
  },
  methods: {
    // 加载用户自身角色权限
    loadUserSelfRole() {
      localStorage.setItem('user_self_role', [])
      const request = {
        ...api.GET_USER_SELF_ROLE,
        params: {
          userOrDepID: getUserId()
        },
        disableSuccessMsg: true
      }
      this.$request(request)
        .asyncThen((resp) => {
          if (resp && resp.data) {
            // 将权限数据存储到 localStorage
            try {
              localStorage.setItem('user_self_role', JSON.stringify(resp.data))
            } catch (err) {
              console.error('存储权限数据到 localStorage 失败:', err)
            }

            // 遍历 user_self_role 数组，查找 menuPath 为 "数据录入/模板管理" 的内容
            this.filterTemplateManagementPermissions()
          }
        })
        .asyncErrorCatch((err) => {
          console.error('获取用户自身角色失败:', err)
        })
    },
    // 过滤模板管理相关的权限
    filterTemplateManagementPermissions() {
      try {
        const permissionDataStr = localStorage.getItem('user_self_role')
        if (!permissionDataStr) {
          this.templateManagementPermissions = []
          return
        }

        const permissionData = JSON.parse(permissionDataStr)
        if (!Array.isArray(permissionData)) {
          this.templateManagementPermissions = []
          return
        }

        // 查找 menuPath 为 "数据录入/模板管理" 的所有权限项
        this.templateManagementPermissions = permissionData.filter((perm) => {
          return perm.menuPath === '数据录入/模板管理'
        })

        console.log('模板管理权限数据:', this.templateManagementPermissions)
      } catch (err) {
        console.error('过滤模板管理权限失败:', err)
        this.templateManagementPermissions = []
      }
    },
    // 检查权限
    // menuPath: 模块路径，如 "数据录入/模板管理"
    // subsystem: 子系统名称（可选，如果提供则检查该子系统的权限）
    // permissionType: 权限类型，"查看" 或 "编辑"
    checkPermission(menuPath, subsystem = null, permissionType = '查看') {
      try {
        const permissionDataStr = localStorage.getItem('user_self_role')
        if (!permissionDataStr) {
          return false
        }
        const permissionData = JSON.parse(permissionDataStr)
        if (!Array.isArray(permissionData)) {
          return false
        }

        // 查找匹配的权限
        const matchedPermissions = permissionData.filter((perm) => {
          // 检查 menuPath 是否匹配（支持包含关系）
          const menuMatch =
            perm.menuPath &&
            menuPath &&
            (perm.menuPath.includes(menuPath) || menuPath.includes(perm.menuPath))
          if (!menuMatch) {
            return false
          }

          // 如果提供了 subsystem，检查是否匹配
          if (subsystem) {
            if (perm.subsystem !== subsystem) {
              return false
            }
          }

          // 检查权限类型是否匹配
          return perm.parameterPer === permissionType
        })

        return matchedPermissions.length > 0
      } catch (err) {
        console.error('检查权限失败:', err)
        return false
      }
    },
    // 检查是否有查看权限（用于模板管理页面，根据templateName匹配subsystem）
    hasViewPermission(templateName = null) {
      if (templateName) {
        // 如果提供了templateName，检查该子系统是否有查看权限
        return this.checkPermission('模板管理', templateName, '查看')
      }
      // 如果没有提供templateName，检查是否有任意子系统的查看权限
      return this.checkPermission('模板管理', null, '查看')
    },
    // 检查是否有编辑权限（用于模板管理页面，根据templateName匹配subsystem）
    hasEditPermission(templateName = null) {
      if (templateName) {
        // 如果提供了templateName，检查该子系统是否有编辑权限
        return this.checkPermission('模板管理', templateName, '编辑')
      }
      // 如果没有提供templateName，检查是否有任意子系统的编辑权限
      return this.checkPermission('模板管理', null, '编辑')
    },
    getStatusType(status) {
      // 如果status是数字类型，直接返回
      if (typeof status === 'number') {
        return status
      }
      // 如果status是字符串类型，转换为数字
      if (typeof status === 'string') {
        if (status === '已发布' || status === 'COMPLETE') return '已完成'
        if (status === '审核中' || status === 'REVIEWING') return '审核中'
        if (status === '校对中' || status === 'PROOFREADING') return '校对中'
        if (status === '已批准' || status === 'APPROVING') return '已批准'
        if (status === '草稿' || status === 'DRAFT') return '草稿'
      }
      // 如果status是布尔值，true为已发布(1)，false为草稿(0)
      if (status === true) {
        return '已发布'
      }
      // 默认为草稿(0)
      return '草稿'
    },
    pageSizeChange(size) {
      this.pagination.pageSize = size
      this.loadData()
    },
    rowClickEvent(row) {
      console.warn(row)
    },
    handleRowDetail(row) {
      this.currentTemplateId = row.rowId
      this.currentTemplateRowId = row.id
      this.currentTemplateName = row.templateName
      // 默认使用最新版本（po_code）
      this.currentVersion = row.version
      // 保存当前模板的详情（包含 status）
      this.currentDetail = {
        status: row.status || ''
      }
      // 获取版本列表
      this.loadVersionList(row)
      // 确保权限数据已加载
      if (this.templateManagementPermissions.length === 0) {
        this.loadUserSelfRole()
      }
      this.showModelDetail = true
    },
    loadVersionList(row) {
      const templateRowId = row && (row.rowId || row.templateRowId || row.id)
      if (!templateRowId) {
        this.versionList = []
        return
      }
      const request = {
        ...api.CHECK_MODEL_VERISON,
        params: {
          templateRowId
        },
        disableSuccessMsg: true
      }
      this.$request(request, false)
        .asyncThen((resp) => {
          const list =
            (resp && resp.data && (resp.data.result || resp.data.list || resp.data)) || []
          this.versionList = Array.isArray(list) ? list : []
        })
        .asyncErrorCatch((err) => {
          console.error('获取版本列表失败:', err)
          this.versionList = []
        })
    },
    handleBackFromDetail() {
      console.log('handleBackFromDetail called')
      this.showModelDetail = false
      this.currentTemplateId = ''
      this.currentTemplateName = ''
      this.currentVersion = ''
      this.versionList = []
      this.currentDetail = {}
      this.loadData()
    },
    demoGetPerson() {
      const request = {
        ...api.GET_ALLUSERS,
        disableSuccessMsg: true,
        params: {
          name: '李'
        }
      }
      this.$request(request)
        .asyncThen((resp) => {
          console.log(resp, 'resp')
        })
        .asyncErrorCatch((err) => {
          console.error('获取人员失败:', err)
        })
    },
    handleRowVersion(row) {
      this.$refs.versionModal.showModal(row)
    },
    handleDownloadImportTemplate() {
      const request = {
        ...api.DOWNLODE_ALL_MODEL,
        disableSuccessMsg: true
      }
      this.$request(request)
        .asyncThen((resp) => {
          console.log(resp, 'resp')
          const blobData = resp.data
          if (!blobData) {
            console.log('下载失败，文件内容为空')
            return
          }
          const downloadUrl = window.URL.createObjectURL(blobData)
          const link = document.createElement('a')
          link.href = downloadUrl
          link.download = '导入模板.xlsx'
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          window.URL.revokeObjectURL(downloadUrl)
        })
        .asyncErrorCatch((err) => {
          console.error('下载导入模板失败:', err)
        })
    },
    handleVersionClick(data) {
      console.log(data, 'data')
      // 处理版本弹窗中的版本点击事件，跳转到详情页面
      const { version, templateId, template, versionList, changeId } = data
      this.currentTemplateRowId = changeId
      // 设置模板ID和名称，跳转到详情页面
      this.currentTemplateId = templateId
      this.currentTemplateName = template.templateName || ''
      // 设置点击的版本信息
      this.currentVersion = version.name || version.version || ''
      // 更新当前模板的详情（包含 status）
      this.currentDetail = {
        status: version.status || template.status || ''
      }
      // 如果有传递版本列表，使用传递的版本列表；否则使用已有的版本列表
      if (versionList && versionList.length > 0) {
        this.versionList = versionList
      }
      this.showModelDetail = true
    },
    handleRowDownload(row) {
      const templateRowId = row.rowId
      if (!templateRowId) {
        console.log('未找到模板ID，无法下载')
        return
      }
      if (this.downloadingRowId === templateRowId) {
        return
      }
      const { url, method = 'get', headers = {} } = api.DOWNLODE_MODEL || {}
      const requestConfig = {
        url,
        method,
        params: {
          templateRowId,
          templateEmpty: false
        },
        responseType: 'blob',
        headers
      }
      if (!requestConfig.url) {
        console.log('未配置下载地址')
        return
      }
      if ((requestConfig.method || '').toLowerCase() === 'post') {
        requestConfig.data = requestConfig.params
        delete requestConfig.params
      }
      const defaultFilename = row.templateName
        ? `${row.templateName}${row.version ? ` ${row.version}` : ''}.xlsx`
        : '文件下载.xlsx'
      this.downloadingRowId = templateRowId
      this.$axios(requestConfig)
        .then((response) => {
          const blobData = response.data
          if (!blobData) {
            console.log('下载失败，文件内容为空')
            return
          }
          const contentType =
            response.headers &&
            (response.headers['content-type'] || response.headers['Content-Type'])
          if (contentType && contentType.includes('application/json')) {
            try {
              const reader = new FileReader()
              reader.onload = () => {
                console.log(`下载失败: ${reader.result}`)
              }
              reader.readAsText(blobData)
            } catch (err) {
              console.error('解析下载失败响应异常:', err)
            }
            return
          }
          const disposition =
            response.headers &&
            (response.headers['content-disposition'] || response.headers['Content-Disposition'])
          let filename = defaultFilename
          if (disposition) {
            const filenameMatch = /filename\*=UTF-8''([^;]+)|filename="?([^";]+)"?/i.exec(
              disposition
            )
            const matchedName = filenameMatch ? filenameMatch[1] || filenameMatch[2] : ''
            if (matchedName) {
              try {
                filename = decodeURIComponent(matchedName)
              } catch (err) {
                filename = matchedName
              }
            }
          }
          const downloadUrl = window.URL.createObjectURL(blobData)
          const link = document.createElement('a')
          link.href = downloadUrl
          link.download = filename
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          window.URL.revokeObjectURL(downloadUrl)
          this.$message({
            type: 'success',
            message: '下载成功'
          })
          console.log('下载开始，请查看浏览器下载列表')
        })
        .catch((err) => {
          console.error('下载失败:', err)
          console.log('下载失败，请稍后重试')
        })
        .finally(() => {
          this.downloadingRowId = ''
        })
    },
    handleRowEdit(row) {
      this.$refs.editModal.showModal(row)
    },
    currentChange(currentPage) {
      this.pagination.currentPage = currentPage
      this.loadData()
    },
    selectDataChange(data) {
      this.$emit('select-data-change', data)
    },

    handleAddTemplate() {
      this.$refs.editModal.showModal(null, 'add')
    },
    handleImportTemplate() {
      if (this.importing) {
        return
      }
      this.selectedImportFile = null
      this.importFileList = []
      this.importDialogVisible = true
    },
    handleImportFileChange(uploadFile, uploadFiles) {
      // 允许的文件类型
      const allowedTypes = ['.xls', '.xlsx', '.csv']
      const allowedMimeTypes = [
        'application/vnd.ms-excel',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'text/csv',
        'application/vnd.ms-excel.sheet.macroEnabled.12'
      ]

      if (uploadFile && uploadFile.raw) {
        const file = uploadFile.raw
        const fileName = file.name || ''
        const fileExtension = fileName.substring(fileName.lastIndexOf('.')).toLowerCase()
        const fileType = file.type || ''

        // 验证文件扩展名
        const isValidExtension = allowedTypes.some((type) => fileExtension === type)
        // 验证 MIME 类型
        const isValidMimeType =
          !fileType || allowedMimeTypes.some((type) => fileType.includes(type))

        if (!isValidExtension && !isValidMimeType) {
          this.$message.error(`文件类型不支持，仅支持 ${allowedTypes.join('、')} 格式的文件`)
          // 清空不符合要求的文件
          this.selectedImportFile = null
          this.importFileList = []
          return false
        }

        this.selectedImportFile = file
        this.importFileList = uploadFiles.slice(-1)
      } else {
        this.selectedImportFile = null
        this.importFileList = uploadFiles.slice(-1)
      }
    },
    handleImportFileRemove() {
      this.selectedImportFile = null
      this.importFileList = []
    },
    handleImportDialogClose() {
      if (this.importing) {
        return
      }
      this.importDialogVisible = false
      this.selectedImportFile = null
      this.importFileList = []
    },
    textDemo() {
      const request = {
        ...api.TEXT_DEMO,
        params: {
          pageNumber: 1,
          pageSize: 10
        }
      }
      this.$request(request)
        .asyncThen((resp) => {
          console.log(resp, 'resp')
        })
        .asyncErrorCatch((err) => {
          console.error('测试接口失败:', err)
        })
    },
    handleImportConfirm() {
      if (this.importing || !this.selectedImportFile) {
        if (!this.selectedImportFile) {
          this.$message.warning('请先选择要导入的文件')
        }
        return
      }
      const file = this.selectedImportFile
      // 再次验证文件类型（双重保险）
      const allowedTypes = ['.xls', '.xlsx', '.csv']
      const fileName = file.name || ''
      const fileExtension = fileName.substring(fileName.lastIndexOf('.')).toLowerCase()

      if (!allowedTypes.includes(fileExtension)) {
        this.$message.error(`文件类型不支持，仅支持 ${allowedTypes.join('、')} 格式的文件`)
        this.selectedImportFile = null
        this.importFileList = []
        return
      }
      const formData = new FormData()
      formData.append('file', file)
      formData.append('userId', getUserId())
      formData.append('createBy', getUserId())
      const request = {
        ...api.IMPORT_MODEL,
        params: formData,
        disableSuccessMsg: false
      }
      this.importing = true
      // 显示全屏 loading 提示
      const loadingInstance = this.$loading({
        lock: true,
        text: '正在导入模板，请稍候...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      this.$upload(request, null, false)
        .then((resp) => {
          console.log(resp, 'resp')
          loadingInstance.close()
          this.importing = false
          setTimeout(() => {
            this.loadData()
          }, 1000)
        })
        .catch((err) => {
          console.log(err, 'err')
          loadingInstance.close()
          this.importing = false
          this.errorList = ''
          if (err && err.data && err.data.errors && Array.isArray(err.data.errors)) {
            for (let error of err.data.errors) {
              this.errorList += error + '\n'
            }
          } else {
            this.errorList = err.message || '导入失败，请稍后重试'
          }
          this.errorDialogVisible = true
        })
        .finally(() => {
          // 确保 loading 在所有情况下都能关闭
          if (loadingInstance) {
            loadingInstance.close()
          }
          this.importing = false
        })
      this.importDialogVisible = false
    },
    handleTemplateSubmit(data) {
      const { mode, formData, row } = data
      console.log(formData, 'formData')
      if (mode === 'add') {
        // 添加新模板到表格
        const request = {
          ...api.ADD_MODEL,
          params: formData
        }
        this.$request(request)
          .asyncThen((resp) => {
            this.loadData()
            this.$message({
              type: 'success',
              message: '添加成功'
            })
          })
          .asyncErrorCatch((err) => {
            console.error('添加失败:', err)
          })
      } else {
        const request = {
          ...api.EDIT_MODEL,
          params: { ...formData, templateRowId: row.rowId }
        }
        this.$request(request)
          .asyncThen((resp) => {
            this.loadData()
            this.$message({
              type: 'success',
              message: '修改成功'
            })
          })
          .asyncErrorCatch((err) => {
            console.error('修改失败:', err)
          })
      }
    },
    resetSearch() {
      Object.assign(this.searchPanelValue, createDefaultSearch())

      this.handleSearch()
    },
    handleSearch() {
      // 每次搜索时，重置页码为1
      this.pagination.currentPage = 1
      this.loadData()
    },
    handleRefresh() {
      this.pagination.currentPage = 1
      // this.pagination.pageSize = 10
      this.handleSearch()
    },
    loadData() {
      const request = {
        ...api.GET_MODEL_LIST,
        params: {
          pageNumber: this.pagination.currentPage,
          pageSize: this.pagination.pageSize,
          templateName: this.searchPanelValue.templateName
        },
        disableSuccessMsg: true
      }
      this.$request(request, false)
        .asyncThen((resp) => {
          this.tableData = resp.data.result
          console.log(resp.data.count, 'resp.data.count')
          this.pagination.total = resp.data.count
        })
        .asyncErrorCatch((err) => {
          console.error('查询失败:', err)
        })
    },
    // 加载模板名称下拉框数据
    loadTemplateOptions() {
      this.templateSelectLoading = true
      const request = {
        ...api.GET_MODEL_LIST,
        params: {
          pageNumber: 1,
          pageSize: 999
        },
        disableSuccessMsg: true
      }
      this.$request(request, false)
        .asyncThen((resp) => {
          const list = resp.data.result || []
          const seen = new Set()
          const options = list
            .map((item) => item.templateName || item.po_name || '')
            .filter((name) => {
              if (!name || seen.has(name)) {
                return false
              }
              seen.add(name)
              return true
            })
            .map((name) => ({
              label: name,
              value: name
            }))
          this.templateOptions = options
          this.templateSelectLoading = false
        })
        .asyncErrorCatch((err) => {
          console.error('加载模板列表失败:', err)
          this.templateOptions = []
          this.templateSelectLoading = false
        })
    },
    // 生成UUID
    generateUUID() {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        const r = (Math.random() * 16) | 0
        const v = c === 'x' ? r : (r & 0x3) | 0x8
        return v.toString(16)
      })
    }
  }
}
</script>

<style lang="scss">
.import-uploader {
  width: 100%;
  .el-upload {
    width: 100%;
  }
  .el-upload-dragger {
    width: 100%;
  }
}
.import-btn {
  color: #027aff;
  border-color: #027aff;
  background-color: #fff;
}
.custom-page {
  width: 100%;
  height: 100%;
  overflow-y: auto;
  display: flex;
  flex-direction: column;

  .page-header {
    display: flex;
    width: calc(100% - 40px) !important;
    align-items: center;
    justify-content: space-between;
    height: 56px;
    padding: 0 20px;
    padding-right: 30px;
    background: #fff;
    border-bottom: 1px solid #ebeef5;
    flex-shrink: 0;

    .title {
      color: #303133;
      font-weight: 500;
      font-size: 18px !important;
      margin: 0;
    }

    .operation {
      display: flex;
      gap: 8px;
      align-items: center;
    }
  }

  .page-search-panel {
    background: white;
    padding: 16px 24px;
    border-bottom: 1px solid #ebeef5;
    flex-shrink: 0;
    display: flex;
    flex-direction: column;
    gap: 16px;

    .search-fields {
      display: flex;
      flex-wrap: wrap;
      gap: 16px 32px;
      width: 100%;
    }

    .search-field {
      display: flex;
      align-items: center;
      gap: 12px;
      flex: 1 1 calc((100% - 64px) / 3);
      min-width: 260px;

      .field-label {
        font-size: 16px;
        font-weight: 600;
        color: #303133;
        white-space: nowrap;
        min-width: 80px;
        text-align: right !important;
        text-align-last: right !important;
      }

      .el-input,
      .el-select {
        width: 220px;
      }

      ::v-deep .el-input__inner,
      ::v-deep .el-select .el-input__inner {
        height: 32px;
        line-height: 32px;
      }
    }

    .search-actions {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      gap: 12px;
      flex: 1 1 calc((100% - 64px) / 3);
      min-width: 260px;

      ::v-deep .el-button {
        padding: 0 16px;
        font-size: 14px;
        border-radius: 4px;
        height: 32px;
        line-height: 32px;
      }
    }
  }

  .page-data-list {
    display: flex;
    flex: 1;
    min-height: 0;
    flex-direction: column;
    padding: 0 20px 20px 20px;
    background: #f7f7f7;

    .x-empty-page {
      top: 0;
    }
  }

  .status-tag {
    display: inline-block;
    padding: 2px;
    color: white;
    height: 18px;
    line-height: 18px;
    border-radius: 20px;
    font-size: 12px;
    width: 100px;
    font-size: 14px;
    width: 70px;
    white-space: nowrap;

    &.status-published {
      background-color: #00b66a;
    }

    &.status-reviewing {
      background-color: #ffa72b;
    }
    &.status-history {
      background-color: #4b82f0;
    }

    &.status-draft {
      background-color: #909399;
    }
  }

  .operation-links {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 0;

    .el-link {
      font-size: 14px;
    }

    .link-separator {
      width: 4px;
      display: inline-block;
    }
  }

  .model-detail-wrapper {
    width: 100%;
    height: 100%;
    flex: 1;
    display: flex;
    flex-direction: column;
  }

  .error-list {
    white-space: pre-line;
    word-break: break-word;
  }
}
.status-tag {
  border-radius: 50px !important;
}
.el-scrollbar {
  max-width: 300px !important;
}
.el-popper {
  min-width: 300px !important;
}
.operation {
  justify-content: flex-start !important;
}
</style>
