<template>
  <Page>
    <VbenCard title="系统设置">
      <template #extra>
        <Icon icon="lucide:settings" class="text-lg" />
      </template>
      
      <VbenTabs v-model:active-key="activeTab" type="card">
        <!-- 基本信息 -->
        <VbenTabPane key="basic" tab="基本信息">
          <VbenForm @submit="handleSubmitBasic">
            <template #default="{ form }">
              <VbenFormItem name="site_name" label="网站名称">
                <Input v-model:value="form.site_name" placeholder="请输入网站名称" />
              </VbenFormItem>
              
              <VbenFormItem name="site_title" label="网站标题">
                <Input v-model:value="form.site_title" placeholder="请输入网站标题" />
              </VbenFormItem>
              
              <VbenFormItem name="site_description" label="网站描述">
                <Input 
                  v-model:value="form.site_description" 
                  type="textarea" 
                  :rows="3" 
                  placeholder="请输入网站描述" 
                />
              </VbenFormItem>
              
              <VbenFormItem name="site_keywords" label="网站关键词">
                <Input 
                  v-model:value="form.site_keywords" 
                  placeholder="请输入网站关键词，多个关键词用逗号分隔" 
                />
              </VbenFormItem>
              
              <VbenFormItem name="site_icp" label="ICP备案号">
                <Input v-model:value="form.site_icp" placeholder="请输入ICP备案号" />
              </VbenFormItem>
              
              <VbenFormItem name="site_copyright" label="版权信息">
                <Input 
                  v-model:value="form.site_copyright" 
                  type="textarea" 
                  :rows="2" 
                  placeholder="请输入版权信息" 
                />
              </VbenFormItem>
            </template>
            
            <template #submit>
              <Space>
                <PrimaryButton html-type="submit" :loading="submitLoading">
                  <Icon icon="lucide:check" class="mr-1" />
                  保存设置
                </PrimaryButton>
                <DefaultButton @click="handleResetBasic">
                  <Icon icon="lucide:rotate-ccw" class="mr-1" />
                  重置
                </DefaultButton>
              </Space>
            </template>
          </VbenForm>
        </VbenTabPane>
        
        <!-- 系统配置 -->
        <VbenTabPane key="config" tab="系统配置">
          <VbenForm @submit="handleSubmitConfig">
            <template #default="{ form }">
              <VbenFormItem name="site_status" label="系统状态">
                <RadioGroup v-model:value="form.site_status">
                  <template #default>
                    <Radio value="1">正常运行</Radio>
                    <Radio value="0">维护模式</Radio>
                  </template>
                </RadioGroup>
              </VbenFormItem>
              
              <VbenFormItem 
                v-if="form.site_status === '0'" 
                name="site_close_reason" 
                label="维护提示"
              >
                <Input 
                  v-model:value="form.site_close_reason" 
                  type="textarea" 
                  :rows="3" 
                  placeholder="请输入维护提示信息" 
                />
              </VbenFormItem>
              
              <VbenFormItem name="timezone" label="时区设置">
                <Select v-model:value="form.timezone" placeholder="请选择时区">
                  <template #default>
                    <SelectOption value="Asia/Shanghai">北京时间 (UTC+8)</SelectOption>
                    <SelectOption value="Asia/Tokyo">东京时间 (UTC+9)</SelectOption>
                    <SelectOption value="America/New_York">纽约时间 (UTC-5)</SelectOption>
                    <SelectOption value="Europe/London">伦敦时间 (UTC+0)</SelectOption>
                    <SelectOption value="Europe/Paris">巴黎时间 (UTC+1)</SelectOption>
                  </template>
                </Select>
              </VbenFormItem>
              
              <VbenFormItem name="default_language" label="默认语言">
                <Select v-model:value="form.default_language" placeholder="请选择默认语言">
                  <template #default>
                    <SelectOption value="zh-CN">简体中文</SelectOption>
                    <SelectOption value="zh-TW">繁体中文</SelectOption>
                    <SelectOption value="en-US">English</SelectOption>
                    <SelectOption value="ja-JP">日本語</SelectOption>
                    <SelectOption value="ko-KR">한국어</SelectOption>
                  </template>
                </Select>
              </VbenFormItem>
              
              <VbenFormItem name="page_size" label="分页大小">
                <InputNumber 
                  v-model:value="form.page_size" 
                  :min="10" 
                  :max="100" 
                  :step="10" 
                  placeholder="请输入分页大小" 
                />
              </VbenFormItem>
              
              <VbenFormItem name="cache_enabled" label="缓存启用">
                <Switch v-model:checked="form.cache_enabled" />
              </VbenFormItem>
              
              <VbenFormItem name="debug_enabled" label="调试模式">
                <Switch v-model:checked="form.debug_enabled" />
              </VbenFormItem>
            </template>
            
            <template #submit>
              <Space>
                <PrimaryButton html-type="submit" :loading="submitLoading">
                  <Icon icon="lucide:check" class="mr-1" />
                  保存设置
                </PrimaryButton>
                <DefaultButton @click="handleResetConfig">
                  <Icon icon="lucide:rotate-ccw" class="mr-1" />
                  重置
                </DefaultButton>
              </Space>
            </template>
          </VbenForm>
        </VbenTabPane>
        
        <!-- 系统信息 -->
        <VbenTabPane key="info" tab="系统信息">
          <VbenDescriptions title="服务器信息" :column="2" bordered>
            <VbenDescriptionsItem label="操作系统">
              {{ systemInfo.os || '-' }}
            </VbenDescriptionsItem>
            <VbenDescriptionsItem label="服务器软件">
              {{ systemInfo.server || '-' }}
            </VbenDescriptionsItem>
            <VbenDescriptionsItem label="PHP版本">
              {{ systemInfo.php_version || '-' }}
            </VbenDescriptionsItem>
            <VbenDescriptionsItem label="MySQL版本">
              {{ systemInfo.mysql_version || '-' }}
            </VbenDescriptionsItem>
            <VbenDescriptionsItem label="Redis版本">
              {{ systemInfo.redis_version || '-' }}
            </VbenDescriptionsItem>
            <VbenDescriptionsItem label="Node.js版本">
              {{ systemInfo.node_version || '-' }}
            </VbenDescriptionsItem>
            <VbenDescriptionsItem label="内存使用">
              {{ systemInfo.memory_usage || '-' }}
            </VbenDescriptionsItem>
            <VbenDescriptionsItem label="磁盘使用">
              {{ systemInfo.disk_usage || '-' }}
            </VbenDescriptionsItem>
          </VbenDescriptions>
          
          <div class="mt-4">
            <Space>
              <DefaultButton @click="handleRefreshInfo" :loading="refreshLoading">
                <Icon icon="lucide:refresh-cw" class="mr-1" />
                刷新信息
              </DefaultButton>
              <DefaultButton @click="handleExportInfo" :loading="exportLoading">
                <Icon icon="lucide:download" class="mr-1" />
                导出信息
              </DefaultButton>
            </Space>
          </div>
        </VbenTabPane>
      </VbenTabs>
    </VbenCard>
  </Page>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { Icon } from '@iconify/vue';
