<template>
  <div class="test-container">
    <h1>VtkStepper 组件测试页面</h1>

    <!-- 基础测试 -->
    <div class="test-section">
      <v-card class="mb-4">
        <v-card-title>基础步骤条</v-card-title>
        <v-form ref="form" v-model="valid" class="px-4">
          <vtk-stepper :el="el" list="基础信息基础信息,执行属性,时间属性,构建" class="mx-auto pt-8" style="max-width: 1200px">
            <template slot="1" v-if="el == 1">
              <v-card>
                <div class=" d-flex">
                  <span class="text-red">{{ $filters.mobile('13812345678') }}</span>
                  <v-spacer />
                  <vtk-search styles="width:320px">
                    <vtk-select v-model="entity.scheduleRoutes" placeholder="请选择调度路由策略"
                      list="LAST:LAST (取尾)/FIRST:FIRST (取头)/ROUND:ROUND (轮流)/RANDOM:RANDOM (随机)/FAILOVER:FAILOVER (正常优先)/BUSYOVER:BUSYOVER (空闲优先)/CONSISTENT_HASH:CONSISTENT_HASH (分布负载)/LEAST_RECENTLY_USED:LEAST_RECENTLY_USED (最近最少使用)/LEAST_FREQUENTLY_USED:LEAST_FREQUENTLY_USED (最不经常使用)/SHARDING_BROADCAST:SHARDING_BROADCAST (全部共享广播)"
                      :rules="[(v) => !!v || '调度路由策略不能为空']" variant="outlined" density="compact"></vtk-select>
                  </vtk-search>
                </div>
                <v-card-text>
                  <vtk-form-item label="调度名称："  must>
                    <v-text-field v-model="entity.scheduleName" placeholder="请输入调度名称"
                      :rules="[(v) => !!v || '调度名称不能为空']" clearable density="compact" variant="outlined" />
                  </vtk-form-item>
                  
                  <vtk-form-item label="调度过期策略：" must>
                    <vtk-radio v-model="entity.scheduleMisfire" color="primary" inline :mandatory="true"
                      list="ADMIN:管理员/USER:普通用户/VIP:VIP用户" placeholder="请选择过期策略" :rules="[(v) => !!v || '过期策略不能为空']" />
                  </vtk-form-item>
                  <vtk-form-item label="管理人员：" must>
                    <vtk-checkbox v-model="entity.scheduleMisfireArr" inline list="ADMIN:管理员/USER:普通用户/VIP:VIP用户"
                      placeholder="请选择管理人员" :rules="[(v) => !!v || '管理人员不能为空']" />

                  </vtk-form-item>
                  <vtk-form-item label="调度路由策略：" must top style="width: 80%;padding-left: 10%;">
                    <vtk-select v-model="entity.scheduleRoutes" placeholder="请选择调度路由策略"
                      list="LAST:LAST (取尾)/FIRST:FIRST (取头)/ROUND:ROUND (轮流)/RANDOM:RANDOM (随机)/FAILOVER:FAILOVER (正常优先)/BUSYOVER:BUSYOVER (空闲优先)/CONSISTENT_HASH:CONSISTENT_HASH (分布负载)/LEAST_RECENTLY_USED:LEAST_RECENTLY_USED (最近最少使用)/LEAST_FREQUENTLY_USED:LEAST_FREQUENTLY_USED (最不经常使用)/SHARDING_BROADCAST:SHARDING_BROADCAST (全部共享广播)"
                      :rules="[(v) => !!v || '调度路由策略不能为空']" variant="outlined" density="compact"></vtk-select>
                  </vtk-form-item>

                  <vtk-form-item label="日期测试：" must>
                    <vtk-date-picker v-model="entity.dateRange" placeholder="请选择开始日期和结束日期" @change="handleChange"
                      :rules="[(v) => !!v || '开始日期和结束日期不能为空']" ></vtk-date-picker>
                  </vtk-form-item>

                  <vtk-form-item label="数字翻牌器：">
                    <VtkCount :start="0" :end="43143" :duration="2000" color="#ff5722" suffix="次" />
                  </vtk-form-item>

                  <vtk-form-item label="执行器重试次数：" must>
                    <v-text-field v-model="entity.scheduleRetries" type="number" placeholder="请输入执行器重试次数"
                      :rules="[(v) => /^\+?(?:0|[1-9]\d*)$/.test(v) || '请输入正整数']" variant="outlined"
                      density="compact"></v-text-field>
                  </vtk-form-item>
                  <vtk-form-item label="执行器超时间：" must>
                    <v-text-field v-model="entity.executorTimeout" type="number" placeholder="请输入执行器超时间"
                      :rules="[(v) => /^\+?(?:0|[1-9]\d*)$/.test(v) || '请输入正整数']" suffix="秒" variant="outlined"
                      density="compact" outlined></v-text-field>
                  </vtk-form-item>

                  <!-- 添加区域选择组件 -->
                  <vtk-form-item label="所属地区：" must top style="width: 80%; padding-left: 10%;">
                    <vtk-area 
                      v-model="entity.areaCode" 
                      :max-area="12" 
                      area-style="width: 100%"
                      @update:modelValue="handleAreaChange"
                    />
                  </vtk-form-item>

                  <!-- 图片列表区域 -->
                  <div class="image-list-section mt-6">
                    <v-card-title class="pa-0 mb-4">相关图片</v-card-title>
                    <v-row>
                      <v-col 
                        v-for="(image, index) in imageList" 
                        :key="index" 
                        cols="12" 
                        sm="2" 
                        md="2" 
                        lg="2"
                      >
                          <vtk-img
                            :src="image.url"
                            :title="image.title"
                            :description="image.description"
                            :image-list="imageList"
                            :index="index"
                            :aspect-ratio="16/9"
                            cover
                            class="image-item"
                          />
                      </v-col>
                    </v-row>
                  </div>
                  
                  <!-- PDF列表区域 -->
                  <div class="pdf-list-section mt-6">
                    <v-card-title class="pa-0 mb-4">相关文档</v-card-title>
                    <v-row>
                      <v-col 
                        v-for="(pdf, index) in pdfList" 
                        :key="index" 
                        cols="12" 
                        sm="2" 
                        md="2" 
                        lg="2"
                      >
                        <vtk-pdf
                          :src="pdf.url"
                          :title="pdf.title"
                          :description="pdf.description"
                          :aspect-ratio="16/9"
                          class="pdf-item"
                        />
                      </v-col>
                    </v-row>
                  </div>
                </v-card-text>
                <v-card-actions>
                  <v-spacer />
                  <v-btn class="mr-3" color="primary" @click="nextStep(2)" elevation="0"><v-icon>mdi-debug-step-into
                      mdi-rotate-270</v-icon> 下一步 </v-btn>
                  <v-spacer />
                </v-card-actions>
              </v-card>
            </template>
            <template slot="2" v-else-if="el == 2">
              <v-card>
                <v-card-title class="d-flex align-center">
                  <span>任务列表</span>
                  <v-spacer></v-spacer>
                  <v-text-field
                    v-model="search"
                    append-icon="mdi-magnify"
                    label="搜索"
                    single-line
                    hide-details
                    density="compact"
                    variant="outlined"
                    class="search-field"
                  ></v-text-field>
                </v-card-title>
                
                <v-data-table
                  :headers="headers"
                  :items="paginatedItems"
                  :items-per-page="pageData.limit"
                  hide-default-footer
                  class="elevation-1"
                >
                  <template v-slot:item.status="{ item }">
                    <v-chip :color="getStatusColor(item.status)" size="small">
                      {{ item.status }}
                    </v-chip>
                  </template>
                  <template v-slot:item.actions="{ item }">
                    <v-btn icon size="small" @click="viewItem(item)">
                      <v-icon>mdi-eye</v-icon>
                    </v-btn>
                    <v-btn icon size="small" @click="editItem(item)">
                      <v-icon>mdi-pencil</v-icon>
                    </v-btn>
                    <v-btn icon size="small" @click="deleteItem(item)">
                      <v-icon>mdi-delete</v-icon>
                    </v-btn>
                  </template>
                </v-data-table>
                
                <!-- 分页组件区域 -->
                <div class="pagination-wrapper">
                  <vtk-page 
                    :page-data="pageData" 
                    :page-sizes="[5, 10, 20]" 
                    @page-change="handlePageChange" 
                  />
                </div>
                
                <!-- 操作按钮区域 -->
                <v-card-actions class="button-wrapper">
                  <v-spacer />
                  <v-btn class="mr-3" @click="el = 1" elevation="0">
                    <v-icon start>mdi-debug-step-into mdi-rotate-90</v-icon>
                    上一步
                  </v-btn>
                  <v-btn class="mr-3" color="primary" @click="nextStep(3)" elevation="0">
                    <v-icon end>mdi-debug-step-into mdi-rotate-270</v-icon>
                    下一步
                  </v-btn>
                  <v-spacer />
                </v-card-actions>
              </v-card>
            </template>
            <template slot="3" v-else-if="el == 3">
              <v-card>
                <v-card-actions>
                  <v-spacer />
                  <v-btn class="mr-3" @click="el = 2" elevation="0">
                    <v-icon start>mdi-debug-step-into mdi-rotate-90</v-icon>
                    上一步
                  </v-btn>
                  <v-btn class="mr-3" color="primary" @click="nextStep(4)" elevation="0">
                    <v-icon end>mdi-debug-step-into mdi-rotate-270</v-icon>
                    下一步
                  </v-btn>
                  <v-spacer />
                </v-card-actions>
              </v-card>
            </template>
            <template slot="4" v-else>
              <v-card class="text-center py-12" elevation="0">
                <p class="green--text display-1 font-weight-bold mt-8 mb-3">配置完成</p>
                <p class="title mb-6" :class="!$vuetify.theme.dark && 'indigo--text text--darken-4'">
                  等待构建，构建完成后默认为未启用状态，请自行启用！</p>
                <v-card-actions>
                  <v-spacer />
                  <v-btn class="mr-3" @click="el = 3" elevation="0">
                    <v-icon start>mdi-debug-step-into mdi-rotate-90</v-icon>
                    上一步
                  </v-btn>
                  <v-btn color="primary" @click="submit" elevation="0">
                    <v-icon start>mdi-check-circle-outline</v-icon>
                    立即构建
                  </v-btn>
                  <v-spacer />
                </v-card-actions>
              </v-card>
            </template>
          </vtk-stepper>
        </v-form>
      </v-card>
    </div>
    
   
    
    <!-- 查看详情对话框 -->
    <v-dialog v-model="dialogView" max-width="600px">
      <v-card>
        <v-card-title>
          <span class="text-h5">任务详情</span>
        </v-card-title>
        <v-card-text v-if="selectedItem">
          <v-list>
            <v-list-item>
              <v-list-item-title>ID:</v-list-item-title>
              <v-list-item-subtitle>{{ selectedItem.id }}</v-list-item-subtitle>
            </v-list-item>
            <v-list-item>
              <v-list-item-title>任务名称:</v-list-item-title>
              <v-list-item-subtitle>{{ selectedItem.name }}</v-list-item-subtitle>
            </v-list-item>
            <v-list-item>
              <v-list-item-title>状态:</v-list-item-title>
              <v-list-item-subtitle>
                <v-chip :color="getStatusColor(selectedItem.status)" size="small">
                  {{ selectedItem.status }}
                </v-chip>
              </v-list-item-subtitle>
            </v-list-item>
            <v-list-item>
              <v-list-item-title>负责人:</v-list-item-title>
              <v-list-item-subtitle>{{ selectedItem.assignee }}</v-list-item-subtitle>
            </v-list-item>
            <v-list-item>
              <v-list-item-title>创建时间:</v-list-item-title>
              <v-list-item-subtitle>{{ selectedItem.createTime }}</v-list-item-subtitle>
            </v-list-item>
            <v-list-item>
              <v-list-item-title>描述:</v-list-item-title>
              <v-list-item-subtitle>{{ selectedItem.description }}</v-list-item-subtitle>
            </v-list-item>
          </v-list>
        </v-card-text>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn color="primary" @click="dialogView = false">关闭</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>

