<template>
  <div class="container">
    <search-table
      :form-model="formModel"
      :form-items="formItems"
      :data="tableData"
      :columns="columns"
      :loading="loading"
      :pagination="pagination"
      title="办公PC管理"
      search-button-text="查询"
      reset-button-text="重置"
      @update:form-model="handleFormModelUpdate"
      @search="handleSearch"
      @reset="handleReset"
      @page-change="handlePageChange"
      @refresh="handleRefresh"
    >
      <template #toolbar-left>
        <a-button type="primary" @click="handleAdd">
          <template #icon>
            <icon-plus />
          </template>
          新增办公PC
        </a-button>
      </template>
      
      <!-- ID -->
      <template #id="{ record }">
        {{ record.id }}
      </template>
      
      <!-- 远程访问 -->
      <template #remote_access="{ record }">
        <a-tag :color="record.remote_access ? 'green' : 'gray'">
          {{ record.remote_access ? '已开启' : '未开启' }}
        </a-tag>
      </template>
      
      <!-- Agent配置 -->
      <template #agent_config="{ record }">
        <a-tag :color="record.agent_config ? 'green' : 'gray'">
          {{ record.agent_config ? '已配置' : '未配置' }}
        </a-tag>
      </template>
      
      <!-- CPU -->
      <template #cpu="{ record }">
        <div class="resource-display">
          <div class="resource-info">
            <span class="resource-label">CPU</span>
            <span class="resource-value">{{ record.cpu_info?.value || 0 }}%</span>
          </div>
          <a-progress 
            :percent="(record.cpu_info?.value || 0) / 100" 
            :color="getProgressColor(record.cpu_info?.value || 0)"
            size="small"
            :show-text="false"
          />
        </div>
      </template>
      
      <!-- 内存 -->
      <template #memory="{ record }">
        <div class="resource-display">
          <div class="resource-info">
            <span class="resource-label">内存</span>
            <span class="resource-value">{{ record.memory_info?.value || 0 }}%</span>
          </div>
          <a-progress 
            :percent="(record.memory_info?.value || 0) / 100" 
            :color="getProgressColor(record.memory_info?.value || 0)"
            size="small"
            :show-text="false"
          />
        </div>
      </template>
      
      <!-- 硬盘 -->
      <template #disk="{ record }">
        <div class="resource-display">
          <div class="resource-info">
            <span class="resource-label">硬盘</span>
            <span class="resource-value">{{ record.disk_info?.value || 0 }}%</span>
          </div>
          <a-progress 
            :percent="(record.disk_info?.value || 0) / 100" 
            :color="getProgressColor(record.disk_info?.value || 0)"
            size="small"
            :show-text="false"
          />
        </div>
      </template>
      
      <!-- 状态 -->
      <template #status="{ record }">
        <a-tag :color="getStatusColor(record.status)">
          {{ getStatusText(record.status) }}
        </a-tag>
      </template>
      
      <!-- 操作栏 -->
      <template #actions="{ record }">
        <a-space>
          <a-button
            v-if="!record.agent_config"
            type="outline"
            size="small"
            @click="handleQuickConfig(record)"
          >
            <template #icon>
              <icon-settings />
            </template>
            快捷配置
          </a-button>
          <a-dropdown trigger="hover">
            <a-button type="primary" size="small">
              管理
              <icon-down />
            </a-button>
            <template #content>
              <a-doption @click="handleRestart(record)">
                <template #icon>
                  <icon-refresh />
                </template>
                重启
              </a-doption>
              <a-doption @click="handleDetail(record)">
                <template #icon>
                  <icon-eye />
                </template>
                详情
              </a-doption>
              <a-doption @click="handleEdit(record)">
                <template #icon>
                  <icon-edit />
                </template>
                编辑
              </a-doption>
              <a-doption @click="handleRemoteControl(record)">
                <template #icon>
                  <icon-desktop />
                </template>
                远程控制
              </a-doption>
              <a-doption @click="handleDelete(record)" style="color: rgb(var(--danger-6))">
                <template #icon>
                  <icon-delete />
                </template>
                删除
              </a-doption>
            </template>
          </a-dropdown>
        </a-space>
      </template>
    </search-table>

    <!-- 新增/编辑对话框 -->
    <FormDialog
      v-model:visible="dialogVisible"
      :record="currentRecord"
      @success="handleFormSuccess"
    />

    <!-- 快捷配置对话框 -->
    <QuickConfigDialog
      v-model:visible="quickConfigVisible"
      :record="currentRecord"
      @success="handleFormSuccess"
    />

  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { Message, Modal } from '@arco-design/web-vue'
import { 
  IconPlus, 
  IconDown,
  IconEdit,
  IconDesktop,
  IconDelete,
  IconRefresh,
  IconEye,
  IconSettings
} from '@arco-design/web-vue/es/icon'
import type { FormItem } from '@/components/search-form/types'
import SearchTable from '@/components/search-table/index.vue'
import { searchFormConfig } from './config/search-form'
import { columns as columnsConfig } from './config/columns'
import {
  fetchPCList,
  deletePC,
} from '@/api/ops/pc'
import FormDialog from './components/FormDialog.vue'
import QuickConfigDialog from './components/QuickConfigDialog.vue'
import Detail from './components/Detail.vue'

