<template>
  <div class="vm-list-container">
    <div class="filter-section">
      <el-input 
        v-model="searchKey" 
        placeholder="输入关键字搜索" 
        style="width: 200px; margin-right: 10px;"
        clearable
        @input="handleSearch"
      />
      <el-button type="primary" @click="handleSearch">
        <el-icon><search /></el-icon>搜索
      </el-button>
      <el-button @click="resetSearch">
        <el-icon><refresh /></el-icon>重置
      </el-button>
      <el-button type="success" @click="showAddVmDialog">
        <el-icon><plus /></el-icon>新增虚拟机
      </el-button>
    </div>
    
    <el-table 
      v-loading="loading" 
      :data="vmList" 
      style="width: 100%"
      border
    >
      <el-table-column prop="id" label="ID" width="100" />
      <el-table-column prop="user_id" label="用户ID" width="100" />
      <el-table-column label="创建时间" width="180">
        <template #default="scope">
          {{ scope.row.created_at }}
        </template>
      </el-table-column>
      <el-table-column label="到期时间" width="180">
        <template #default="scope">
          {{ scope.row.become_time }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.state == 0 || scope.row.state == 1
              ? 'info'
              : scope.row.state == 2
                ? 'success'
                : scope.row.state == 4 || scope.row.state == 5 || scope.row.state == 6
                  ? 'warning'
                  : 'danger'
            ">{{
              scope.row.state == 0
                ? "未支付"
                : scope.row.state == 1
                  ? "未创建"
                  : scope.row.state == 2
                    ? "已启动"
                    : scope.row.state == 3
                      ? "已关机"
                      : scope.row.state == 4
                        ? "重装中"
                        : scope.row.state == 5
                          ? "创建快照中"
                          : scope.row.state == 6
                            ? "恢复快照中"
                            : "未知状态"
            }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300" fixed="right">
        <template #default="scope">
          <el-button 
            type="primary" 
            link 
            size="small" 
            @click="handleManage(scope.row)"
          >
            <el-icon><menu /></el-icon>管理
          </el-button>
          <!-- <el-button 
            type="primary" 
            link 
            size="small" 
            @click="handleStart(scope.row)"
            :disabled="scope.row.state == 2 || scope.row.state == 0 || scope.row.state == 1 || scope.row.state == 4 || scope.row.state == 5 || scope.row.state == 6"
          >
            开机
          </el-button> -->
          <!-- <el-button 
            type="primary" 
            link 
            size="small" 
            @click="handleStop(scope.row)"
            :disabled="scope.row.state != 2"
          >
            关机
          </el-button> -->
          <!-- <el-dropdown trigger="click" @command="(command) => handleCommand(command, scope.row)" style="transform: translateY(3px) translateX(10px);">
            <el-button 
              type="primary" 
              link 
              size="small"
            >
              更多
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                 <el-dropdown-item :disabled="scope.row.state != 2" command="restart">重启</el-dropdown-item>
                <el-dropdown-item divided :disabled="scope.row.state == 0 || scope.row.state == 1 || scope.row.state == 4 || scope.row.state == 5 || scope.row.state == 6" command="reinstall">重装系统</el-dropdown-item>
                <el-dropdown-item :disabled="scope.row.state == 0 || scope.row.state == 1 || scope.row.state == 4 || scope.row.state == 5 || scope.row.state == 6" command="snapshot">快照管理</el-dropdown-item>
                <el-dropdown-item :disabled="scope.row.state == 0 || scope.row.state == 1 || scope.row.state == 4 || scope.row.state == 5 || scope.row.state == 6" command="enterRescue">进入救援系统</el-dropdown-item>
                <el-dropdown-item :disabled="scope.row.state == 0 || scope.row.state == 1 || scope.row.state == 4 || scope.row.state == 5 || scope.row.state == 6" command="exitRescue">退出救援系统</el-dropdown-item>
                <el-dropdown-item divided :disabled="scope.row.state == 0 || scope.row.state == 1" command="console">虚拟机控制台</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown> -->
        </template>
      </el-table-column>
    </el-table>
    
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增虚拟机对话框 -->
    <el-dialog
      v-model="addVmDialogVisible"
      title="新增虚拟机"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="addVmFormRef"
        :model="addVmForm"
        :rules="addVmRules"
        label-width="120px"
      >
        <el-form-item label="用户ID" prop="user_id">
          <el-input
            v-model="addVmForm.user_id"
            placeholder="请输入用户ID"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="套餐" prop="plan_id">
          <el-select
            v-model="addVmForm.plan_id"
            placeholder="请选择套餐"
            style="width: 100%"
            clearable
            :loading="planLoading"
            @focus="fetchPlanList"
          >
            <el-option
              v-for="plan in planList"
              :key="plan.id"
              :label="plan.name"
              :value="plan.plan_id"
            >
              <span style="float: left">{{ plan.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">
                {{ plan.price }}元/月
              </span>
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="额外数据卷大小" prop="volume_size">
          <el-input-number
            v-model="addVmForm.volume_size"
            :min="0"
            :max="10000"
            placeholder="请输入额外数据卷大小(GB)"
            style="width: 100%"
            controls-position="right"
          />
        </el-form-item>
        
        <el-form-item label="购买时间(月)" prop="pay_months">
          <el-input-number
            v-model="addVmForm.pay_months"
            :min="1"
            :max="120"
            placeholder="请输入购买月数"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="支付类型" prop="pay_type">
          <el-select
            v-model="addVmForm.pay_type"
            placeholder="请选择支付类型"
            style="width: 100%"
            clearable
          >
            <!-- <el-option label="支付宝" value="alipay" />
            <el-option label="微信支付" value="wechat" />
            <el-option label="银行卡" value="bank" /> -->
            <el-option label="余额" value="0" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="镜像" prop="image_id">
          <el-select
            v-model="addVmForm.image_id"
            placeholder="请选择镜像"
            style="width: 100%"
            clearable
            :loading="mirrorLoading"
            @focus="fetchMirrorList"
          >
            <el-option
              v-for="mirror in mirrorList"
              :key="mirror.id"
              :label="mirror.name"
              :value="mirror.id"
            >
              <span style="float: left">{{ mirror.name }}</span>
<!--              <span style="float: right; color: #8492a6; font-size: 13px">-->
<!--                {{ mirror.size }}MB-->
<!--              </span>-->
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="价格" prop="price">
          <el-input-number
            v-model="addVmForm.price"
            :min="0"
            :max="999999"
            :precision="2"
            placeholder="请输入价格"
            style="width: 100%"
            controls-position="right"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelAddVm">取消</el-button>
          <el-button type="primary" @click="confirmAddVm" :loading="addVmLoading">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, defineProps, watch } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { 
  Search, Refresh, Menu, VideoPlay, VideoPause, RefreshRight, ArrowDown, Plus
} from '@element-plus/icons-vue';
import { 
  getContainer, 
  startInstance, 
  stopInstance, 
  restartInstance,
  getInstanceList,
  reinstallI,
  rescueInstance,
  exitRescueInstance,
  addInstance,
  getServerPlan
} from '@/utils/acs/server';
import { getMirrorList } from '@/utils/acs/mirror';

const props = defineProps({
  ID: {
    type: String,
    required: true
  }
});

const router = useRouter();
const loading = ref(false);
const vmList = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const searchKey = ref('');

// 新增虚拟机相关状态
const addVmDialogVisible = ref(false);
const addVmLoading = ref(false);
const addVmFormRef = ref(null);
const addVmForm = ref({
  user_id: '',
  plan_id: '',
  volume_size: null,
  pay_months: null,
  pay_type: '',
  image_id: '',
  price: null
});

// 套餐和镜像数据
const planList = ref([]);
const mirrorList = ref([]);
const planLoading = ref(false);
const mirrorLoading = ref(false);

// 表单验证规则
const addVmRules = ref({
  user_id: [
    { required: true, message: '请输入用户ID', trigger: 'blur' }
  ],
  plan_id: [
    { required: true, message: '请选择套餐', trigger: 'change' }
  ],
  pay_months: [
    { required: true, message: '请输入购买月数', trigger: 'blur' }
  ],
  pay_type: [
    { required: true, message: '请选择支付类型', trigger: 'change' }
  ],
  image_id: [
    { required: true, message: '请选择镜像', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' }
  ]
});

// 获取虚拟机列表
const fetchVmList = async () => {
  loading.value = true;
  try {
    const response = await getInstanceList({
      server_id: props.ID,
      page: currentPage.value,
      count: pageSize.value,
      key: searchKey.value,
      user_id: ''
    });
    console.log("获取虚拟机列表：",response);
    
    if (response && response.data && response.data.code === 200) {
      vmList.value = response.data.data || [];
      total.value = response.data.count || 0;
    } else {
      ElMessage.error('获取虚拟机列表失败');
    }
  } catch (error) {
    console.error('获取虚拟机列表出错:', error);
    ElMessage.error('获取虚拟机列表出错');
  } finally {
    loading.value = false;
  }
};

function Formater(row){
  return row.hostname || '未设置'
}

// 获取状态类型
const getStatusType = (state) => {
  console.log("获取状态类型：",state)
  switch (state) {
    case '0':
      return 'success';
    case '1':
      return 'danger';
    case '2':
      return 'warning';
    default:
      return 'info';
  }
};

// 获取状态文本
const getStatusText = (state) => {
  switch (state) {
    case '0':
      return '运行中';
    case '1':
      return '已停止';
    case '2':
      return '已暂停';
    case '3':
      return '创建中';
    case '4':
      return '错误';
    default:
      return '未知';
  }
};

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchVmList();
};

// 重置搜索
const resetSearch = () => {
  searchKey.value = '';
  currentPage.value = 1;
  fetchVmList();
};

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchVmList();
};

