<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { Page } from '@vben/common-ui';
import { Card, Form, Input, Button, message, Tabs, InputNumber, Upload } from 'ant-design-vue';
import { useAppConfig } from '@vben/hooks';
import { 
  getSettingApi, 
  saveSettingApi,
  uploadSettingImageApi,
  type SettingApi 
} from '#/api';

defineOptions({ name: 'SettingIndex' });

const formRef = ref();
const loading = ref(false);
const uploading = ref(false);
const activeTab = ref('basic');
const { apiURL } = useAppConfig(import.meta.env, import.meta.env.PROD);
const fileList = ref<any[]>([]);

const formData = ref<Partial<SettingApi.SettingInfo>>({
  site_name: '',
  site_desc: '',
  site_icp: '',
  default_avatar: '',
  upload_allowed_ext: '',
  upload_max_size: '',
  upload_path: '',
  upload_image_size: '',
  upload_image_ext: '',
  mail_host: '',
  mail_port: '',
  mail_username: '',
  mail_password: '',
  wxapp_appid: '',
  wxapp_secret: '',
  wxapp_name: '',
  wxapp_original: '',
});

// 获取完整的头像URL
const getAvatarUrl = (avatarPath?: string | null): string => {
  if (!avatarPath) return '';
  // 如果已经是完整URL，直接返回
  if (avatarPath.startsWith('http://') || avatarPath.startsWith('https://')) {
    return avatarPath;
  }
  // 拼接完整的URL
  if (!apiURL) {
    console.warn('apiURL is not configured');
    return avatarPath;
  }
  const baseUrl = apiURL.replace(/\/$/, '');
  const path = avatarPath.startsWith('/') ? avatarPath : `/${avatarPath}`;
  return `${baseUrl}${path}`;
};

const fetchData = async () => {
  loading.value = true;
  try {
    const res = await getSettingApi();
    // 支持 code 为 0 或 200 的成功响应
    if (res && (res.code === 0 || res.code === 200)) {
      // 根据实际返回格式，数据在 res.data 中
      const data = res.data || res;
      formData.value = {
        site_name: data.site_name || '',
        site_desc: data.site_desc || '',
        site_icp: data.site_icp || '',
        site_banners: data.site_banners || '',
        default_avatar: data.default_avatar || '',
        upload_allowed_ext: data.upload_allowed_ext || '',
        upload_max_size: data.upload_max_size || '',
        upload_path: data.upload_path || '',
        upload_image_size: data.upload_image_size || '',
        upload_image_ext: data.upload_image_ext || '',
        mail_host: data.mail_host || '',
        mail_port: data.mail_port || '',
        mail_username: data.mail_username || '',
        mail_password: data.mail_password || '',
        wxapp_appid: data.wxapp_appid || '',
        wxapp_secret: data.wxapp_secret || '',
        wxapp_name: data.wxapp_name || '',
        wxapp_original: data.wxapp_original || '',
      };
      // 初始化头像文件列表
      if (formData.value.default_avatar) {
        const avatarUrl = getAvatarUrl(formData.value.default_avatar);
        fileList.value = [
          {
            uid: '-1',
            name: 'avatar',
            status: 'done',
            url: avatarUrl,
          },
        ];
      } else {
        fileList.value = [];
      }
    } else {
      message.error(res?.message || res?.msg || '获取系统设置失败');
    }
  } catch (error: any) {
    console.error('获取系统设置失败:', error);
    message.error(error?.response?.data?.message || error?.response?.data?.msg || '获取系统设置失败');
  } finally {
    loading.value = false;
  }
};

// 处理头像上传前
const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith('image/');
  if (!isImage) {
    message.error('只能上传图片文件！');
    return false;
  }
  const isLt10M = file.size / 1024 / 1024 < 10;
  if (!isLt10M) {
    message.error('图片大小不能超过 10MB！');
    return false;
  }
  
  // 立即上传
  handleUpload(file);
  
  return false; // 阻止自动上传
};

// 上传图片
const handleUpload = async (file: File) => {
  try {
    uploading.value = true;
    const res = await uploadSettingImageApi(file);
    
    // 处理响应，获取图片路径
    // 支持多种响应格式：
    // 1. { code: 200, data: "path" } 或 { code: 200, data: { src: "path" } }
    // 2. { code: 200, data: { url: "path" } } 或 { code: 200, data: { path: "path" } }
    // 3. 直接返回字符串路径
    // 4. { url: "path" } 或 { path: "path" }
    let imagePath = '';
    if (res && (res.code === 0 || res.code === 200)) {
      // 标准响应格式
      if (typeof res.data === 'string') {
        imagePath = res.data;
      } else if (res.data?.src) {
        // 优先使用 src 字段
        imagePath = res.data.src;
      } else if (res.data?.url || res.data?.path) {
        imagePath = res.data.url || res.data.path;
      }
    } else if (typeof res === 'string') {
      // 直接返回字符串
      imagePath = res;
    } else if (res?.data) {
      // 嵌套的 data 字段
      if (typeof res.data === 'string') {
        imagePath = res.data;
      } else {
        imagePath = res.data.src || res.data.url || res.data.path || '';
      }
    } else if (res?.src || res?.url || res?.path) {
      // 直接包含 src、url 或 path
      imagePath = res.src || res.url || res.path;
    }
    
    if (imagePath) {
      formData.value.default_avatar = imagePath;
      // 更新文件列表
      const avatarUrl = getAvatarUrl(imagePath);
      fileList.value = [
        {
          uid: Date.now().toString(),
          name: file.name,
          status: 'done',
          url: avatarUrl,
        },
      ];
      message.success('头像上传成功');
    } else {
      message.error('上传失败：未获取到图片路径');
    }
  } catch (error: any) {
    message.error(error?.response?.data?.message || error?.message || '上传头像失败');
  } finally {
    uploading.value = false;
  }
};

