<template>
  <div class="base">
    <div class="base-content">
      <p class="title">系统名称与LOGO配置</p>
      <el-form ref="ruleFormRef" :model="form">
        <el-form-item label="系统名称" prop="name">
          <el-input v-model="form.name" maxlength="11" show-word-limit />
        </el-form-item>
        <el-form-item label="系统图标" prop="logo">
          <div class="text-center">
            <el-upload
              v-model:file-list="fileList"
              list-type="picture-card"
              :limit="1"
              :on-remove="handleRemove"
              :action="uploadUrl"
              :on-change="handleChange"
              :before-upload="beforeUpload"
              :on-exceed="handleExceed"
              :auto-upload="false"
              accept="image/jpeg,image/png"
              :on-preview="handlePictureCardPreview"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>

            <el-dialog v-model="dialogVisible">
              <img w-full :src="dialogImageUrl" alt="Preview Image" />
            </el-dialog>
          </div>
        </el-form-item>
        <el-form-item class="ml-17">
          <p>只支持.jpg、.png格式,最多上传1张，单张大小不超过500kb</p>
        </el-form-item>
        <el-form-item class="button-item">
          <div class="flex justify-center gap-4">
            <el-button @click="cancel" class="w-120px mr-100px -ml-100px">取 消</el-button>
            <el-button type="primary" @click="save" class="w-120px">保存配置</el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import type { UploadProps, UploadUserFile } from 'element-plus';
import { uploadDemo, getDemo, updateDemo } from '@/api/systemList/index';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import router from '@/router';

const uploadUrl = import.meta.env.VITE_BASE_API + '/system/logo/upload';

const form = ref({
  name: '可视化电子围栏管理系统',
  url: ''
});

const getList = async () => {
  const res = await getDemo();

  console.log('getList基本数据', res);

  if (res.data.url) {
    fileList.value = [
      {
        url: res.data.url,
        name: '系统图标'
      }
    ];
    form.value.url = res.data.url;
    form.value.name = res.data.name;
  }
};

const cancel = () => {
  fileList.value = [];
  form.value.url = '';
  form.value.name = '';
};
const save = async () => {
  console.log('保存数据', form.value);
  updateDemo(form.value)
    .then((res) => {
      console.log('保存成功', res);
      ElMessage.success('保存成功');
      // 刷新当前路由
      router.go(0);
    })
    .catch((err) => {
      console.error('保存失败', err);
      // ElMessage.error('保存失败');
    });
};

/* ------------------------------------------ 图片上传逻辑----------------------------------------- */

const fileList = ref<UploadUserFile[]>([]);

const dialogImageUrl = ref('');
const dialogVisible = ref(false);

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  // 清空 logo 字段
  form.value.url = '';
};

// 处理超出限制的情况
const handleExceed: UploadProps['onExceed'] = () => {
  ElMessage.warning('最多只能上传1张图片，请先删除现有图片后再上传');
};

// 自定义 change 处理函数
const handleChange = (file: any) => {
  // ⚠️ 核心点：必须使用 file.raw 才能获取到真实的原生 File 对象
  const realFile = file.raw;

  console.log('原生file对象', realFile);

  // 直接调用你封装好的 uploadDemo 方法
  uploadDemo(realFile)
    .then((res) => {
      console.log('上传成功', res);
      form.value.url = res.data.imgUrl;
      console.log('上传设备', form.value);
      fileList.value = [form.value];
      //getList(); // 刷新列表获取最新的 logo URL
    })
    .catch((err) => {
      console.error('上传失败', err);
      fileList.value = []; // 清空上传列表
    });
};

//验证逻辑
const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
  console.log('开始上传');

  // 验证文件大小（500KB）
  const isLt500K = rawFile.size / 1024 / 1024 < 0.5;
  if (!isLt500K) {
    ElMessage.error('图片大小不能超过 500KB!');
    return false;
  }

  // 验证文件类型
  const isJPGorPNG = rawFile.type === 'image/jpeg' || rawFile.type === 'image/png';
  if (!isJPGorPNG) {
    ElMessage.error('只能上传 JPG/PNG 格式的图片!');
    return false;
  }

  return true;
};

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};

onMounted(() => {
  getList();
});
</script>

<style lang="scss" scoped>
.base {
  margin: 0 auto;
  padding: 20px;
  height: 100vh;
  width: 100vw;
  background-color: #fff;
  .base-content {
    width: 800px;
    margin: 0 auto;
    padding: 20px;
  }
}

// 覆盖 el-form-item 默认样式，确保按钮居中
:deep(.button-item) {
  .el-form-item__content {
    justify-content: center !important;
    margin-top: 50px;
  }
}
</style>