<script setup>
import { ref, computed, reactive, onMounted } from 'vue'

// 如果你有真实的 vtk-area 组件，取消下面的导入
// import VtkArea from '@/components/assembly/VtkArea.vue'

const { proxy } = getCurrentInstance();
const router = useRouter();
// 添加跳转到/home的方法
const goToHome = () => {
  router.push('/home')
}

console.log('111---', proxy.$vtk.request)

const dateRange = ref([])

const reset = () => {
  form.value = {
    username: '',
    email: '',
    remark: ''
  }
}

const handleChange = (range) => {
  console.log('日期范围已更改:', range)
}

// 处理区域选择变化
const handleAreaChange = (areaCode) => {
  console.log('选择的区域代码:', areaCode)
  entity.areaCode = areaCode
}

// 基础测试数据
const el = ref(1)
const currentStep = ref(1)
const valid = ref(false)
const form = ref(null) // 添加表单引用

// 表格相关数据
const search = ref('')
const dialogView = ref(false)
const selectedItem = ref(null)

// 图片查看器相关数据
const imageViewerDialog = ref(false)
const currentImageIndex = ref(0)
const imageRotation = ref(0)

// 实体数据
const entity = reactive({
  scheduleName: '',
  scheduleMisfire: '',
  scheduleMisfire2: '',
  scheduleMisfireArr: [],
  scheduleRoutes: '',
  dateRange: [],
  testDate: '',
  exid: '',
  executorBlocks: '',
  scheduleRetries: '',
  executorTimeout: '',
  executorType: '',
  executorParam: '',
  executorText: '',
  scheduleType: '',
  scheduleConf: '',
  areaCode: '' // 添加区域代码字段
})