const router = useRouter()

// Mock 假数据
const mockPCData = [
  {
    id: 1,
    unique_id: 'PC-2024-0001',
    name: '开发PC-01',
    os: 'Windows 11',
    location: '数据中心A-1楼-办公区01',
    tags: '开发,前端',
    ip: '192.168.1.201',
    remote_access: true,
    agent_config: true,
    cpu_info: { value: 35, total: '8核', used: '2.8核' },
    memory_info: { value: 52, total: '16GB', used: '8.3GB' },
    disk_info: { value: 65, total: '512GB', used: '333GB' },
    status: 'online',
  },
  {
    id: 2,
    unique_id: 'PC-2024-0002',
    name: '测试PC-01',
    os: 'Windows 10',
    location: '数据中心A-1楼-办公区02',
    tags: '测试,自动化',
    ip: '192.168.1.202',
    remote_access: true,
    agent_config: true,
    cpu_info: { value: 28, total: '4核', used: '1.1核' },
    memory_info: { value: 45, total: '8GB', used: '3.6GB' },
    disk_info: { value: 72, total: '256GB', used: '184GB' },
    status: 'online',
  },
  {
    id: 3,
    unique_id: 'PC-2024-0003',
    name: '设计PC-01',
    os: 'macOS Sonoma',
    location: '数据中心A-2楼-设计室01',
    tags: '设计,创意',
    ip: '192.168.1.203',
    remote_access: false,
    agent_config: false,
    cpu_info: { value: 0, total: '12核', used: '0核' },
    memory_info: { value: 0, total: '32GB', used: '0GB' },
    disk_info: { value: 0, total: '1TB', used: '0GB' },
    status: 'offline',
  },
  {
    id: 4,
    unique_id: 'PC-2024-0004',
    name: '运维PC-01',
    os: 'Windows 11',
    location: '数据中心B-1楼-运维室01',
    tags: '运维,监控',
    ip: '192.168.2.201',
    remote_access: true,
    agent_config: true,
    cpu_info: { value: 42, total: '6核', used: '2.5核' },
    memory_info: { value: 58, total: '16GB', used: '9.3GB' },
    disk_info: { value: 68, total: '512GB', used: '348GB' },
    status: 'online',
  },
  {
    id: 5,
    unique_id: 'PC-2024-0005',
    name: '财务PC-01',
    os: 'Windows 10',
    location: '数据中心B-2楼-财务室01',
    tags: '财务,报表',
    ip: '192.168.2.202',
    remote_access: true,
    agent_config: true,
    cpu_info: { value: 22, total: '4核', used: '0.9核' },
    memory_info: { value: 38, total: '8GB', used: '3.0GB' },
    disk_info: { value: 55, total: '256GB', used: '141GB' },
    status: 'online',
  },
  {
    id: 6,
    unique_id: 'PC-2024-0006',
    name: '备用PC-01',
    os: 'Windows 11',
    location: '数据中心A-1楼-备用室01',
    tags: '备用,测试',
    ip: '192.168.1.204',
    remote_access: false,
    agent_config: false,
    cpu_info: { value: 0, total: '4核', used: '0核' },
    memory_info: { value: 0, total: '8GB', used: '0GB' },
    disk_info: { value: 0, total: '256GB', used: '0GB' },
    status: 'maintenance',
  },
  {
    id: 7,
    unique_id: 'PC-2024-0007',
    name: '开发PC-02',
    os: 'Ubuntu 22.04',
    location: '数据中心A-1楼-办公区03',
    tags: '开发,后端',
    ip: '192.168.1.205',
    remote_access: true,
    agent_config: true,
    cpu_info: { value: 48, total: '8核', used: '3.8核' },
    memory_info: { value: 62, total: '16GB', used: '9.9GB' },
    disk_info: { value: 58, total: '512GB', used: '297GB' },
    status: 'online',
  },
  {
    id: 8,
    unique_id: 'PC-2024-0008',
    name: '产品PC-01',
    os: 'Windows 11',
    location: '数据中心B-1楼-产品室01',
    tags: '产品,设计',
    ip: '192.168.2.203',
    remote_access: true,
    agent_config: true,
    cpu_info: { value: 32, total: '6核', used: '1.9核' },
    memory_info: { value: 45, total: '16GB', used: '7.2GB' },
    disk_info: { value: 62, total: '512GB', used: '317GB' },
    status: 'online',
  },
]

// 状态管理
const loading = ref(false)
const tableData = ref<any[]>([])
const formModel = ref({
  keyword: '',
  datacenter_id: undefined,
  rack_id: undefined,
  status: undefined,
})

const dialogVisible = ref(false)
const quickConfigVisible = ref(false)
const currentRecord = ref<any>(null)

const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
})

// 表单项配置
const formItems = computed<FormItem[]>(() => searchFormConfig)

