<template>
  <GiPageLayout>
    <div class="personnel-distribution-container">
      <!-- 顶部搜索表单 -->
      <a-card class="search-card" :bordered="false">
        <a-form :model="searchForm" layout="inline">
          <a-form-item label="项目选择">
            <a-select 
              v-model="searchForm.projectName" 
              :placeholder="'请选择项目'"
              style="width: 200px"
              allow-clear
            >
              <a-option value="wind-tower-detection">风电塔下检测项目</a-option>
              <a-option value="blade-inspection">叶片检测项目</a-option>
              <a-option value="maintenance-project">维护项目</a-option>
            </a-select>
          </a-form-item>
          <a-form-item label="角色筛选">
            <a-select 
              v-model="searchForm.role" 
              :placeholder="'请选择角色'"
              style="width: 150px"
              allow-clear
            >
              <a-option value="construction">施工人员</a-option>
              <a-option value="safety">安全经理</a-option>
              <a-option value="project">项目经理</a-option>
              <a-option value="quality">质量经理</a-option>
            </a-select>
          </a-form-item>
          <a-form-item label="时间范围">
            <a-range-picker 
              v-model="searchForm.timeRange" 
              style="width: 300px"
              format="YYYY-MM-DD"
              :placeholder="['开始日期', '结束日期']"
            />
          </a-form-item>
          <a-form-item>
            <a-button type="primary" @click="handleSearch">
              <template #icon><icon-search /></template>
              查询
            </a-button>
          </a-form-item>
          <a-form-item>
            <a-button @click="handleReset">
              <template #icon><icon-refresh /></template>
              重置
            </a-button>
          </a-form-item>
        </a-form>
      </a-card>

      <!-- 页面标题和操作按钮 -->
      <div class="title-section">
        <h2 class="page-title">{{ currentProjectTitle }} 人员分布</h2>
        <div class="action-buttons">
          <a-button type="primary" :class="{ active: viewMode === 'chart' }" @click="setViewMode('chart')">
            <template #icon><icon-bar-chart /></template>
            分布图
          </a-button>
          <a-button :class="{ active: viewMode === 'table' }" @click="setViewMode('table')">
            <template #icon><icon-list /></template>
            分布表
          </a-button>
          <a-button :class="{ active: viewMode === 'gantt' }" @click="setViewMode('gantt')">
            <template #icon><icon-clock-circle /></template>
            甘特图
          </a-button>
          <a-button type="outline" @click="handleAddSchedule">
            <template #icon><icon-plus /></template>
            新增安排
          </a-button>
          <a-button @click="handleExport" status="success">
            <template #icon><icon-download /></template>
            导出
          </a-button>
        </div>
      </div>

      <!-- 主内容区域 -->
      <div class="main-content">
        <!-- 左侧角色图例 -->
        <div class="legend-section">
          <div class="legend-title">角色分布</div>
          <div class="legend-list">
            <div 
              v-for="(role, index) in roleData" 
              :key="index"
              class="legend-item"
              @click="toggleRole(index)"
            >
              <span 
                class="legend-dot" 
                :style="{ backgroundColor: role.color }"
              ></span>
              <span class="legend-label">{{ role.name }}</span>
            </div>
          </div>
        </div>

        <!-- 右侧图表区域 -->
        <div class="chart-section">
          <a-card class="chart-card" :bordered="false">
            <template #title>
              <div class="chart-title">{{ currentProjectTitle }} - 角色分布</div>
            </template>
            
            <div class="chart-container">
              <div id="personnelChart" class="chart"></div>
            </div>
          </a-card>
        </div>
      </div>
    </div>
  </GiPageLayout>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { Message } from '@arco-design/web-vue'
import { 
  IconSearch, 
  IconRefresh, 
  IconBarChart, 
  IconList, 
  IconClockCircle, 
  IconPlus, 
  IconDownload 
} from '@arco-design/web-vue/es/icon'

defineOptions({ name: 'PersonnelDistribution' })

// 搜索表单
const searchForm = reactive({
  projectName: 'wind-tower-detection',
  role: '',
  timeRange: []
})

// 视图模式
const viewMode = ref('chart')

// 当前项目标题
const currentProjectTitle = computed(() => {
  const projectMap = {
    'wind-tower-detection': '风电塔下检测项目',
    'blade-inspection': '叶片检测项目',
    'maintenance-project': '维护项目'
  }
  return projectMap[searchForm.projectName] || '风电塔下检测项目'
})

// 角色数据
const roleData = ref([
  {
    name: '施工人员',
    color: '#6366f1',
    value: 12,
    percentage: 42.9
  },
  {
    name: '安全经理',
    color: '#10b981',
    value: 6,
    percentage: 21.4
  },
  {
    name: '项目经理',
    color: '#f59e0b',
    value: 5,
    percentage: 17.9
  },
  {
    name: '质量经理',
    color: '#ef4444',
    value: 5,
    percentage: 17.9
  }
])

