<template>
  <div class="part-box">
    <el-table class="page-table" :data="tableData" border stripe>
      <el-table-column prop="type" label="类型" width="180" />
      <el-table-column prop="description" label="详情" />
      <el-table-column label="操作" width="100">
        <template #default="scope">
          <el-button type="primary" link @click="handleEdit(scope.row)"
            >修改</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </div>

  <!-- 配置项修改 -->
  <el-dialog
    v-model="dialogVisible"
    title="修改配置"
    width="600px"
    :close-on-click-modal="false"
    @close="handleDialogClose"
  >
    <el-form ref="formRef" :model="formModel" :rules="rules" label-width="80px">
      <el-form-item label="类型">
        <el-input v-model="formModel.type" readonly disabled />
      </el-form-item>
      <el-form-item label="详情" prop="description">
        <el-input
          v-if="!isEnableDetail"
          v-model="formModel.description"
          type="textarea"
          :rows="4"
          placeholder="请输入详情"
        />
        <el-switch v-else v-model="formModel.description" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">返回</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit"
          >保存</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, computed } from 'vue';
  import type { FormInstance, FormRules } from 'element-plus';
  import { ElMessage } from 'element-plus';
  import { SettingItem } from '@/api/types/admin';

  // 假设有API获取和更新配置
  // import { getSystemSettings, updateSystemSetting } from '@/api/admin';

  defineOptions({
    name: 'SetManage',
  });

  const tableData = ref<SettingItem[]>([]);
  const dialogVisible = ref(false);
  const formRef = ref<FormInstance>();
  const loading = ref(false);

  const initialFormState: Partial<SettingItem> = {
    id: '',
    type: '',
    description: '',
    key: '',
  };
  const formModel = reactive({ ...initialFormState });

  const isEnableDetail = computed(() => {
    return (
      formModel.key === 'enable_marking_process' ||
      formModel.key === 'calculate_scanned_cards'
    );
  });

  const rules = reactive<FormRules>({
    description: [{ required: true, message: '请输入详情', trigger: 'blur' }],
  });

  // 模拟API调用获取数据
  const mockFetchSettings = async () => {
    return new Promise<SettingItem[]>((resolve) => {
      setTimeout(() => {
        resolve([
          {
            id: 1,
            type: '图片服务',
            description: 'http://192.168.10.83:9004/',
            key: 'image_service_url',
          },
          {
            id: 2,
            type: '评阅时长',
            description: '60',
            key: 'review_duration_minutes',
          },
          {
            id: 3,
            type: '启动阅卷',
            description: false,
            key: 'enable_marking_process',
          },
          {
            id: 4,
            type: '计算扫描卡张数',
            description: false,
            key: 'calculate_scanned_cards',
          },
        ]);
      }, 500);
    });
  };

  const loadSettings = async () => {
    try {
      // const res = await getSystemSettings(); // 实际API调用
      const res = await mockFetchSettings(); // 使用模拟数据
      tableData.value = res;
    } catch (error) {
      console.error('获取配置失败:', error);
      ElMessage.error('获取配置失败');
    }
  };

  onMounted(() => {
    loadSettings();
  });

  const handleEdit = (row: SettingItem) => {
    Object.assign(formModel, row);
    dialogVisible.value = true;
  };

  const handleDialogClose = () => {
    formRef.value?.resetFields();
    Object.assign(formModel, initialFormState);
  };

  const handleSubmit = async () => {
    if (!formRef.value) return;
    try {
      const valid = await formRef.value?.validate().catch(() => false);
      if (!valid) return;
      loading.value = true;
      // const paramsToUpdate = { key: formModel.key, value: formModel.description, id: formModel.id };
      // await updateSystemSetting(paramsToUpdate); // 实际API调用
      console.log('保存的配置:', formModel);
      ElMessage.success('保存成功');
      dialogVisible.value = false;
      await loadSettings(); // 重新加载数据
    } catch (error) {
      console.error('保存失败:', error);
      // ElMessage.error('保存失败');
    } finally {
      loading.value = false;
    }
  };
</script>
