<template>
  <div class="company-info-page">
    <div class="header-actions">
      <h2>企业基本信息管理</h2>
      <el-button type="primary" @click="handleSubmit" :loading="loading">保存修改</el-button>
    </div>

    <div class="form-container" v-loading="fetchLoading">
      <el-form :model="form" label-width="120px">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>公司简介</span>
            </div>
          </template>
          <el-form-item label="简介内容">
            <el-input 
              v-model="form.intro_content" 
              type="textarea" 
              :rows="6"
              placeholder="请输入公司简介"
            />
          </el-form-item>
          <el-form-item label="简介图片">
            <el-upload
              class="avatar-uploader"
              :http-request="customUpload"
              :show-file-list="false"
              :on-success="handleUploadSuccess"
            >
              <img v-if="form.intro_image_url" :src="getImageUrl(form.intro_image_url)" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-card>

        <el-card class="box-card" style="margin-top: 20px;">
          <template #header>
            <div class="card-header">
              <span>企业文化</span>
            </div>
          </template>
          <el-form-item label="企业愿景">
            <el-input v-model="form.vision" placeholder="例如：成为中国领先的人工智能产教融合服务商" />
          </el-form-item>
          <el-form-item label="企业使命">
            <el-input v-model="form.mission" placeholder="例如：赋能教育，智创未来" />
          </el-form-item>
          <el-form-item label="核心价值观">
            <el-input v-model="form.values" placeholder="例如：客户第一，创新驱动，诚信正直，合作共赢" />
          </el-form-item>
        </el-card>

        <el-card class="box-card" style="margin-top: 20px;">
          <template #header>
            <div class="card-header">
              <span>联系方式</span>
            </div>
          </template>
          <el-form-item label="联系电话">
            <el-input v-model="form.phone" placeholder="例如：123-456-7890" />
          </el-form-item>
          <el-form-item label="联系邮箱">
            <el-input v-model="form.email" placeholder="例如：contact@example.com" />
          </el-form-item>
          <el-form-item label="公众号二维码">
            <el-upload
              class="avatar-uploader"
              :http-request="customUploadQR"
              :show-file-list="false"
              :on-success="handleUploadSuccessQR"
            >
              <img v-if="form.qrcode_url" :src="getImageUrl(form.qrcode_url)" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-card>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import api from '../api'
import { ElMessage } from 'element-plus'

const fetchLoading = ref(false)
const loading = ref(false)
const form = ref({
  id: null,
  intro_content: '',
  intro_image_url: '',
  vision: '',
  mission: '',
  values: '',
  phone: '',
  email: '',
  qrcode_url: ''
})

const getImageUrl = (url) => {
  if (!url) return ''
  if (url.startsWith('http')) return url
  return `${import.meta.env.VITE_IMG_BASE_URL}${url}`
}

const customUpload = async (options) => {
  const { file, onSuccess, onError } = options
  const formData = new FormData()
  formData.append('file', file)
  
  try {
    const res = await api.post('/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    onSuccess(res.data)
  } catch (error) {
    onError(error)
    ElMessage.error('上传失败')
  }
}

const handleUploadSuccess = (response) => {
  form.value.intro_image_url = response.url
}

const customUploadQR = async (options) => {
  const { file, onSuccess, onError } = options
  const formData = new FormData()
  formData.append('file', file)
  
  try {
    const res = await api.post('/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    onSuccess(res.data)
  } catch (error) {
    onError(error)
    ElMessage.error('上传失败')
  }
}

const handleUploadSuccessQR = (response) => {
  form.value.qrcode_url = response.url
}

const fetchData = async () => {
  fetchLoading.value = true
  try {
    const res = await api.get('/company-info')
    if (res.data && res.data.id) {
      form.value = res.data
    } else {
        // Initialize with default values if empty
        form.value = {
            id: null,
            intro_content: '四川网讯创智科技有限公司（以下简称“网讯创智”）是一家专注于人工智能领域的产教融合服务商。公司致力于将产业前沿技术转化为教育资源，通过“产、学、研、用”一体化模式，为高校提供专业建设、人才培养、实验室建设等全方位解决方案。\n\n网讯创智依托百度、阿里、华为等头部企业的技术生态，构建了基于 MaaS（Model as a Service）架构的高校训战一体化综合实践平台，助力高校培养具备创新思维与实战能力的人工智能复合型人才。',
            intro_image_url: '',
            vision: '成为中国领先的人工智能产教融合服务商',
            mission: '赋能教育，智创未来',
            values: '客户第一，创新驱动，诚信正直，合作共赢',
            phone: '123-456-7890',
            email: 'contact@example.com',
            qrcode_url: 'https://api.qrserver.com/v1/create-qr-code/?size=100x100&data=网讯创智'
        }
    }
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    fetchLoading.value = false
  }
}

const handleSubmit = async () => {
  loading.value = true
  try {
    await api.post('/company-info', form.value)
    ElMessage.success('保存成功')
    fetchData()
  } catch (error) {
    ElMessage.error('保存失败')
  } finally {
    loading.value = false
  }
}

onMounted(fetchData)
</script>

<style scoped>
.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.box-card {
  width: 100%;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 300px;
  height: 200px;
  text-align: center;
  line-height: 200px;
}
.avatar {
  width: 300px;
  height: 200px;
  display: block;
  object-fit: cover;
}
</style>