// 处理头像上传变化
const handleAvatarChange = (info: any) => {
  if (info.file.status === 'removed') {
    fileList.value = [];
    formData.value.default_avatar = '';
  }
};

const handleSubmit = async () => {
  try {
    await formRef.value.validate();
    loading.value = true;
    await saveSettingApi(formData.value);
    message.success('保存成功');
  } catch (error) {
    console.error('保存失败:', error);
  } finally {
    loading.value = false;
  }
};

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

<template>
  <Page title="系统设置">
    <Card>
      <Form
        ref="formRef"
        :model="formData"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 20 }"
      >
        <Tabs v-model:activeKey="activeTab">
          <Tabs.TabPane key="basic" tab="基本信息">
            <Form.Item label="站点名称" name="site_name">
              <Input v-model:value="formData.site_name" placeholder="请输入站点名称" />
            </Form.Item>
            <Form.Item label="站点描述" name="site_desc">
              <Input v-model:value="formData.site_desc" placeholder="请输入站点描述" />
            </Form.Item>
            <Form.Item label="ICP备案号" name="site_icp">
              <Input v-model:value="formData.site_icp" placeholder="请输入ICP备案号" />
            </Form.Item>
            <Form.Item label="默认头像" name="default_avatar">
              <Upload
                v-model:file-list="fileList"
                list-type="picture-card"
                :max-count="1"
                :before-upload="beforeUpload"
                :disabled="uploading"
                @change="handleAvatarChange"
                accept="image/*"
              >
                <div v-if="fileList.length < 1">
                  <div style="margin-top: 8px">
                    <span>上传</span>
                  </div>
                </div>
              </Upload>
            </Form.Item>
          </Tabs.TabPane>
          <Tabs.TabPane key="upload" tab="上传设置">
            <Form.Item label="上传路径" name="upload_path">
              <Input v-model:value="formData.upload_path" placeholder="请输入上传路径" />
            </Form.Item>
            <Form.Item label="允许上传扩展名" name="upload_allowed_ext">
              <Input v-model:value="formData.upload_allowed_ext" placeholder="如：jpg,png" />
            </Form.Item>
            <Form.Item label="上传最大大小(MB)" name="upload_max_size">
              <InputNumber v-model:value="formData.upload_max_size" :min="0" placeholder="请输入上传最大大小" style="width: 100%" />
            </Form.Item>
            <Form.Item label="图片扩展名" name="upload_image_ext">
              <Input v-model:value="formData.upload_image_ext" placeholder="如：jpg,jpeg,png,gif,webp" />
            </Form.Item>
            <Form.Item label="图片大小限制(MB)" name="upload_image_size">
              <InputNumber v-model:value="formData.upload_image_size" :min="0" placeholder="请输入图片大小限制" style="width: 100%" />
            </Form.Item>
          </Tabs.TabPane>
          <Tabs.TabPane key="mail" tab="邮件设置">
            <Form.Item label="邮件主机" name="mail_host">
              <Input v-model:value="formData.mail_host" placeholder="请输入邮件主机" />
            </Form.Item>
            <Form.Item label="邮件端口" name="mail_port">
              <InputNumber v-model:value="formData.mail_port" :min="0" :max="65535" placeholder="请输入邮件端口" style="width: 100%" />
            </Form.Item>
            <Form.Item label="邮件用户名" name="mail_username">
              <Input v-model:value="formData.mail_username" placeholder="请输入邮件用户名" />
            </Form.Item>
            <Form.Item label="邮件密码" name="mail_password">
              <Input.Password v-model:value="formData.mail_password" placeholder="请输入邮件密码" />
            </Form.Item>
          </Tabs.TabPane>
          <Tabs.TabPane key="wxapp" tab="微信小程序">
            <Form.Item label="小程序AppID" name="wxapp_appid">
              <Input v-model:value="formData.wxapp_appid" placeholder="请输入小程序AppID" />
            </Form.Item>
            <Form.Item label="小程序Secret" name="wxapp_secret">
              <Input.Password v-model:value="formData.wxapp_secret" placeholder="请输入小程序Secret" />
            </Form.Item>
            <Form.Item label="小程序名称" name="wxapp_name">
              <Input v-model:value="formData.wxapp_name" placeholder="请输入小程序名称" />
            </Form.Item>
            <Form.Item label="原始ID" name="wxapp_original">
              <Input v-model:value="formData.wxapp_original" placeholder="请输入原始ID" />
            </Form.Item>
          </Tabs.TabPane>
        </Tabs>
        <Form.Item :wrapper-col="{ offset: 4, span: 20 }">
          <Button type="primary" :loading="loading" @click="handleSubmit">保存</Button>
        </Form.Item>
      </Form>
    </Card>
  </Page>
</template>

