<template>
  <el-form
    ref="normalFormRef"
    :model="formData"
    :rules="normalRules"
    label-width="120px"
    style="max-width: 600px"
  >
    <el-form-item label="站点名称" prop="sitename">
      <el-input v-model="sitename" placeholder="请输入站点名称" />
    </el-form-item>
    <el-form-item label="站点Logo" prop="logo">
      <el-upload
        class="logo-uploader"
        :show-file-list="false"
        :auto-upload="false"
        :on-change="handleLogoChange"
      >
        <img
          v-if="logo"
          :src="getPreviewUrl(logo)"
          class="logo-image"
        />
        <el-icon v-else class="logo-uploader-icon"><Plus /></el-icon>
      </el-upload>
    </el-form-item>
    <el-form-item label="站点Logo-浅色" prop="logow">
      <el-upload
        class="logo-uploader"
        :show-file-list="false"
        :auto-upload="false"
        :on-change="handleLogowChange"
      >
        <img
          v-if="logow"
          :src="getPreviewUrl(logow)"
          class="logo-image darkbg"
        />
        <el-icon v-else class="logo-uploader-icon"><Plus /></el-icon>
      </el-upload>
    </el-form-item>
    <el-form-item label="站点图标" prop="ico">
      <el-upload
        class="logo-uploader"
        :show-file-list="false"
        :auto-upload="false"
        :on-change="handleIconChange"
      >
        <img
          v-if="ico"
          :src="getPreviewUrl(ico)"
          class="logo-image"
        />
        <el-icon v-else class="logo-uploader-icon"><Plus /></el-icon>
      </el-upload>
      <div class="form-tip">请上传ico格式文件</div>
    </el-form-item>
    <el-form-item label="企业名称" prop="companyname">
      <el-input v-model="companyname" placeholder="请输入企业名称" />
    </el-form-item>
    <el-form-item label="企业介绍" prop="companyintroduction">
      <el-input v-model="companyintroduction" type="textarea" rows="5" placeholder="请输入企业介绍" />
    </el-form-item>
    <el-form-item label="站点简介" prop="description">
      <el-input v-model="description" placeholder="请输入站点简介" />
    </el-form-item>
    <el-form-item label="版权信息" prop="copyright">
      <el-input v-model="copyright" placeholder="如：© 2026 公司名称" />
    </el-form-item>
    <el-form-item label="备案号 " prop="icp">
      <el-input v-model="icp" placeholder="如：苏ICP备20260000号" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="handleSaveNormalInfos"
        >保存设置</el-button
      >
      <el-button @click="resetnormalForm">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import type { FormInstance, FormRules, UploadFile } from "element-plus";
import { getNormalInfos, saveNormalInfos } from "@/api/sitesettings";
import { uploadFile } from "@/api/file";
import { useAuthStore } from "@/stores/auth";

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;
const authStore = useAuthStore();

const normalFormRef = ref<FormInstance>();

const sitename = ref("");
const companyname = ref("");
const companyintroduction = ref("");
const logo = ref("");
const logow = ref("");
const description = ref("");
const copyright = ref("");
const icp = ref("");
const ico = ref("");

const formData = {
  sitename,
  companyname,
  companyintroduction,
  logo,
  logow,
  ico,
  description,
  copyright,
  icp,
};

const normalRules: FormRules = {
  sitename: [{ required: true, message: "请输入站点名称", trigger: "blur" }],
};

const getPreviewUrl = (url: string) => {
  const value = String(url || "").trim().replace(/\\/g, "/");
  if (!value) return "";
  if (/^(https?:\/\/|\/\/|data:|blob:)/i.test(value)) {
    return value;
  }

  const base = String(API_BASE_URL || "").replace(/\/+$/, "");
  const path = value.startsWith("/") ? value : `/${value}`;
  return `${base}${path}`;
};

//调用基础数据
const initNormalInfos = async () => {
  const res = await getNormalInfos(authStore.user.tid);
  if (res.code === 200 && res.data) {
    const data = res.data;
    sitename.value = data.sitename || "";
    companyintroduction.value = data.companyintroduction || "";
    logo.value = data.logo || "";
    logow.value = data.logow || "";
    ico.value = data.ico || "";
    description.value = data.description || "";
    copyright.value = data.copyright || "";
    icp.value = data.icp || "";
    companyname.value = data.companyname || "";
  }
};

const handleLogoChange = (file: UploadFile) => {
  const uploadFormData = new FormData();
  uploadFormData.append("file", file.raw);
  uploadFormData.append("cate", "site");

  uploadFile(uploadFormData).then((uploadRes) => {
    if (
      (uploadRes.code === 200 || uploadRes.code === 201) &&
      uploadRes.data &&
      uploadRes.data.url
    ) {
      logo.value = uploadRes.data.url.replace(/\\/g, "/");
    } else {
      ElMessage.error(uploadRes.msg || "上传失败");
    }
  });
};

const handleLogowChange = (file: UploadFile) => {
  const uploadFormData = new FormData();
  uploadFormData.append("file", file.raw);
  uploadFormData.append("cate", "site");

  uploadFile(uploadFormData).then((uploadRes) => {
    if (
      (uploadRes.code === 200 || uploadRes.code === 201) &&
      uploadRes.data &&
      uploadRes.data.url
    ) {
      logow.value = uploadRes.data.url.replace(/\\/g, "/");
    } else {
      ElMessage.error(uploadRes.msg || "上传失败");
    }
  });
};

const handleSaveNormalInfos = async () => {
  if (!normalFormRef.value) return;
  await normalFormRef.value.validate(async (valid) => {
    if (valid) {
      const data = {
        tid: authStore.user.tid,
        sitename: sitename.value,
        companyintroduction: companyintroduction.value,
        logo: logo.value,
        logow: logow.value,
        ico: ico.value, 
        description: description.value,
        companyname: companyname.value,
        copyright: copyright.value,
        icp: icp.value,
      };
      const res = await saveNormalInfos(data);
      if (res.code === 200) {
        ElMessage.success("保存成功");
      } else {
        ElMessage.error(res.msg || "保存失败");
      }
    }
  });
};

const handleIconChange = (file: UploadFile) => {
  const uploadFormData = new FormData();
  uploadFormData.append("file", file.raw);
  uploadFormData.append("cate", "site");

  uploadFile(uploadFormData).then((uploadRes) => {
    if ((uploadRes.code === 200 || uploadRes.code === 201) && uploadRes.data?.url) {
      ico.value = uploadRes.data.url.replace(/\\/g, "/");
    } else {
      ElMessage.error(uploadRes.msg || "上传失败");
    }
  });
};

const resetnormalForm = () => {
  sitename.value = "";
  companyname.value = "";
  companyintroduction.value = "";
  logo.value = "";
  logow.value = "";
  ico.value = "";
  description.value = "";
  copyright.value = "";
  icp.value = "";
};

defineExpose({
  sitename,
  companyname,
  companyintroduction,
  logo,
  logow,
  ico,
  description,
  copyright,
  icp,
});

// 初始化基础数据
onMounted(() => {
  initNormalInfos();
});
</script>

<style lang="less" scoped>
.darkbg {
  background-color: #efefef;
}

.form-tip{
  margin-left: 20px;
  color: #999;
  font-size: 12px;
  margin-top: 5px;
}

.logo-uploader {
  :deep(.el-upload) {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: all 0.3s;

    &:hover {
      border-color: #3973ff;
    }
  }

  .logo-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .logo-image {
    width: 100px;
    height: 100px;
    object-fit: contain;
    display: block;
  }
}
</style>
