<template>
  <div class="disposal-console desktop-layout">
      <el-row :gutter="16">
        <el-col :span="isMobile ? 24 : 8" class="left-panel">
          <!-- Statistics -->
          <DisposalStatsCard
            ref="statsCard"
            @stat-click="handleStatClick"
          />
          
          <!-- Task List Card (with integrated filters) -->
          <el-card shadow="never" class="task-list-card">
            <div slot="header" class="card-header">
              <span>任务列表</span>
              <el-button
                type="text"
                icon="el-icon-refresh"
                @click="handleRefresh"
                size="mini"
              >
                刷新
              </el-button>
            </div>
            <TaskListCard
              ref="desktopTaskList"
              :page-size="200"
              :auto-refresh="true"
              :refresh-interval="30000"
              :show-filter-bar="true"
              @view="handleSelectTask"
            />
          </el-card>
        </el-col>
        
        <el-col v-if="!isMobile" :span="16" class="right-panel">
          <StepDetailPanel
            v-if="selectedTask && currentStepId"
            :task-id="selectedTask.id"
            :step-id="currentStepId"
            @back="handleStepBack"
          />
          <TaskDetailPanel
            v-else-if="selectedTask"
            :task="selectedTask"
            @close="selectedTask = null"
            @refresh="refreshTaskList"
            @view-step="handleViewStep"
            @step-action="handleStepAction"
          />
          <div v-else class="empty-detail">
            <i class="el-icon-document"></i>
            <p>请选择任务查看详情</p>
          </div>
        </el-col>
      </el-row>
      
      <!-- 移动端覆盖层 -->
      <div v-if="isMobile && (selectedTask || currentStepId)" class="mobile-overlay">
        <div class="mobile-overlay-content">
          <StepDetailPanel
            v-if="selectedTask && currentStepId"
            :task-id="selectedTask.id"
            :step-id="currentStepId"
            @back="handleStepBack"
          />
          <TaskDetailPanel
            v-else-if="selectedTask"
            :task="selectedTask"
            :is-mobile="true"
            @close="handleCloseMobile"
            @refresh="refreshTaskList"
            @view-step="handleViewStep"
            @step-action="handleStepAction"
          />
        </div>
      </div>
  </div>
</template>

<script>
import DisposalStatsCard from './components/DisposalStatsCard.vue'
import TaskListCard from './components/TaskListCard.vue'
import TaskDetailPanel from './components/TaskDetailPanel.vue'
import StepDetailPanel from './components/StepDetailPanel.vue'