// 图片列表数据
const imageList = ref([
  {
    url: 'https://picsum.photos/800/600?random=1',
    title: '项目概览图',
    description: '展示项目整体架构'
  },
  {
    url: 'https://picsum.photos/800/600?random=2',
    title: '流程图',
    description: '业务流程示意图'
  },
  {
    url: 'https://picsum.photos/800/600?random=3',
    title: '',
    description: '关键指标趋势分析'
  },
  {
    url: 'https://picsum.photos/800/600?random=4',
    title: '系统拓扑图',
    description: ''
  },
  {
    url: 'https://picsum.photos/800/600?random=5',
    title: '用户界面',
    description: '前端界面设计稿'
  },
  {
    url: 'https://picsum.photos/800/600?random=6',
    title: '',
    description: ''
  },
  {
    url: 'https://picsum.photos/800/600?random=7',
    title: 'API文档',
    description: '接口规范说明'
  },
  {
    url: 'https://picsum.photos/800/600?random=8',
    title: '测试报告',
    description: '自动化测试结果'
  }
])

// PDF列表数据
const pdfList = ref([
  {
    url: 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf',
    title: '项目需求文档',
    description: '详细的需求规格说明书'
  },
  {
    url: 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf',
    title: '技术设计文档',
    description: '系统架构和技术选型说明'
  },
  {
    url: 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf',
    title: '测试报告',
    description: '功能测试和性能测试结果'
  },
  {
    url: 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf',
    title: '用户手册',
    description: '系统使用指南和操作说明'
  },
  {
    url: 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf',
    title: '部署文档',
    description: '系统部署和维护指南'
  },
  {
    url: 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf',
    title: 'API文档',
    description: '接口文档和调用示例'
  }
])

