<template>
  <div class="app-container theme-config-page">
    <el-card class="theme-card" shadow="never">
      <template #header>
        <div>
          <div class="page-title">展示主题配置</div>
          <div class="page-desc">用于配置机器人屏幕待机页的品牌信息、背景图、欢迎文案和按钮样式。</div>
        </div>
      </template>

      <el-alert
        v-if="!hasRemoteConfig"
        title="当前未配置待机页主题，屏幕端将使用本地默认主题。如需自定义展示内容，请填写配置并保存。"
        type="info"
        :closable="false"
        show-icon
        class="mb16"
      />

      <el-form
        ref="opsScreenThemeConfigRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        v-loading="loading"
      >
        <!-- 品牌信息 -->
        <el-divider content-position="left">品牌信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="Logo 图片" prop="logoUrl">
              <div class="custom-upload-wrap">
                <el-upload
                  class="asset-uploader"
                  drag
                  :action="uploadUrl"
                  :headers="uploadHeaders"
                  :show-file-list="false"
                  :before-upload="beforeLogoUpload"
                  :on-success="(res, file) => handleLogoSuccess(res, file)"
                  :on-error="handleUploadError">
                  <div v-if="form.logoUrl" class="upload-preview">
                    <img :src="form.logoUrl" class="preview-img" />
                    <div class="upload-overlay">
                      <el-icon><UploadFilled /></el-icon>
                      <span>重新上传</span>
                    </div>
                  </div>
                  <template v-else>
                    <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
                    <div class="el-upload__text">拖拽 Logo 到此处，或 <em>点击上传</em></div>
                  </template>
                </el-upload>
                <div v-if="form.logoUrl" class="upload-actions">
                  <el-button type="danger" size="small" @click="form.logoUrl = null">删除</el-button>
                </div>
              </div>
              <div class="form-tip">建议上传 png/jpg/jpeg 格式图片，大小不超过 200KB；未配置时屏幕端使用本地默认 Logo。</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌标题" prop="robotName">
              <el-input v-model="form.robotName" placeholder="请输入品牌标题" maxlength="50" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌副标题" prop="brandSubtitle">
              <el-input v-model="form.brandSubtitle" placeholder="请输入品牌副标题" maxlength="100" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 背景设置 -->
        <el-divider content-position="left">背景设置</el-divider>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="背景图" prop="backgroundImage">
              <div class="custom-upload-wrap">
                <el-upload
                  class="asset-uploader bg-uploader"
                  drag
                  :action="uploadUrl"
                  :headers="uploadHeaders"
                  :show-file-list="false"
                  :before-upload="beforeBgUpload"
                  :on-success="(res, file) => handleBgSuccess(res, file)"
                  :on-error="handleUploadError">
                  <div v-if="form.backgroundImage" class="upload-preview bg-preview">
                    <img :src="form.backgroundImage" class="preview-img" />
                    <div class="upload-overlay">
                      <el-icon><UploadFilled /></el-icon>
                      <span>重新上传</span>
                    </div>
                  </div>
                  <template v-else>
                    <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
                    <div class="el-upload__text">拖拽背景图到此处，或 <em>点击上传</em></div>
                  </template>
                </el-upload>
                <div v-if="form.backgroundImage" class="upload-actions">
                  <el-button type="danger" size="small" @click="form.backgroundImage = null">删除</el-button>
                </div>
              </div>
              <div class="form-tip">建议上传适配屏幕比例的横图，png/jpg/jpeg 格式，大小不超过 2MB；未配置时屏幕端使用本地默认背景。</div>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 欢迎文案 -->
        <el-divider content-position="left">欢迎文案</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="欢迎主标题" prop="welcomeTitle">
              <el-input v-model="form.welcomeTitle" placeholder="请输入欢迎主标题" maxlength="50" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="欢迎副标题" prop="welcomeSubtitle">
              <el-input v-model="form.welcomeSubtitle" placeholder="请输入欢迎副标题" maxlength="150" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 按钮设置 -->
        <el-divider content-position="left">按钮设置</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="按钮文案" prop="touchText">
              <el-input v-model="form.touchText" placeholder="请输入按钮文案" maxlength="50" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="按钮颜色" prop="buttonColor">
              <div class="color-row">
                <el-color-picker v-model="form.buttonColor" />
                <el-input v-model="form.buttonColor" placeholder="#2f8ee5" class="color-input" />
                <el-button @click="form.buttonColor = DEFAULT_FORM.buttonColor">默认蓝色</el-button>
              </div>
              <div class="form-tip">按钮阴影颜色由屏幕端根据按钮颜色自动生成，不单独配置。</div>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 备注 -->
        <el-divider content-position="left">备注</el-divider>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" maxlength="500" show-word-limit :rows="3" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 底部操作 -->
        <div class="bottom-actions">
          <el-button icon="Refresh" @click="handleRefresh">刷新</el-button>
          <el-button icon="Delete" @click="handleClearConfig">清空配置</el-button>
          <el-button type="primary" icon="Check" @click="submitForm">保存配置</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup name="OpsScreenThemeConfig">