export default {
  name: 'DisposalConsole',
  components: {
    DisposalStatsCard,
    TaskListCard,
    TaskDetailPanel,
    StepDetailPanel
  },
  data() {
    return {
      selectedTask: null,
      currentStepId: null,
      windowWidth: window.innerWidth,
      windowHeight: window.innerHeight,
      backButtonHandler: null
    }
  },
  computed: {
    // 判断是否为移动端，主要根据屏幕宽度判断
    isMobile() {
      // 宽度小于768px认为是移动端，或者宽高比小于1（竖屏）且宽度小于1024px
      const width = this.windowWidth
      const height = this.windowHeight
      const aspectRatio = width / height
      
      // 竖屏且宽度较小，或横屏但宽度仍然很小
      return width < 768 || (aspectRatio < 1 && width < 1024)
    }
  },
  mounted() {
    this.refreshTaskList()
    this.handleResize()
    window.addEventListener('resize', this.handleResize)
    // 移动端：监听浏览器返回按钮
    if (this.isMobile) {
      this.setupBackButtonHandler()
    }
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
    // 移除返回按钮监听
    if (this.backButtonHandler) {
      window.removeEventListener('popstate', this.backButtonHandler)
    }
  },
  beforeRouteLeave(to, from, next) {
    // 移动端：如果任务详情打开，拦截路由跳转并关闭详情
    if (this.isMobile && this.selectedTask) {
      this.handleCloseMobile()
      // 阻止路由跳转
      next(false)
      return
    }
    next()
  },
  watch: {
    isMobile(newVal) {
      // 当移动端状态改变时，重新设置返回按钮监听
      if (newVal && !this.backButtonHandler) {
        this.setupBackButtonHandler()
      } else if (!newVal && this.backButtonHandler) {
        window.removeEventListener('popstate', this.backButtonHandler)
        this.backButtonHandler = null
      }
    }
  },
  methods: {
    setupBackButtonHandler() {
      // 设置浏览器返回按钮的拦截处理
      this.backButtonHandler = () => {
        // 如果任务详情打开，关闭详情并阻止浏览器返回
        if (this.selectedTask) {
          this.selectedTask = null
          this.currentStepId = null
          // 阻止浏览器返回，通过 pushState 保持当前路由
          window.history.pushState({ overlayClosed: true }, '', window.location.href)
        }
      }
      window.addEventListener('popstate', this.backButtonHandler)
    },
    handleResize() {
      this.windowWidth = window.innerWidth
      this.windowHeight = window.innerHeight
    },
    refreshTaskList() {
      if (this.$refs.desktopTaskList) {
        this.$refs.desktopTaskList.fetchTasks()
      }
    },
    handleRefresh() {
      this.refreshTaskList()
      this.$refs.statsCard?.fetchStats?.()
    },
    handleStatClick(stat) {
      this.$message.info(`点击统计：${stat.label}，功能待实现`)
    },
    handleSelectTask(task) {
      // 移动端和PC端都使用 selectedTask，移动端通过覆盖层显示
      this.selectedTask = task
      this.currentStepId = null
      // 移动端：打开详情时，添加历史记录以便拦截返回
      if (this.isMobile) {
        window.history.pushState({ overlayOpen: true }, '', window.location.href)
      }
    },
    handleViewStep(step) {
      this.currentStepId = step?.id || null
    },
    handleStepAction({ command, step }) {
      const actionMap = {
        start: '开始执行',
        complete: '标记完成',
        fail: '标记失败'
      }
      const text = actionMap[command] || '操作'
      const name = step?.name || step?.title || '行动项'
      this.$message.info(`${text} "${name}" 功能待实现`)
    },
    handleStepBack() {
      this.currentStepId = null
    },
    handleCloseMobile() {
      this.selectedTask = null
      this.currentStepId = null
      // 移动端：关闭详情时，如果有历史记录则返回
      if (this.isMobile && window.history.state && window.history.state.overlayOpen) {
        // 移除 popstate 监听，避免触发
        if (this.backButtonHandler) {
          window.removeEventListener('popstate', this.backButtonHandler)
        }
        window.history.back()
        // 重新添加监听
        this.$nextTick(() => {
          if (this.isMobile && this.backButtonHandler) {
            window.addEventListener('popstate', this.backButtonHandler)
          }
        })
      }
    },
    prepareResourceGroups(resources = []) {
      const groups = {
        materials: [],
        equipment: [],
        vehicles: []
      }
      resources.forEach(item => {
        if (item.resourceType === 'material') {
          groups.materials.push(item)
        } else if (item.resourceType === 'equipment') {
          groups.equipment.push(item)
        } else if (item.resourceType === 'vehicle') {
          groups.vehicles.push(item)
        }
      })
      return groups
    }
  }
}
</script>

<style lang="scss" scoped>
.desktop-layout {
  height: calc(100vh - 84px); // Adjust based on header/navbar height
  padding: 16px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}
.desktop-layout ::v-deep .el-row {
  height: 100%;
  min-height: 0;
}

.desktop-layout ::v-deep .el-col {
  height: 100%;
  min-height: 0;
}

.left-panel {
  height: 100%;
  display: flex;
  flex-direction: column;
  min-height: 0;
  gap: 16px;
  overflow: hidden;
  
  .task-list-card {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-height: 0;
    margin-bottom: 0;
    overflow: hidden;
    
    ::v-deep .el-card__body {
      flex: 1;
      display: flex;
      flex-direction: column;
      min-height: 0;
      overflow: hidden;
      padding: 20px;
    }
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.right-panel {
  height: 100%;
  overflow: hidden;
}

.task-detail-container {
  height: 100%;
  padding: 16px;
  background: #fff;
  border-radius: 4px;
}

.task-detail-placeholder {
  padding: 40px;
  text-align: center;
  color: #909399;
  
  .hint {
    font-size: 12px;
    color: #c0c4cc;
    margin-top: 8px;
  }
}

.empty-detail {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
  
  i {
    font-size: 64px;
    margin-bottom: 16px;
  }
}

.loading-container,
.empty-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  padding: 40px 20px;
  color: #909399;
}

.step-resource-section {
  margin-top: 16px;
}

.resource-table {
  margin-bottom: 16px;
}

.resource-table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 6px;

  h4 {
    margin: 0;
    font-size: 14px;
    color: #303133;
  }

  span {
    font-size: 12px;
    color: #909399;
  }
}

/* 移动端覆盖层 */
.mobile-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 2000;
  background: #f5f7fb;
  overflow: hidden;
}

.mobile-overlay-content {
  height: 100%;
  width: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}
</style>