// 执行器列表
const execList = ref([
  { id: 1, name: '执行器1', title: '执行器1描述' },
  { id: 2, name: '执行器2', title: '执行器2描述' },
  { id: 3, name: '执行器3', title: '执行器3描述' }
])

// 调度配置验证规则
const checkScheduleConf = [(v) => !!v || '调度配置不能为空']

// 动态测试数据
const dynamicStepsInput = ref("信息填写,数据验证,完成提交")
const dynamicSteps = ref("信息填写,数据验证,完成提交")
const dynamicCurrentStep = ref(1)

// 表格数据
const tableItems = ref([])
const pageData = ref({
  pageno: 1,
  pageCount: 1,
  rowCount: 0,
  limit: 10
})

// 表格列定义
const headers = [
  { title: 'ID', key: 'id' },
  { title: '任务名称', key: 'name' },
  { title: '状态', key: 'status' },
  { title: '负责人', key: 'assignee' },
  { title: '创建时间', key: 'createTime' },
  { title: '操作', key: 'actions', sortable: false }
]

// 计算属性
const dynamicStepsArray = computed(() => {
  return dynamicSteps.value ? dynamicSteps.value.split(',') : []
})

// 分页数据计算
const paginatedItems = computed(() => {
  const start = (pageData.value.pageno - 1) * pageData.value.limit
  const end = start + pageData.value.limit
  return tableItems.value.slice(start, end)
})