// 处理每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
  fetchVmList();
};

// 管理虚拟机
const handleManage = (row) => {
  // 标记这是从列表页面进入详情页面，不是返回操作
  sessionStorage.setItem('vmDetailFrom', 'list');
  sessionStorage.setItem('vmDetailTimestamp', Date.now().toString());
  router.push(`/servers/vm?instance_id=${row.id}`);
};

// 启动虚拟机
const handleStart = async (row) => {
  try {
    const res = await startInstance(row.instance_id);
    if (res && res.data && res.data.code === 200) {
      ElMessage.success('启动指令已发送');
      setTimeout(() => {
        fetchVmList();
      }, 2000);
    } else {
      ElMessage.error('启动失败: ' + (res.data.message || '未知错误'));
    }
  } catch (error) {
    console.error('启动虚拟机出错:', error);
    ElMessage.error('启动虚拟机出错');
  }
};

// 停止虚拟机
const handleStop = async (row) => {
  try {
    ElMessageBox.confirm('确定要停止该虚拟机吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      const res = await stopInstance(row.instance_id);
      if (res && res.data && res.data.code === 200) {
        ElMessage.success('停止指令已发送');
        setTimeout(() => {
          fetchVmList();
        }, 2000);
      } else {
        ElMessage.error('停止失败: ' + (res.data.message || '未知错误'));
      }
    }).catch(() => {});
  } catch (error) {
    console.error('停止虚拟机出错:', error);
    ElMessage.error('停止虚拟机出错');
  }
};

