<template>
  <div class="page-container">
    <div class="page-header">
      <span class="breadcrumb-label">当前位置：</span>
      <span class="breadcrumb-path">院区信息管理</span>
      <span class="breadcrumb-separator">&gt;</span>
      <span class="breadcrumb-current">医院概况</span>
    </div>
    <div class="page-content">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-mask">
        <div class="loading-spinner"></div>
        <span>加载中...</span>
      </div>
      <form class="hospital-form" @submit.prevent="handleSave" v-show="!loading">
        <!-- 医院名称 -->
        <div class="form-item required">
          <label>医院名称</label>
          <input 
            v-model="form.name" 
            type="text" 
            placeholder="请输入医院名称" 
            maxlength="100"
          />
        </div>

        <!-- 医院Logo -->
        <div class="form-item">
          <label>医院Logo</label>
          <div class="logo-section">
            <!-- Logo展示框 -->
            <div class="logo-display">
              <div class="logo-box">
                <img v-if="form.logo" :src="getLogoUrl(form.logo)" alt="医院Logo" />
                <div v-else class="logo-placeholder">
                  <span>暂无Logo</span>
                </div>
              </div>
            </div>
            <!-- 上传操作区 -->
            <div class="logo-upload">
              <input 
                type="file" 
                ref="fileInput"
                accept=".jpg,.jpeg,.png" 
                @change="handleFileChange"
                style="display: none;"
              />
              <button type="button" class="upload-btn" @click="$refs.fileInput.click()">上传Logo</button>
              <button type="button" class="remove-btn" v-if="form.logo" @click="removeLogo">删除Logo</button>
              <p class="upload-tip">支持jpg、png格式，大小不超过10M</p>
            </div>
          </div>
        </div>

        <!-- 医院地址 -->
        <div class="form-item">
          <label>医院地址</label>
          <input 
            v-model="form.address" 
            type="text" 
            placeholder="请输入医院地址" 
            maxlength="200"
          />
        </div>

        <!-- 联系电话 -->
        <div class="form-item">
          <label>联系电话</label>
          <input 
            v-model="form.phone" 
            type="text" 
            placeholder="请输入联系电话" 
            maxlength="50"
          />
        </div>

        <!-- 医院介绍 -->
        <div class="form-item">
          <label>医院介绍</label>
          <div class="editor-container">
            <Toolbar
              :editor="editorRef"
              :defaultConfig="toolbarConfig"
              mode="default"
              style="border-bottom: 1px solid #ccc;"
            />
            <Editor
              v-model="form.introduction"
              :defaultConfig="editorConfig"
              mode="default"
              style="height: 300px; overflow-y: hidden;"
              @onCreated="handleCreated"
            />
          </div>
        </div>

        <!-- 提交按钮 -->
        <div class="form-actions">
          <button type="submit" class="save-btn" :disabled="saving">
            {{ saving ? '保存中...' : '保存' }}
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, shallowRef } from 'vue'
import request from '@/utils/request'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'

// 编辑器实例
const editorRef = shallowRef()

// 工具栏配置
const toolbarConfig = {}

// 编辑器配置
const editorConfig = {
  placeholder: '请输入医院介绍...',
  MENU_CONF: {}
}

// 表单数据
const form = reactive({
  name: '',
  logo: '',
  address: '',
  phone: '',
  introduction: ''
})

const saving = ref(false)
const loading = ref(false)
const fileInput = ref(null)

// 组件挂载时获取数据
onMounted(async () => {
  loading.value = true
  try {
    await loadHospitalInfo()
  } finally {
    loading.value = false
  }
})

// 组件销毁前销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor) {
    editor.destroy()
  }
})

// 编辑器创建回调
const handleCreated = (editor) => {
  editorRef.value = editor
}

// 加载医院信息
const loadHospitalInfo = async () => {
  try {
    const res = await request.get('/api/hospital/info')
    if (res.code === 200 && res.data) {
      Object.assign(form, res.data)
    }
  } catch (error) {
    console.error('加载医院信息失败：', error)
  }
}