import { 
  Page, 
  VbenCard, 
  VbenTabs, 
  VbenTabPane,
  VbenDescriptions,
  VbenDescriptionsItem
} from '@vben/common-ui';
import { useVbenForm } from '#/adapter/form';
import type { VbenFormSchema } from '#/adapter/form';
import { 
  getSystemConfigApi, 
  updateSystemConfigApi,
  getSystemInfoApi,
  exportSystemInfoApi
} from '#/api/common/system';

// 响应式数据
const activeTab = ref('basic');
const submitLoading = ref(false);
const refreshLoading = ref(false);
const exportLoading = ref(false);

// 系统信息
const systemInfo = reactive({
  os: '',
  server: '',
  php_version: '',
  mysql_version: '',
  redis_version: '',
  node_version: '',
  memory_usage: '',
  disk_usage: '',
});

// 基本信息表单配置
const basicFormSchema: VbenFormSchema[] = [
  {
    component: 'Input',
    fieldName: 'site_name',
    label: '网站名称',
    rules: 'required',
    componentProps: {
      placeholder: '请输入网站名称',
    },
  },
  {
    component: 'Input',
    fieldName: 'site_title', 
    label: '网站标题',
    rules: 'required',
    componentProps: {
      placeholder: '请输入网站标题',
    },
  },
  {
    component: 'Input',
    fieldName: 'site_description',
    label: '网站描述',
    componentProps: {
      type: 'textarea',
      rows: 3,
      placeholder: '请输入网站描述',
    },
  },
  {
    component: 'Input',
    fieldName: 'site_keywords',
    label: '网站关键词',
    componentProps: {
      placeholder: '请输入网站关键词，多个关键词用逗号分隔',
    },
  },
  {
    component: 'Input',
    fieldName: 'site_icp',
    label: 'ICP备案号',
    componentProps: {
      placeholder: '请输入ICP备案号',
    },
  },
  {
    component: 'Input',
    fieldName: 'site_copyright',
    label: '版权信息',
    componentProps: {
      type: 'textarea',
      rows: 2,
      placeholder: '请输入版权信息',
    },
  },
];