// 重启虚拟机
const handleRestart = async (row) => {
  try {
    ElMessageBox.confirm('确定要重启该虚拟机吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      const res = await restartInstance(row.instance_id);
      if (res && res.data && res.data.code === 200) {
        ElMessage.success('重启指令已发送');
        setTimeout(() => {
          fetchVmList();
        }, 2000);
      } else {
        ElMessage.error('重启失败: ' + (res.data.message || '未知错误'));
      }
    }).catch(() => {});
  } catch (error) {
    console.error('重启虚拟机出错:', error);
    ElMessage.error('重启虚拟机出错');
  }
};

// 重装系统
const handleReinstall = async (row) => {
  try {
    ElMessageBox.confirm('重装系统将清除所有数据，确定要继续吗?', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      router.push(`/servers/reinstall?instance_id=${row.instance_id}`);
    }).catch(() => {});
  } catch (error) {
    console.error('重装系统出错:', error);
    ElMessage.error('重装系统出错');
  }
};

// 快照管理
const handleSnapshot = (row) => {
  router.push(`/servers/snapshots?instance_id=${row.instance_id}`);
};

// 进入救援系统
const handleEnterRescue = async (row) => {
  try {
    ElMessageBox.confirm('确定要进入救援系统吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      const res = await rescueInstance(row.instance_id);
      if (res && res.data && res.data.code === 200) {
        ElMessage.success('已进入救援系统');
        setTimeout(() => {
          fetchVmList();
        }, 2000);
      } else {
        ElMessage.error('操作失败: ' + (res.data.message || '未知错误'));
      }
    }).catch(() => {});
  } catch (error) {
    console.error('进入救援系统出错:', error);
    ElMessage.error('进入救援系统出错');
  }
};

// 退出救援系统
const handleExitRescue = async (row) => {
  try {
    ElMessageBox.confirm('确定要退出救援系统吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      const res = await exitRescueInstance(row.instance_id);
      if (res && res.data && res.data.code === 200) {
        ElMessage.success('已退出救援系统');
        setTimeout(() => {
          fetchVmList();
        }, 2000);
      } else {
        ElMessage.error('操作失败: ' + (res.data.message || '未知错误'));
      }
    }).catch(() => {});
  } catch (error) {
    console.error('退出救援系统出错:', error);
    ElMessage.error('退出救援系统出错');
  }
};

// 打开虚拟机控制台
const handleConsole = (row) => {
  window.open(`/console?instance_id=${row.instance_id}`, '_blank');
};