// 获取Logo完整URL
const getLogoUrl = (logo) => {
  if (!logo) return ''
  if (logo.startsWith('http')) return logo
  // 图片保存在前端 public/img 目录，可直接访问
  return logo
}

// 删除Logo
const removeLogo = () => {
  form.logo = ''
}

// 文件选择处理
const handleFileChange = async (e) => {
  const file = e.target.files[0]
  if (!file) return

  // 检查文件大小
  if (file.size > 10 * 1024 * 1024) {
    alert('文件大小不能超过10M')
    return
  }

  // 检查文件类型
  const validTypes = ['image/jpeg', 'image/png', 'image/jpg']
  if (!validTypes.includes(file.type)) {
    alert('只支持jpg、png格式图片')
    return
  }

  // 上传文件
  const formData = new FormData()
  formData.append('file', file)

  try {
    const res = await request.post('/api/hospital/upload-logo', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
    if (res.code === 200) {
      form.logo = res.data
    } else {
      alert(res.message || '上传失败')
    }
  } catch (error) {
    console.error('上传失败：', error)
    alert('上传失败')
  }

  // 清空文件输入
  e.target.value = ''
}

// 保存表单
const handleSave = async () => {
  if (!form.name) {
    alert('请输入医院名称')
    return
  }

  saving.value = true
  try {
    const res = await request.post('/api/hospital/save', form)
    if (res.code === 200) {
      alert('保存成功')
    } else {
      alert(res.message || '保存失败')
    }
  } catch (error) {
    console.error('保存失败：', error)
    alert('保存失败')
  } finally {
    saving.value = false
  }
}
</script>

<style scoped>
.page-container {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
}
.page-header {
  border-bottom: 1px solid #eee;
  padding-bottom: 15px;
  margin-bottom: 20px;
  font-size: 14px;
}
.breadcrumb-label {
  color: #666;
}
.breadcrumb-path {
  color: #666;
}
.breadcrumb-separator {
  margin: 0 5px;
  color: #666;
}
.breadcrumb-current {
  color: #409eff;
}

/* 表单样式 */
.hospital-form {
  max-width: 800px;
}

.form-item {
  margin-bottom: 24px;
}

.form-item label {
  display: block;
  margin-bottom: 8px;
  color: #333;
  font-size: 14px;
}

.form-item.required label::before {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}

.form-item input[type="text"] {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  box-sizing: border-box;
}

.form-item input[type="text"]:focus {
  outline: none;
  border-color: #667eea;
}

/* Logo展示和上传 */
.logo-section {
  display: flex;
  align-items: flex-start;
  gap: 24px;
}

.logo-display {
  flex-shrink: 0;
}

.logo-box {
  width: 150px;
  height: 150px;
  border: 2px dashed #dcdfe6;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fafafa;
  overflow: hidden;
}

.logo-box img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.logo-placeholder {
  text-align: center;
  color: #c0c4cc;
}

.logo-placeholder span {
  font-size: 14px;
}

.logo-upload {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 10px;
}

.logo-upload .upload-btn {
  padding: 8px 20px;
  background: #667eea;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.logo-upload .upload-btn:hover {
  background: #5a6fd6;
}

.logo-upload .remove-btn {
  padding: 8px 20px;
  background: #f56c6c;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.logo-upload .remove-btn:hover {
  background: #f45c5c;
}

.upload-tip {
  margin: 0;
  font-size: 12px;
  color: #909399;
}

/* 编辑器 */
.editor-container {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

/* 提交按钮 */
.form-actions {
  margin-top: 30px;
}

.save-btn {
  padding: 12px 40px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
}

.save-btn:hover {
  opacity: 0.9;
}

.save-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 加载状态 */
.loading-mask {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100px 0;
  color: #909399;
}
.loading-spinner {
  width: 32px;
  height: 32px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #409eff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 12px;
}
@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>