// 表格列配置
const columns = computed(() => columnsConfig)

// 获取状态颜色
const getStatusColor = (status?: string) => {
  const colorMap: Record<string, string> = {
    online: 'green',
    offline: 'red',
    maintenance: 'orange',
    retired: 'gray',
  }
  return colorMap[status || ''] || 'gray'
}

// 获取状态文本
const getStatusText = (status?: string) => {
  const textMap: Record<string, string> = {
    online: '在线',
    offline: '离线',
    maintenance: '维护中',
    retired: '已退役',
  }
  return textMap[status || ''] || '-'
}

// 获取进度条颜色
const getProgressColor = (value: number) => {
  if (value >= 90) return '#F53F3F' // 红色
  if (value >= 70) return '#FF7D00' // 橙色
  if (value >= 50) return '#FFD00B' // 黄色
  return '#00B42A' // 绿色
}

// 获取PC列表（使用 Mock 数据）
const fetchPCs = async () => {
  loading.value = true
  
  try {
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 使用 Mock 数据
    tableData.value = mockPCData
    pagination.total = mockPCData.length
    
    // 如果有搜索条件，进行过滤
    if (formModel.value.keyword || formModel.value.status) {
      let filteredData = [...mockPCData]
      
      if (formModel.value.keyword) {
        const keyword = formModel.value.keyword.toLowerCase()
        filteredData = filteredData.filter(item => 
          item.name.toLowerCase().includes(keyword) ||
          item.unique_id.toLowerCase().includes(keyword) ||
          item.ip.toLowerCase().includes(keyword)
        )
      }
      
      if (formModel.value.status) {
        filteredData = filteredData.filter(item => item.status === formModel.value.status)
      }
      
      tableData.value = filteredData
      pagination.total = filteredData.length
    }
  } catch (error) {
    console.error('获取PC列表失败:', error)
    Message.error('获取PC列表失败')
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchPCs()
}

// 处理表单模型更新
const handleFormModelUpdate = (value: any) => {
  formModel.value = value
}

// 重置
const handleReset = () => {
  formModel.value = {
    keyword: '',
    datacenter_id: undefined,
    rack_id: undefined,
    status: undefined,
  }
  pagination.current = 1
  fetchPCs()
}

// 分页变化
const handlePageChange = (current: number) => {
  pagination.current = current
  fetchPCs()
}

// 刷新
const handleRefresh = () => {
  fetchPCs()
  Message.success('数据已刷新')
}

// 新增PC
const handleAdd = () => {
  currentRecord.value = null
  dialogVisible.value = true
}

// 快捷配置
const handleQuickConfig = (record: any) => {
  currentRecord.value = record
  quickConfigVisible.value = true
}

// 编辑PC
const handleEdit = (record: any) => {
  currentRecord.value = record
  dialogVisible.value = true
}

// 详情 - 在当前窗口打开
const handleDetail = (record: any) => {
  router.push({
    path: '/dc/detail',
    query: {
      id: record.id,
      name: record.name,
      ip: record.ip,
      status: record.status,
    },
  })
}

// 重启
const handleRestart = (record: any) => {
  Modal.confirm({
    title: '确认重启',
    content: `确认重启办公PC ${record.name} 吗？`,
    onOk: () => {
      Message.info('正在发送重启指令...')
    },
  })
}

// 远程控制 - 在新窗口打开
const handleRemoteControl = (record: any) => {
  const url = router.resolve({
    path: '/dc/remote',
    query: {
      id: record.id,
      name: record.name,
      ip: record.ip,
      status: record.status,
    },
  }).href
  window.open(url, '_blank')
}

// 表单提交成功
const handleFormSuccess = () => {
  fetchPCs()
}

// 删除PC
const handleDelete = async (record: any) => {
  try {
    Modal.confirm({
      title: '确认删除',
      content: `确认删除PC ${record.name} 吗？`,
      onOk: async () => {
        // Mock 删除操作
        const index = mockPCData.findIndex(item => item.id === record.id)
        if (index > -1) {
          mockPCData.splice(index, 1)
          Message.success('删除成功')
          fetchPCs()
        } else {
          Message.error('删除失败')
        }
      },
    })
  } catch (error) {
    console.error('删除PC失败:', error)
  }
}

// 初始化加载数据
fetchPCs()
</script>

<script lang="ts">
export default {
  name: 'DataCenterPC',
}
</script>

<style scoped lang="less">
.container {
  margin-top: 20px;
}

.resource-display {
  display: flex;
  flex-direction: column;
  gap: 4px;
  padding: 4px 0;
  
  .resource-info {
    display: flex;
    align-items: center;
    justify-content: space-between;
    > div {
      display: inline-block;
    }
    .resource-value {
      font-size: 12px;
      font-weight: 500;
      color: rgb(var(--text-1));
    }
  }
  
  :deep(.arco-progress) {
    margin: 0;
    
    .arco-progress-bar-bg {
      border-radius: 2px;
    }
    
    .arco-progress-bar {
      border-radius: 2px;
      transition: all 0.3s ease;
    }
  }
}
</style>