// 处理下拉菜单命令
const handleCommand = (command, row) => {
  switch (command) {
    case 'start':
      handleStart(row);
      break;
    case 'stop':
      handleStop(row);
      break;
    case 'restart':
      handleRestart(row);
      break;
    case 'reinstall':
      handleReinstall(row);
      break;
    case 'snapshot':
      handleSnapshot(row);
      break;
    case 'enterRescue':
      handleEnterRescue(row);
      break;
    case 'exitRescue':
      handleExitRescue(row);
      break;
    case 'console':
      handleConsole(row);
      break;
    default:
      break;
  }
};

// 监听ID变化
watch(() => props.ID, (newVal) => {
  if (newVal) {
    fetchVmList();
  }
});

// 获取套餐列表
const fetchPlanList = async () => {
  if (planList.value.length > 0) return; // 已加载过，不重复加载
  
  planLoading.value = true;
  try {
    const response = await getServerPlan({
      server_id: props.ID,
      count: 10
    });
    
    if (response && response.data && response.data.code === 200) {
      planList.value = response.data.data || [];
    } else {
      ElMessage.error('获取套餐列表失败');
    }
  } catch (error) {
    console.error('获取套餐列表出错:', error);
    ElMessage.error('获取套餐列表出错');
  } finally {
    planLoading.value = false;
  }
};

// 获取镜像列表
const fetchMirrorList = async () => {
  if (mirrorList.value.length > 0) return; // 已加载过，不重复加载
  
  mirrorLoading.value = true;
  try {
    const response = await getMirrorList(props.ID);
    
    if (response && response.data && response.data.code === 200) {
      mirrorList.value = response.data.data || [];
    } else {
      ElMessage.error('获取镜像列表失败');
    }
  } catch (error) {
    console.error('获取镜像列表出错:', error);
    ElMessage.error('获取镜像列表出错');
  } finally {
    mirrorLoading.value = false;
  }
};

// 显示新增虚拟机对话框
const showAddVmDialog = () => {
  addVmDialogVisible.value = true;
  // 重置表单
  addVmForm.value = {
    user_id: '',
    plan_id: '',
    volume_size: null,
    pay_months: null,
    pay_type: '',
    image_id: '',
    price: null
  };
  // 清除验证
  if (addVmFormRef.value) {
    addVmFormRef.value.clearValidate();
  }
  // 预加载数据
  fetchPlanList();
  fetchMirrorList();
};

// 取消新增虚拟机
const cancelAddVm = () => {
  addVmDialogVisible.value = false;
};

// 确认新增虚拟机
const confirmAddVm = async () => {
  if (!addVmFormRef.value) return;
  
  try {
    // 验证表单
    await addVmFormRef.value.validate();
    
    addVmLoading.value = true;
    
    // 准备API参数
    const apiParams = {
      user_id: addVmForm.value.user_id,
      plan_id: addVmForm.value.plan_id,
      volume_size: addVmForm.value.volume_size?.toString() || '',
      pay_months: addVmForm.value.pay_months?.toString() || '',
      pay_type: addVmForm.value.pay_type,
      image_id: addVmForm.value.image_id,
      price: addVmForm.value.price?.toString() || ''
    };
    
    console.log('新增虚拟机参数:', apiParams);
    
    // 调用API
    const response = await addInstance(apiParams);
    
    if (response && response.data && response.data.code === 200) {
      ElMessage.success('虚拟机创建成功');
      addVmDialogVisible.value = false;
      // 刷新列表
      fetchVmList();
    } else {
      ElMessage.error('创建失败: ' + (response.data?.message || '未知错误'));
    }
  } catch (error) {
    console.error('新增虚拟机出错:', error);
    if (error.message) {
      ElMessage.error('表单验证失败: ' + error.message);
    } else {
      ElMessage.error('新增虚拟机出错');
    }
  } finally {
    addVmLoading.value = false;
  }
};

onMounted(() => {
  if (props.ID) {
    fetchVmList();
  }
});
</script>

<style scoped>
.vm-list-container {
  padding: 10px 0;
}

.filter-section {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 添加下拉菜单样式 */
:deep(.el-dropdown-menu) {
  min-width: 120px;
}

:deep(.el-dropdown-menu__item) {
  padding: 8px 16px;
  font-size: 14px;
  line-height: 1.5;
}

:deep(.el-dropdown-menu__item--divided) {
  margin-top: 6px;
  border-top: 1px solid #ebeef5;
  margin-bottom: 6px;
}

:deep(.el-dropdown-menu__item--divided:before) {
  height: 6px;
  margin-top: -6px;
}
</style> 