// 系统配置表单配置
const configFormSchema: VbenFormSchema[] = [
  {
    component: 'RadioGroup',
    fieldName: 'site_status',
    label: '系统状态',
    rules: 'required',
    componentProps: {
      options: [
        { label: '正常运行', value: '1' },
        { label: '维护模式', value: '0' },
      ],
    },
  },
  {
    component: 'Input',
    fieldName: 'site_close_reason',
    label: '维护提示',
    dependencies: {
      triggerFields: ['site_status'],
      show: (values) => values.site_status === '0',
    },
    componentProps: {
      type: 'textarea',
      rows: 3,
      placeholder: '请输入维护提示信息',
    },
  },
  {
    component: 'Select',
    fieldName: 'timezone',
    label: '时区设置',
    rules: 'required',
    componentProps: {
      placeholder: '请选择时区',
      options: [
        { label: '北京时间 (UTC+8)', value: 'Asia/Shanghai' },
        { label: '东京时间 (UTC+9)', value: 'Asia/Tokyo' },
        { label: '纽约时间 (UTC-5)', value: 'America/New_York' },
        { label: '伦敦时间 (UTC+0)', value: 'Europe/London' },
        { label: '巴黎时间 (UTC+1)', value: 'Europe/Paris' },
      ],
    },
  },
  {
    component: 'Select',
    fieldName: 'default_language',
    label: '默认语言',
    rules: 'required',
    componentProps: {
      placeholder: '请选择默认语言',
      options: [
        { label: '简体中文', value: 'zh-CN' },
        { label: '繁体中文', value: 'zh-TW' },
        { label: 'English', value: 'en-US' },
        { label: '日本語', value: 'ja-JP' },
        { label: '한국어', value: 'ko-KR' },
      ],
    },
  },
  {
    component: 'InputNumber',
    fieldName: 'page_size',
    label: '分页大小',
    componentProps: {
      min: 10,
      max: 100,
      step: 10,
      placeholder: '请输入分页大小',
    },
  },
  {
    component: 'Switch',
    fieldName: 'cache_enabled',
    label: '缓存启用',
  },
  {
    component: 'Switch',
    fieldName: 'debug_enabled',
    label: '调试模式',
  },
];

// 创建表单实例
const [BasicForm, basicFormApi] = useVbenForm({
  schema: basicFormSchema,
  showDefaultActions: false,
});

const [ConfigForm, configFormApi] = useVbenForm({
  schema: configFormSchema,
  showDefaultActions: false,
});

// 处理基本信息提交
const handleSubmitBasic = async (values: Record<string, any>) => {
  try {
    submitLoading.value = true;
    await updateSystemConfigApi('basic', values);
    // 显示成功消息
  } catch (error) {
    console.error('保存基本信息失败:', error);
  } finally {
    submitLoading.value = false;
  }
};

// 处理系统配置提交
const handleSubmitConfig = async (values: Record<string, any>) => {
  try {
    submitLoading.value = true;
    await updateSystemConfigApi('config', values);
    // 显示成功消息
  } catch (error) {
    console.error('保存系统配置失败:', error);
  } finally {
    submitLoading.value = false;
  }
};

// 重置基本信息
const handleResetBasic = () => {
  basicFormApi.resetForm();
};

// 重置系统配置
const handleResetConfig = () => {
  configFormApi.resetForm();
};

// 刷新系统信息
const handleRefreshInfo = async () => {
  try {
    refreshLoading.value = true;
    const data = await getSystemInfoApi();
    Object.assign(systemInfo, data);
  } catch (error) {
    console.error('刷新系统信息失败:', error);
  } finally {
    refreshLoading.value = false;
  }
};

// 导出系统信息
const handleExportInfo = async () => {
  try {
    exportLoading.value = true;
    await exportSystemInfoApi();
  } catch (error) {
    console.error('导出系统信息失败:', error);
  } finally {
    exportLoading.value = false;
  }
};

// 初始化数据
const initData = async () => {
  try {
    const [basicData, configData, infoData] = await Promise.all([
      getSystemConfigApi('basic'),
      getSystemConfigApi('config'),
      getSystemInfoApi(),
    ]);
    
    basicFormApi.setValues(basicData);
    configFormApi.setValues(configData);
    Object.assign(systemInfo, infoData);
  } catch (error) {
    console.error('初始化数据失败:', error);
  }
};

// 组件挂载时初始化数据
onMounted(() => {
  initData();
});
</script>

<style scoped>
.card-header {
  display: flex;
  align-items: center;
}
</style>