<template>
  <div class="smart-host-container">
    <a-card title="智能主机管理" :bordered="false">
      <a-row :gutter="16">
        <a-col :span="24">
          <a-form layout="inline" :model="searchForm">
            <a-form-item label="主机编号">
              <a-input v-model:value="searchForm.hostId" placeholder="请输入主机编号" />
            </a-form-item>
            <a-form-item label="状态">
              <a-select v-model:value="searchForm.status" placeholder="请选择状态" style="width: 120px">
                <a-select-option value="online">在线</a-select-option>
                <a-select-option value="offline">离线</a-select-option>
                <a-select-option value="maintenance">维护中</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="handleSearch">查询</a-button>
              <a-button style="margin-left: 8px" @click="resetSearch">重置</a-button>
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
      
      <a-row style="margin-top: 16px">
        <a-col :span="24">
          <a-button type="primary" @click="showAddModal">
            <template #icon><PlusOutlined /></template>
            添加主机
          </a-button>
        </a-col>
      </a-row>
      
      <a-table
        style="margin-top: 16px"
        :columns="columns"
        :data-source="dataSource"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        rowKey="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </a-tag>
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a @click="showEditModal(record)">编辑</a>
              <a-divider type="vertical" />
              <a @click="showDetailModal(record)">详情</a>
              <a-divider type="vertical" />
              <a-popconfirm
                title="确定要删除此主机吗?"
                ok-text="确定"
                cancel-text="取消"
                @confirm="handleDelete(record)"
              >
                <a class="danger-text">删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
      
      <!-- 添加/编辑模态框 -->
      <a-modal
        :title="modalTitle"
        :visible="modalVisible"
        :confirm-loading="modalLoading"
        @ok="handleModalOk"
        @cancel="handleModalCancel"
      >
        <a-form :model="formData" :rules="rules" ref="formRef" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
          <a-form-item label="主机编号" name="hostId">
            <a-input v-model:value="formData.hostId" placeholder="请输入主机编号" />
          </a-form-item>
          <a-form-item label="主机名称" name="name">
            <a-input v-model:value="formData.name" placeholder="请输入主机名称" />
          </a-form-item>
          <a-form-item label="IP地址" name="ipAddress">
            <a-input v-model:value="formData.ipAddress" placeholder="请输入IP地址" />
          </a-form-item>
          <a-form-item label="状态" name="status">
            <a-select v-model:value="formData.status" placeholder="请选择状态">
              <a-select-option value="online">在线</a-select-option>
              <a-select-option value="offline">离线</a-select-option>
              <a-select-option value="maintenance">维护中</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="备注" name="remark">
            <a-textarea v-model:value="formData.remark" placeholder="请输入备注" :rows="4" />
          </a-form-item>
        </a-form>
      </a-modal>
      
      <!-- 详情模态框 -->
      <a-modal
        title="主机详情"
        :visible="detailModalVisible"
        :footer="null"
        @cancel="handleDetailModalCancel"
      >
        <a-descriptions bordered>
          <a-descriptions-item label="主机编号" span="3">{{ detailData.hostId }}</a-descriptions-item>
          <a-descriptions-item label="主机名称" span="3">{{ detailData.name }}</a-descriptions-item>
          <a-descriptions-item label="IP地址" span="3">{{ detailData.ipAddress }}</a-descriptions-item>
          <a-descriptions-item label="状态" span="3">
            <a-tag :color="getStatusColor(detailData.status)">
              {{ getStatusText(detailData.status) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="创建时间" span="3">{{ detailData.createdAt }}</a-descriptions-item>
          <a-descriptions-item label="更新时间" span="3">{{ detailData.updatedAt }}</a-descriptions-item>
          <a-descriptions-item label="备注" span="3">{{ detailData.remark || '无' }}</a-descriptions-item>
        </a-descriptions>
      </a-modal>
    </a-card>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import api from '../../../utils/api';

// 状态映射函数：前端状态 -> 后端状态
const frontToBackStatus = (status) => {
  const statusMap = {
    online: 'active',
    offline: 'inactive',
    maintenance: 'maintenance'
  };
  return statusMap[status] || status;
};

// 状态映射函数：后端状态 -> 前端状态
const backToFrontStatus = (status) => {
  const statusMap = {
    active: 'online',
    inactive: 'offline',
    maintenance: 'maintenance'
  };
  return statusMap[status] || status;
};

export default {
  name: 'SmartHost',
  components: {
    PlusOutlined
  },
  setup() {
    // 搜索表单
    const searchForm = reactive({
      hostId: '',
      status: undefined
    });

    // 表格数据
    const loading = ref(false);
    const dataSource = ref([]);
    const pagination = reactive({
      current: 1,
      pageSize: 10,
      total: 0,
      showSizeChanger: true,
      showTotal: (total) => `共 ${total} 条`
    });

    // 表格列定义
    const columns = [
      {
        title: '主机编号',
        dataIndex: 'hostId',
        key: 'hostId',
        sorter: true
      },
      {
        title: '主机名称',
        dataIndex: 'name',
        key: 'name'
      },
      {
        title: 'IP地址',
        dataIndex: 'ipAddress',
        key: 'ipAddress'
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        filters: [
          { text: '在线', value: 'online' },
          { text: '离线', value: 'offline' },
          { text: '维护中', value: 'maintenance' }
        ]
      },
      {
        title: '创建时间',
        dataIndex: 'createdAt',
        key: 'createdAt',
        sorter: true
      },
      {
        title: '操作',
        key: 'action'
      }
    ];

    // 模态框相关
    const modalVisible = ref(false);
    const modalLoading = ref(false);
    const modalTitle = ref('添加主机');
    const formRef = ref(null);
    const formData = reactive({
      id: null,
      hostId: '',
      name: '',
      ipAddress: '',
      status: 'offline',
      remark: ''
    });
    const rules = {
      hostId: [{ required: true, message: '请输入主机编号', trigger: 'blur' }],
      name: [{ required: true, message: '请输入主机名称', trigger: 'blur' }],
      ipAddress: [{ required: true, message: '请输入IP地址', trigger: 'blur' }],
      status: [{ required: true, message: '请选择状态', trigger: 'change' }]
    };

    // 详情模态框
    const detailModalVisible = ref(false);
    const detailData = reactive({});



    // 获取数据
    const fetchData = async () => {
      loading.value = true;
      try {
        const params = {
          page: pagination.current,
          pageSize: pagination.pageSize,
          hostId: searchForm.hostId || undefined,
          status: searchForm.status ? frontToBackStatus(searchForm.status) : undefined
        };
        
        const response = await api.government.smartHosts.getList(params);
        
        if (response.success) {
          // 将后端返回的状态转换为前端使用的状态
          dataSource.value = response.data.map(item => ({
            ...item,
            status: backToFrontStatus(item.status)
          }));
          pagination.total = response.total;
        } else {
          throw new Error(response.message || '获取数据失败');
        }
      } catch (error) {
        console.error('获取智能主机数据失败:', error);
        dataSource.value = [];
        pagination.total = 0;
        // 可以在这里添加错误提示
      } finally {
        loading.value = false;
      }
    };

    // 状态相关
    const getStatusColor = (status) => {
      const statusMap = {
        online: 'green',
        offline: 'gray',
        maintenance: 'orange'
      };
      return statusMap[status] || 'default';
    };

    const getStatusText = (status) => {
      const statusMap = {
        online: '在线',
        offline: '离线',
        maintenance: '维护中'
      };
      return statusMap[status] || '未知';
    };

    // 搜索相关
    const handleSearch = () => {
      pagination.current = 1;
      fetchData();
    };

    const resetSearch = () => {
      searchForm.hostId = '';
      searchForm.status = undefined;
      handleSearch();
    };

    // 表格相关
    const handleTableChange = (pag, filters, sorter) => {
      pagination.current = pag.current;
      pagination.pageSize = pag.pageSize;
      fetchData();
    };

    // 模态框相关
    const showAddModal = () => {
      modalTitle.value = '添加主机';
      formData.id = null;
      formData.hostId = '';
      formData.name = '';
      formData.ipAddress = '';
      formData.status = 'offline';
      formData.remark = '';
      modalVisible.value = true;
    };

    const showEditModal = (record) => {
      modalTitle.value = '编辑主机';
      formData.id = record.id;
      formData.hostId = record.hostId;
      formData.name = record.name;
      formData.ipAddress = record.ipAddress;
      formData.status = record.status;
      formData.remark = record.remark;
      modalVisible.value = true;
    };

    const handleModalOk = async () => {
      formRef.value.validate().then(async () => {
        modalLoading.value = true;
        try {
          // 准备请求数据，将前端状态转换为后端状态
          const requestData = {
            ...formData,
            status: frontToBackStatus(formData.status)
          };
          
          let response;
          if (formData.id) {
            // 编辑
            response = await api.government.smartHosts.update(formData.id, requestData);
          } else {
            // 添加
            response = await api.government.smartHosts.create(requestData);
          }
          
          if (!response.success) {
            throw new Error(response.message || '操作失败');
          }
          
          modalVisible.value = false;
          fetchData();
          // 可以在这里添加成功提示
        } catch (error) {
          console.error('操作失败:', error);
          // 可以在这里添加错误提示
        } finally {
          modalLoading.value = false;
        }
      });
    };

    const handleModalCancel = () => {
      modalVisible.value = false;
    };

    // 详情相关
    const showDetailModal = (record) => {
      Object.assign(detailData, record);
      detailModalVisible.value = true;
    };

    const handleDetailModalCancel = () => {
      detailModalVisible.value = false;
    };

    // 删除
    const handleDelete = async (record) => {
      loading.value = true;
      try {
        const response = await api.government.smartHosts.delete(record.id);
        
        if (!response.success) {
          throw new Error(response.message || '删除失败');
        }
        
        fetchData();
        // 可以在这里添加成功提示
      } catch (error) {
        console.error('删除智能主机失败:', error);
        // 可以在这里添加错误提示
      } finally {
        loading.value = false;
      }
    };

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

    return {
      searchForm,
      loading,
      dataSource,
      pagination,
      columns,
      modalVisible,
      modalLoading,
      modalTitle,
      formRef,
      formData,
      rules,
      detailModalVisible,
      detailData,
      getStatusColor,
      getStatusText,
      handleSearch,
      resetSearch,
      handleTableChange,
      showAddModal,
      showEditModal,
      handleModalOk,
      handleModalCancel,
      showDetailModal,
      handleDetailModalCancel,
      handleDelete
    };
  }
};
</script>

<style scoped>
.smart-host-container {
  padding: 16px;
}
.danger-text {
  color: #ff4d4f;
}
</style>