// 初始化表格数据
const initializeTableData = () => {
  const mockData = []
  const statuses = ['运行中', '已完成', '待处理', '已暂停', '错误']
  const assignees = ['张三', '李四', '王五', '赵六', '钱七']
  
  for (let i = 1; i <= 47; i++) {
    mockData.push({
      id: i,
      name: `任务-${i.toString().padStart(3, '0')}`,
      status: statuses[Math.floor(Math.random() * statuses.length)],
      assignee: assignees[Math.floor(Math.random() * assignees.length)],
      createTime: `2023-${String(Math.floor(Math.random() * 12) + 1).padStart(2, '0')}-${String(Math.floor(Math.random() * 28) + 1).padStart(2, '0')} ${String(Math.floor(Math.random() * 24)).padStart(2, '0')}:${String(Math.floor(Math.random() * 60)).padStart(2, '0')}:${String(Math.floor(Math.random() * 60)).padStart(2, '0')}`,
      description: `这是任务-${i.toString().padStart(3, '0')}的详细描述信息`
    })
  }
  
  tableItems.value = mockData
  pageData.value.rowCount = mockData.length
  pageData.value.pageCount = Math.ceil(mockData.length / pageData.value.limit)
}

// 状态颜色映射
const getStatusColor = (status) => {
  const colorMap = {
    '运行中': 'success',
    '已完成': 'primary',
    '待处理': 'warning',
    '已暂停': 'info',
    '错误': 'error'
  }
  return colorMap[status] || 'default'
}


// 表格操作方法
const viewItem = (item) => {
  selectedItem.value = item
  dialogView.value = true
}

const editItem = (item) => {
  console.log('编辑项目:', item)
}

const deleteItem = (item) => {
  console.log('删除项目:', item)
}

// 分页处理
const handlePageChange = (page) => {
  pageData.value.pageno = page.pageno
  pageData.value.limit = page.limit
}

// 基础步骤控制方法
const nextStep = (step) => {
  console.log(form.value.validate())
  form.value.validate().then((res) => {
    if (res.valid) {
      console.log(res)
      el.value = step
    } else {
      return
    }
  })
}

const prevStep = () => {
  if (el.value > 1) {
    el.value--
  }
}

const resetStep = () => {
  el.value = 1
}

// 动态步骤控制方法
const updateDynamicSteps = () => {
  dynamicSteps.value = dynamicStepsInput.value
  dynamicCurrentStep.value = 1
}

const dynamicNextStep = () => {
  if (dynamicCurrentStep.value < dynamicStepsArray.value.length) {
    dynamicCurrentStep.value++
  }
}

const dynamicPrevStep = () => {
  if (dynamicCurrentStep.value > 1) {
    dynamicCurrentStep.value--
  }
}

const resetDynamicStep = () => {
  dynamicCurrentStep.value = 1
}

// 模拟方法（实际项目中需要替换为真实实现）
const swapInputFn = () => {
  console.log('编辑按钮点击')
}

const dialogEditClick = () => {
  console.log('代码按钮点击')
}

const handleCloseDialog = () => {
  console.log('关闭对话框')
}

const submit = () => {
  console.log('提交表单')
}

// 生命周期钩子
onMounted(() => {
  initializeTableData()
})
</script>

<style scoped>
.test-container {
  padding: 20px;
  /* max-width: 1200px; */
  margin: 0 auto;
  width: 100%;
}

.search-field {
  max-width: 300px;
}

.pagination-wrapper {
  padding: 16px;
  display: flex;
  justify-content: center;
}

.button-wrapper {
  padding: 16px 0;
}

.image-card {
  transition: transform 0.2s ease-in-out;
  cursor: pointer;
}

.image-card:hover {
  transform: translateY(-5px);
}

.image-item {
  height: 200px;
}

.pdf-item {
  height: 200px;
}

/* 图片查看器样式 */
.image-viewer-card {
  background-color: rgba(0, 0, 0, 0.9);
  color: white;
}

.image-viewer-content {
  display: flex;
  align-items: center;
  justify-content: center;
  height: calc(100vh - 150px);
  position: relative;
}

.image-container {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.viewer-image {
  max-width: 90%;
  max-height: 80vh;
  transition: transform 0.3s ease;
}

.nav-button {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  z-index: 10;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  width: 50px;
  height: 50px;
}

.prev-button {
  left: 20px;
}

.next-button {
  right: 20px;
}

.image-info {
  padding: 20px;
  background-color: rgba(0, 0, 0, 0.7);
}

.image-info p {
  margin: 5px 0;
}
</style>