<template>
  <div class="text-left">
    <el-button
      v-if="type === 'edit'"
      size="small"
      @click="dialogVisible = true"
      type="primary"
      :icon="Edit"
      >编辑</el-button>

    <el-button
      v-else
      @click="dialogVisible = true"
      type="primary"
      :icon="Plus"
      >添加</el-button>

    <teleport to="body">
      <el-dialog
        v-model="dialogVisible"
        :title="(type === 'edit' ? '编辑' : '添加') + 'Scrapyd服务'"
        width="500px"
        center
        @open="handleOpen"
      >
      <el-form
        :model="form"
        ref="formRef"
        :rules="rules"
        status-icon
        label-width="80px"
        size="default"
      >
        <el-form-item
          label="服务名称"
          prop="server_name"
        >
          <el-input v-model="form.server_name"></el-input>
        </el-form-item>

        <el-form-item
          label="服务地址"
          prop="server_url"
        >
          <el-input v-model="form.server_url"></el-input>
        </el-form-item>

        <el-form-item
          label="用户名"
          prop="username"
        >
          <el-input v-model="form.username"></el-input>
        </el-form-item>

        <el-form-item
          label="密码"
          prop="password"
        >
          <el-input v-model="form.password"></el-input>
        </el-form-item>

        <el-form-item
          label="启用/禁用"
          prop="status"
        >
          <el-switch
            v-model="form.status"
            :active-value="1"
            :inactive-value="0"
          ></el-switch>
        </el-form-item>
      </el-form>

      <template #footer>
        <span>
          <el-button
            size="default"
            @click="dialogVisible = false"
            >取 消</el-button>
          <el-button
            type="primary"
            size="default"
            @click="submit"
            >确 定</el-button>
        </span>
      </template>
    </el-dialog>
    </teleport>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, defineProps, defineEmits, watch } from 'vue';
import { Edit, Plus } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import type { FormInstance } from 'element-plus';
import { addScrapydServer, updateScrapydServer } from '@/api/scrapydServer';

// 定义props
const props = defineProps({
  type: { 
    type: String, 
    default: 'add' 
  },
  row: { 
    type: Object, 
    default: () => null 
  }
});

// 定义事件
const emit = defineEmits(['success']);

// 表单实例引用
const formRef = ref<FormInstance>();

// 对话框可见性
const dialogVisible = ref(false);

// 表单数据
const form = reactive({
  server_name: '',
  server_url: '',
  username: '',
  password: '',
  status: 1
});

// 表单验证规则
const rules = {
  server_name: [
    { required: true, message: '请输入服务名称', trigger: 'blur' }
  ],
  server_url: [
    { required: true, message: '请输入服务地址', trigger: 'blur' }
  ]
};

// 在对话框打开时处理数据
const handleOpen = () => {
  getData();
};

// 获取数据
const getData = () => {
  if (props.row && props.row.id) {
    for (const key in form) {
      if (Object.prototype.hasOwnProperty.call(form, key) && props.row[key] !== undefined) {
        (form as any)[key] = props.row[key];
      }
    }
  }
};

// 提交表单
const submit = () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      const params = {
        server_name: form.server_name,
        server_url: form.server_url,
        username: form.username,
        password: form.password,
        status: form.status
      };

      try {
        if (props.row && props.row.id) {
          const res = await updateScrapydServer({
            ...params,
            scrapydServerId: props.row.id
          });

          if (res.code === 0) {
            ElMessage.success('更新成功');
            emit('success');
            dialogVisible.value = false;
          } else {
            ElMessage.error(res.message || '更新失败');
          }
        } else {
          const res = await addScrapydServer(params);

          if (res.code === 0) {
            ElMessage.success('添加成功');
            emit('success');
            dialogVisible.value = false;
          } else {
            ElMessage.error(res.message || '添加失败');
          }
        }
      } catch (error) {
        console.error('提交失败:', error);
        ElMessage.error('操作失败');
      }
    }
  });
};
</script>

<style>
.el-button:focus {
    outline: none;
}

.el-dialog__headerbtn:focus {
  outline: none;
}
</style>