// 设置视图模式
const setViewMode = (mode: string) => {
  viewMode.value = mode
  if (mode === 'chart') {
    nextTick(() => {
      initChart()
    })
  }
}

// 切换角色显示
const toggleRole = (index: number) => {
  // 切换角色的显示/隐藏状态
  // 这里可以添加具体的逻辑
  Message.info(`切换 ${roleData.value[index].name} 显示状态`)
}

// 搜索处理
const handleSearch = () => {
  Message.success('查询成功')
  // 重新初始化图表
  nextTick(() => {
    initChart()
  })
}

// 重置搜索
const handleReset = () => {
  searchForm.projectName = 'wind-tower-detection'
  searchForm.role = ''
  searchForm.timeRange = []
  handleSearch()
}

// 新增安排
const handleAddSchedule = () => {
  Message.info('新增安排功能')
}

// 导出数据
const handleExport = () => {
  Message.success('导出成功')
}

// 初始化图表
const initChart = () => {
  const chartContainer = document.getElementById('personnelChart')
  if (!chartContainer) return

  // 清空容器
  chartContainer.innerHTML = ''

  // SVG 图表参数
  const svgWidth = 400
  const svgHeight = 400
  const centerX = svgWidth / 2
  const centerY = svgHeight / 2
  const outerRadius = 150
  const innerRadius = 80

  // 创建 SVG
  const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
  svg.setAttribute('width', svgWidth.toString())
  svg.setAttribute('height', svgHeight.toString())
  svg.setAttribute('viewBox', `0 0 ${svgWidth} ${svgHeight}`)

  // 计算角度
  let currentAngle = 0
  const total = roleData.value.reduce((sum, item) => sum + item.value, 0)

  // 绘制饼图扇形
  roleData.value.forEach((role, index) => {
    const percentage = role.value / total
    const angleSpan = percentage * 2 * Math.PI
    const endAngle = currentAngle + angleSpan

    // 计算路径
    const startX = centerX + Math.cos(currentAngle) * outerRadius
    const startY = centerY + Math.sin(currentAngle) * outerRadius
    const endX = centerX + Math.cos(endAngle) * outerRadius
    const endY = centerY + Math.sin(endAngle) * outerRadius

    const innerStartX = centerX + Math.cos(currentAngle) * innerRadius
    const innerStartY = centerY + Math.sin(currentAngle) * innerRadius
    const innerEndX = centerX + Math.cos(endAngle) * innerRadius
    const innerEndY = centerY + Math.sin(endAngle) * innerRadius

    const largeArcFlag = angleSpan > Math.PI ? 1 : 0

    // 创建路径
    const pathData = [
      `M ${innerStartX} ${innerStartY}`,
      `L ${startX} ${startY}`,
      `A ${outerRadius} ${outerRadius} 0 ${largeArcFlag} 1 ${endX} ${endY}`,
      `L ${innerEndX} ${innerEndY}`,
      `A ${innerRadius} ${innerRadius} 0 ${largeArcFlag} 0 ${innerStartX} ${innerStartY}`,
      'Z'
    ].join(' ')

    const path = document.createElementNS('http://www.w3.org/2000/svg', 'path')
    path.setAttribute('d', pathData)
    path.setAttribute('fill', role.color)
    path.setAttribute('stroke', '#fff')
    path.setAttribute('stroke-width', '2')
    path.style.cursor = 'pointer'

    // 添加悬停效果
    path.addEventListener('mouseenter', () => {
      path.setAttribute('transform', `scale(1.05)`)
      path.style.transformOrigin = `${centerX}px ${centerY}px`
    })

    path.addEventListener('mouseleave', () => {
      path.setAttribute('transform', 'scale(1)')
    })

    svg.appendChild(path)

    currentAngle = endAngle
  })

  chartContainer.appendChild(svg)
}

onMounted(() => {
  nextTick(() => {
    initChart()
  })
})
</script>

<style scoped lang="scss">
.personnel-distribution-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.title-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  margin: 0;
  color: #1d2129;
}

.action-buttons {
  display: flex;
  gap: 8px;

  .arco-btn.active {
    background-color: #1890ff;
    border-color: #1890ff;
    color: white;
  }
}

.main-content {
  display: flex;
  gap: 20px;
}

.legend-section {
  flex-shrink: 0;
  width: 200px;
}

.legend-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 20px;
  color: #1d2129;
}

.legend-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.2s;

  &:hover {
    background-color: #f7f8fa;
  }
}

.legend-dot {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  flex-shrink: 0;
}

.legend-label {
  font-size: 14px;
  color: #4e5969;
}

.chart-section {
  flex: 1;
}

.chart-card {
  .chart-title {
    font-size: 16px;
    font-weight: 600;
    color: #1d2129;
  }
}

.chart-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

.chart {
  width: 100%;
  height: 400px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style> 