import { listOpsScreenThemeConfig, addOpsScreenThemeConfig, updateOpsScreenThemeConfig, delOpsScreenThemeConfig } from '@/api/base/opsScreenThemeConfig'
import useUserStore from '@/store/modules/user'

const { proxy } = getCurrentInstance()

const loading = ref(false)
const hasRemoteConfig = ref(false)

// 上传配置
const uploadUrl = ref(import.meta.env.VITE_APP_BASE_API + '/common/uploadMediaFile')
const uploadHeaders = ref({
  Authorization: 'Bearer ' + useUserStore()?.token
})

const DEFAULT_FORM = {
  id: null,
  configKey: 'default',
  logoUrl: null,
  robotName: null,
  brandSubtitle: null,
  backgroundImage: null,
  welcomeTitle: null,
  welcomeSubtitle: null,
  touchText: null,
  buttonColor: '#2f8ee5',
  remark: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null
}

const form = ref({ ...DEFAULT_FORM })

const rules = {
  robotName: [
    { max: 50, message: '品牌标题不能超过 50 字', trigger: 'blur' }
  ],
  brandSubtitle: [
    { max: 100, message: '品牌副标题不能超过 100 字', trigger: 'blur' }
  ],
  welcomeTitle: [
    { max: 50, message: '欢迎主标题不能超过 50 字', trigger: 'blur' }
  ],
  welcomeSubtitle: [
    { max: 150, message: '欢迎副标题不能超过 150 字', trigger: 'blur' }
  ],
  touchText: [
    { max: 50, message: '按钮文案不能超过 50 字', trigger: 'blur' }
  ],
  buttonColor: [
    { validator: validateColor, trigger: 'blur' }
  ],
  remark: [
    { max: 500, message: '备注不能超过 500 字', trigger: 'blur' }
  ]
}

function validateColor(rule, value, callback) {
  if (!value) {
    callback()
    return
  }
  const reg = /^#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})$/
  if (!reg.test(value)) {
    callback(new Error('按钮颜色格式不正确，请输入类似 #2f8ee5 的颜色值'))
    return
  }
  callback()
}

/** 加载配置 */
function loadConfig(showSuccess = false) {
  loading.value = true
  listOpsScreenThemeConfig({ configKey: 'default', pageNum: 1, pageSize: 1 }).then(response => {
    const rows = response.rows || []
    if (rows.length > 0) {
      form.value = normalizeConfig(rows[0])
      hasRemoteConfig.value = true
    } else {
      form.value = { ...DEFAULT_FORM }
      hasRemoteConfig.value = false
    }
    if (showSuccess) {
      proxy.$modal.msgSuccess('刷新成功')
    }
  }).catch(() => {
    form.value = { ...DEFAULT_FORM }
    hasRemoteConfig.value = false
    if (showSuccess) {
      proxy.$modal.msgError('刷新失败，已显示空配置表单')
    }
  }).finally(() => {
    loading.value = false
  })
}

function normalizeConfig(config) {
  return {
    ...DEFAULT_FORM,
    ...(config || {}),
    configKey: 'default'
  }
}

/** 刷新 */
function handleRefresh() {
  loadConfig(true)
}

/** 清空配置 */
function handleClearConfig() {
  if (!form.value.id) {
    form.value = { ...DEFAULT_FORM }
    hasRemoteConfig.value = false
    proxy.$modal.msgSuccess('当前未配置待机页主题，屏幕端将使用本地默认主题')
    return
  }
  proxy.$modal.confirm('确认清空配置吗？该操作将删除当前运维端主题配置，删除后屏幕端将使用本地默认主题。').then(() => {
    return delOpsScreenThemeConfig(form.value.id)
  }).then(() => {
    proxy.$modal.msgSuccess('已清空配置，屏幕端将使用本地默认主题')
    form.value = { ...DEFAULT_FORM }
    hasRemoteConfig.value = false
  }).catch(() => {})
}

/** 保存配置 */
function normalizePayload(data) {
  const payload = {
    ...data,
    configKey: 'default'
  }
  const stringFields = [
    'logoUrl',
    'robotName',
    'brandSubtitle',
    'backgroundImage',
    'welcomeTitle',
    'welcomeSubtitle',
    'touchText',
    'buttonColor',
    'remark'
  ]
  stringFields.forEach(key => {
    if (typeof payload[key] === 'string') {
      const value = payload[key].trim()
      payload[key] = value === '' ? null : value
    }
  })
  if (!payload.buttonColor) {
    payload.buttonColor = DEFAULT_FORM.buttonColor
  }
  return payload
}

function submitForm() {
  proxy.$refs.opsScreenThemeConfigRef.validate(valid => {
    if (!valid) return
    const payload = normalizePayload(form.value)
    const request = payload.id ? updateOpsScreenThemeConfig(payload) : addOpsScreenThemeConfig(payload)
    request.then(() => {
      proxy.$modal.msgSuccess('保存成功')
      loadConfig()
    }).catch(() => {
      proxy.$modal.msgError('保存失败，请稍后重试')
    })
  })
}

/** Logo 上传前校验 */
function beforeLogoUpload(file) {
  const allowedTypes = ['image/jpeg', 'image/png', 'image/webp']
  const isAllowed = allowedTypes.includes(file.type)
  const isLt200KB = file.size / 1024 <= 200
  if (!isAllowed) {
    proxy.$modal.msgError('Logo 仅支持 jpg、png、webp 格式图片')
    return false
  }
  if (!isLt200KB) {
    proxy.$modal.msgError('Logo 文件大小不能超过 200KB')
    return false
  }
  proxy.$modal.loading('正在上传 Logo...')
  return true
}

/** Logo 上传成功 */
function handleLogoSuccess(response, file) {
  proxy.$modal.closeLoading()
  if (response.code === 200 || response.code === undefined) {
    const url = response.data?.fileUrl || response.fileUrl || response.url
    if (url) {
      form.value.logoUrl = url
      proxy.$modal.msgSuccess('Logo 上传成功')
    } else {
      proxy.$modal.msgError('Logo 上传成功，但未获取到文件地址')
    }
  } else {
    proxy.$modal.msgError(response.msg || 'Logo 上传失败')
  }
}

/** 背景图上传前校验 */
function beforeBgUpload(file) {
  const allowedTypes = ['image/jpeg', 'image/png', 'image/webp']
  const isAllowed = allowedTypes.includes(file.type)
  const isLt2MB = file.size / 1024 / 1024 <= 2
  if (!isAllowed) {
    proxy.$modal.msgError('背景图仅支持 jpg、png、webp 格式图片')
    return false
  }
  if (!isLt2MB) {
    proxy.$modal.msgError('背景图文件大小不能超过 2MB')
    return false
  }
  proxy.$modal.loading('正在上传背景图...')
  return true
}

/** 背景图上传成功 */
function handleBgSuccess(response, file) {
  proxy.$modal.closeLoading()
  if (response.code === 200 || response.code === undefined) {
    const url = response.data?.fileUrl || response.fileUrl || response.url
    if (url) {
      form.value.backgroundImage = url
      proxy.$modal.msgSuccess('背景图上传成功')
    } else {
      proxy.$modal.msgError('背景图上传成功，但未获取到文件地址')
    }
  } else {
    proxy.$modal.msgError(response.msg || '背景图上传失败')
  }
}

/** 上传失败 */
function handleUploadError(error) {
  proxy.$modal.closeLoading()
  proxy.$modal.msgError('文件上传失败，请检查文件格式或稍后重试')
}

onMounted(() => {
  loadConfig()
})
</script>

<style scoped>
.theme-config-page {
  min-height: calc(100vh - 84px);
}
.theme-card {
  max-width: 1100px;
}
.page-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}
.page-desc {
  margin-top: 6px;
  font-size: 13px;
  color: #909399;
}
.mb16 {
  margin-bottom: 16px;
}
.form-tip {
  width: 100%;
  margin-top: 4px;
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
}
.color-row {
  display: flex;
  align-items: center;
  gap: 10px;
}
.color-input {
  width: 130px;
}
.bottom-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding-top: 18px;
  border-top: 1px solid #ebeef5;
}
/* 自定义上传样式 */
.custom-upload-wrap {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}
.asset-uploader {
  width: 148px;
}
.asset-uploader :deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.2s;
}
.asset-uploader :deep(.el-upload:hover) {
  border-color: #409eff;
}
.asset-uploader :deep(.el-upload-dragger) {
  width: 100%;
  height: 148px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #fafafa;
}
.bg-uploader :deep(.el-upload-dragger) {
  height: 120px;
}
.upload-preview {
  width: 100%;
  height: 100%;
  position: relative;
}
.preview-img {
  width: 100%;
  height: 100%;
  object-fit: contain;
  background: #fff;
}
.upload-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #fff;
  opacity: 0;
  transition: opacity 0.2s;
}
.upload-preview:hover .upload-overlay {
  opacity: 1;
}
.upload-overlay .el-icon {
  font-size: 28px;
  margin-bottom: 4px;
}
.upload-overlay span {
  font-size: 12px;
}
.bg-preview .preview-img {
  object-fit: cover;
}
.upload-actions {
  padding-top: 4px;
}
</style>
