<template>
  <div class="p-6">
    <!-- 头部操作区 -->
    <div class="bg-white rounded-lg shadow p-6 mb-6">
      <div class="flex justify-between items-center">
        <h2 class="text-2xl font-bold text-gray-800">客户管理</h2>
        <div class="flex space-x-4">
          <button 
            @click="showAddDialog = true"
            class="flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
          >
            <PlusIcon class="w-5 h-5 mr-2" />
            新增客户
          </button>
          <button 
            @click="showAnalysisDialog = true"
            class="flex items-center px-4 py-2 bg-yellow-500 text-white rounded-lg hover:bg-yellow-600 transition-colors"
          >
            <BarChartIcon class="w-5 h-5 mr-2" />
            客户分析
          </button>
          <button 
            @click="handleExport"
            class="flex items-center px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors"
          >
            <DownloadIcon class="w-5 h-5 mr-2" />
            导出数据
          </button>
          <div class="relative">
            <input 
              type="file" 
              class="hidden" 
              ref="fileInput"
              @change="handleFileChange"
            />
            <button 
              @click="$refs.fileInput.click()"
              class="flex items-center px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors"
            >
              <UploadIcon class="w-5 h-5 mr-2" />
              导入数据
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 筛选区 -->
    <div class="bg-white rounded-lg shadow p-6 mb-6">
      <div class="flex flex-wrap gap-4">
        <div class="relative flex-1 min-w-[200px]">
          <SearchIcon class="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
          <input 
            v-model="searchQuery"
            type="text"
            placeholder="搜索客户名称/联系人/电话"
            class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
            @input="handleSearch"
          />
        </div>
        <select 
          v-model="filterLevel"
          class="px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
          @change="handleSearch"
        >
          <option value="">客户等级</option>
          <option v-for="level in customerLevels" :key="level.value" :value="level.value">
            {{ level.label }}
          </option>
        </select>
        <select 
          v-model="filterStatus"
          class="px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
          @change="handleSearch"
        >
          <option value="">客户状态</option>
          <option v-for="status in customerStatuses" :key="status.value" :value="status.value">
            {{ status.label }}
          </option>
        </select>
        <div class="flex items-center space-x-2">
          <input 
            type="date" 
            v-model="dateRange[0]"
            class="px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
            @change="handleSearch"
          />
          <span>至</span>
          <input 
            type="date" 
            v-model="dateRange[1]"
            class="px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
            @change="handleSearch"
          />
        </div>
      </div>
    </div>

    <!-- 客户列表 -->
    <div class="bg-white rounded-lg shadow overflow-hidden">
      <div class="overflow-x-auto">
        <table class="min-w-full divide-y divide-gray-200">
          <thead class="bg-gray-50">
            <tr>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                <input 
                  type="checkbox" 
                  v-model="selectAll"
                  class="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                />
              </th>
              <th 
                v-for="column in columns" 
                :key="column.prop"
                class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider cursor-pointer"
                @click="handleSort(column.prop)"
              >
                <div class="flex items-center">
                  {{ column.label }}
                  <span class="ml-1">
                    <ChevronUpIcon v-if="sortKey === column.prop && sortOrder === 'asc'" class="h-4 w-4 inline-block" />
                    <ChevronDownIcon v-else-if="sortKey === column.prop && sortOrder === 'desc'" class="h-4 w-4 inline-block" />
                  </span>
                </div>
              </th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                操作
              </th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            <tr v-for="customer in filteredCustomers" :key="customer.id" class="hover:bg-gray-50">
              <td class="px-6 py-4 whitespace-nowrap">
                <input 
                  type="checkbox" 
                  v-model="selectedItems"
                  :value="customer.id"
                  class="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                />
              </td>
              <td class="px-6 py-4 whitespace-nowrap">{{ customer.name }}</td>
              <td class="px-6 py-4 whitespace-nowrap">{{ customer.contact }}</td>
              <td class="px-6 py-4 whitespace-nowrap">{{ customer.phone }}</td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span 
                  :class="[
                    'px-2 py-1 text-xs font-semibold rounded-full',
                    getLevelClass(customer.level)
                  ]"
                >
                  {{ getLevelLabel(customer.level) }}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span 
                  :class="[
                    'px-2 py-1 text-xs font-semibold rounded-full',
                    getStatusClass(customer.status)
                  ]"
                >
                  {{ getStatusLabel(customer.status) }}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">{{ formatDateTime(customer.createTime) }}</td>
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="flex space-x-2">
                  <button 
                    @click="showDetail(customer)"
                    class="px-3 py-1 text-sm text-blue-600 hover:text-blue-800"
                  >
                    详情
                  </button>
                  <button 
                    @click="handleEdit(customer)"
                    class="px-3 py-1 text-sm text-green-600 hover:text-green-800"
                  >
                    编辑
                  </button>
                  <button 
                    @click="handleDelete(customer)"
                    class="px-3 py-1 text-sm text-red-600 hover:text-red-800"
                  >
                    删除
                  </button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- 批量操作 -->
      <div v-if="selectedItems.length > 0" class="px-6 py-4 bg-gray-50 border-t border-gray-200">
        <div class="flex items-center justify-between">
          <span class="text-sm text-gray-600">已选择 {{ selectedItems.length }} 项</span>
          <div class="flex space-x-4">
            <button 
              @click="handleBatchEdit"
              class="flex items-center px-4 py-2 text-sm text-blue-600 hover:text-blue-800"
            >
              <EditIcon class="w-4 h-4 mr-1" />
              批量编辑
            </button>
            <button 
              @click="handleBatchDelete"
              class="flex items-center px-4 py-2 text-sm text-red-600 hover:text-red-800"
            >
              <TrashIcon class="w-4 h-4 mr-1" />
              批量删除
            </button>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="px-6 py-4 bg-gray-50 border-t border-gray-200">
        <div class="flex items-center justify-between">
          <div class="flex items-center">
            <span class="text-sm text-gray-700 mr-4">每页显示</span>
            <select 
              v-model="pageSize"
              class="px-2 py-1 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              @change="handleSizeChange"
            >
              <option v-for="size in [10, 20, 50, 100]" :key="size" :value="size">
                {{ size }}
              </option>
            </select>
          </div>
          <div class="flex items-center space-x-2">
            <button 
              @click="currentPage--"
              :disabled="currentPage === 1"
              class="px-3 py-1 border border-gray-300 rounded-md disabled:opacity-50"
            >
              <ChevronLeftIcon class="w-4 h-4" />
            </button>
            <span class="text-sm text-gray-700">
              第 {{ currentPage }} 页 / 共 {{ totalPages }} 页
            </span>
            <button 
              @click="currentPage++"
              :disabled="currentPage === totalPages"
              class="px-3 py-1 border border-gray-300 rounded-md disabled:opacity-50"
            >
              <ChevronRightIcon class="w-4 h-4" />
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 客户统计 -->
    <div class="grid grid-cols-4 gap-6 mt-6">
      <div v-for="stat in statistics" :key="stat.title" class="bg-white rounded-lg shadow p-6">
        <div class="text-gray-500 text-sm">{{ stat.title }}</div>
        <div class="text-2xl font-bold text-gray-800 mt-2">{{ stat.value }}</div>
      </div>
    </div>

    <!-- 客户分析图表 -->
    <div class="bg-white rounded-lg shadow p-6 mt-6">
      <div class="flex justify-between items-center mb-6">
        <h3 class="text-lg font-semibold text-gray-800">客户分析</h3>
        <div class="flex space-x-2">
          <button 
            v-for="type in ['level', 'status', 'growth']"
            :key="type"
            @click="analysisType = type"
            :class="[
              'px-4 py-2 rounded-lg',
              analysisType === type 
                ? 'bg-blue-600 text-white' 
                : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
            ]"
          >
            {{ type === 'level' ? '等级分布' : type === 'status' ? '状态分布' : '增长趋势' }}
          </button>
        </div>
      </div>
      <div class="h-80" ref="analysisChart"></div>
    </div>

    <!-- 新增/编辑客户对话框 -->
    <div v-if="showAddDialog" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center">
      <div class="bg-white rounded-lg shadow-xl w-1/2 max-w-2xl">
        <div class="flex justify-between items-center p-6 border-b">
          <h3 class="text-lg font-semibold">{{ isEdit ? '编辑客户' : '新增客户' }}</h3>
          <button @click="showAddDialog = false" class="text-gray-400 hover:text-gray-500">
            <XIcon class="w-5 h-5" />
          </button>
        </div>
        <form @submit.prevent="handleSubmit" class="p-6">
          <div class="grid grid-cols-2 gap-6">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">客户名称</label>
              <input 
                v-model="addForm.name"
                type="text"
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                required
              />
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">客户等级</label>
              <select 
                v-model="addForm.level"
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                required
              >
                <option v-for="level in customerLevels" :key="level.value" :value="level.value">
                  {{ level.label }}
                </option>
              </select>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">联系人</label>
              <input 
                v-model="addForm.contact"
                type="text"
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                required
              />
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">联系电话</label>
              <input 
                v-model="addForm.phone"
                type="tel"
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                required
              />
            </div>
          </div>
          <div class="mt-6 flex justify-end space-x-4">
            <button 
              type="button"
              @click="showAddDialog = false"
              class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50"
            >
              取消
            </button>
            <button 
              type="submit"
              class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700"
            >
              确定
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- 客户分析对话框 -->
    <div v-if="showAnalysisDialog" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center">
      <div class="bg-white rounded-lg shadow-xl w-3/4 max-w-4xl">
        <div class="flex justify-between items-center p-6 border-b">
          <h3 class="text-lg font-semibold">客户分析</h3>
          <button @click="showAnalysisDialog = false" class="text-gray-400 hover:text-gray-500">
            <XIcon class="w-5 h-5" />
          </button>
        </div>
        <div class="p-6">
          <div class="flex justify-center space-x-4 mb-6">
            <button 
              v-for="type in ['level', 'status', 'growth']"
              :key="type"
              @click="analysisType = type"
              :class="[
                'px-4 py-2 rounded-lg',
                analysisType === type 
                  ? 'bg-blue-600 text-white' 
                  : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
              ]"
            >
              {{ type === 'level' ? '等级分布' : type === 'status' ? '状态分布' : '增长趋势' }}
            </button>
          </div>
          <div class="h-96" ref="analysisChart"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'
import * as echarts from 'echarts'
import { 
  LineChart,
  BarChart,
  PieChart,
  ScatterChart
} from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DataZoomComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import { 
  PlusIcon, 
  DownloadIcon, 
  UploadIcon, 
  SearchIcon, 
  ChevronUpIcon,
  ChevronDownIcon,
  EditIcon,
  TrashIcon,
  ChevronLeftIcon,
  ChevronRightIcon,
  XIcon,
  BarChartIcon
} from 'lucide-vue-next'
import { useRouter } from 'vue-router'

// 注册必要的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DataZoomComponent,
  LineChart,
  BarChart,
  PieChart,
  ScatterChart,
  CanvasRenderer
])

const router = useRouter()

// Mock 数据
const mockData = {
  customers: {
    list: [
      {
        id: 1,
        name: '客户A',
        contact: '张三',
        phone: '13800138000',
        level: 'vip',
        status: 'active',
        createTime: '2024-03-20T10:00:00'
      },
      {
        id: 2,
        name: '客户B',
        contact: '李四',
        phone: '13800138001',
        level: 'normal',
        status: 'inactive',
        createTime: '2024-03-19T09:30:00'
      }
    ],
    total: 2
  },
  statistics: {
    totalCustomers: 100,
    activeCustomers: 80,
    vipCustomers: 20,
    newCustomers: 10
  }
}

// 状态管理
const loading = ref(false)
const searchQuery = ref('')
const filterLevel = ref('')
const filterStatus = ref('')
const dateRange = ref(['', ''])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const selectedItems = ref([])
const showAddDialog = ref(false)
const showAnalysisDialog = ref(false)
const analysisType = ref('level')
const isEdit = ref(false)
const sortKey = ref('')
const sortOrder = ref('asc')
const analysisChart = ref(null)
const statistics = ref([
  { title: '总客户数', value: mockData.statistics.totalCustomers },
  { title: '活跃客户', value: mockData.statistics.activeCustomers },
  { title: 'VIP客户', value: mockData.statistics.vipCustomers },
  { title: '新增客户', value: mockData.statistics.newCustomers }
])
const addForm = ref({
  name: '',
  level: '',
  contact: '',
  phone: ''
})

// 常量定义
const customerLevels = [
  { value: 'vip', label: 'VIP客户' },
  { value: 'normal', label: '普通客户' }
]

const customerStatuses = [
  { value: 'active', label: '活跃' },
  { value: 'inactive', label: '非活跃' }
]

const columns = [
  { prop: 'name', label: '客户名称' },
  { prop: 'contact', label: '联系人' },
  { prop: 'phone', label: '联系电话' },
  { prop: 'level', label: '客户等级' },
  { prop: 'status', label: '客户状态' },
  { prop: 'createTime', label: '创建时间' }
]

// 计算属性
const filteredCustomers = computed(() => {
  return mockData.customers.list
})

const totalPages = computed(() => {
  return Math.ceil(total.value / pageSize.value)
})

const selectAll = computed({
  get: () => selectedItems.value.length === filteredCustomers.value.length,
  set: (value) => {
    selectedItems.value = value ? filteredCustomers.value.map(c => c.id) : []
  }
})

// 方法
const handleSearch = () => {
  currentPage.value = 1
  fetchCustomers()
}

const handleSort = (prop) => {
  if (sortKey.value === prop) {
    sortOrder.value = sortOrder.value === 'asc' ? 'desc' : 'asc'
  } else {
    sortKey.value = prop
    sortOrder.value = 'asc'
  }
  const sortedCustomers = [...filteredCustomers.value]
  sortedCustomers.sort((a, b) => {
    const aValue = a[prop]
    const bValue = b[prop]
    if (sortOrder.value === 'asc') {
      return aValue > bValue ? 1 : -1
    } else {
      return aValue < bValue ? 1 : -1
    }
  })
  filteredCustomers.value = sortedCustomers
}

const handleSizeChange = () => {
  currentPage.value = 1
  fetchCustomers()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchCustomers()
}

const handleFileChange = (event) => {
  const file = event.target.files[0]
  if (file) {
    // 处理文件上传
  }
}

const handleExport = () => {
  // 实现导出逻辑
}

const handleBatchEdit = () => {
  // 实现批量编辑逻辑
}

const handleBatchDelete = () => {
  // 实现批量删除逻辑
}

const showDetail = (customer) => {
  // 实现查看详情逻辑
}

const handleEdit = (customer) => {
  isEdit.value = true
  addForm.value = { ...customer }
  showAddDialog.value = true
}

const handleDelete = (customer) => {
  // 实现删除逻辑
}

const handleSubmit = () => {
  // 实现表单提交逻辑
}

const getLevelClass = (level) => {
  return {
    'bg-purple-100 text-purple-800': level === 'vip',
    'bg-gray-100 text-gray-800': level === 'normal'
  }
}

const getStatusClass = (status) => {
  return {
    'bg-green-100 text-green-800': status === 'active',
    'bg-red-100 text-red-800': status === 'inactive'
  }
}

const getLevelLabel = (level) => {
  return customerLevels.find(l => l.value === level)?.label || level
}

const getStatusLabel = (status) => {
  return customerStatuses.find(s => s.value === status)?.label || status
}

const formatDateTime = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 图表相关方法
const initAnalysisChart = () => {
  if (!analysisChart.value) return
  
  const chart = echarts.init(analysisChart.value)
  
  const updateChart = () => {
    let option = {}
    
    switch (analysisType.value) {
      case 'level':
        option = {
          title: {
            text: '客户等级分布',
            left: 'center'
          },
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          legend: {
            orient: 'vertical',
            left: 'left',
            data: ['VIP客户', '普通客户']
          },
          series: [
            {
              name: '客户等级',
              type: 'pie',
              radius: ['50%', '70%'],
              avoidLabelOverlap: false,
              itemStyle: {
                borderRadius: 10,
                borderColor: '#fff',
                borderWidth: 2
              },
              label: {
                show: false,
                position: 'center'
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: '20',
                  fontWeight: 'bold'
                }
              },
              labelLine: {
                show: false
              },
              data: [
                { value: mockData.statistics.vipCustomers, name: 'VIP客户' },
                { value: mockData.statistics.totalCustomers - mockData.statistics.vipCustomers, name: '普通客户' }
              ]
            }
          ]
        }
        break
        
      case 'status':
        option = {
          title: {
            text: '客户状态分布',
            left: 'center'
          },
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          legend: {
            orient: 'vertical',
            left: 'left',
            data: ['活跃客户', '非活跃客户']
          },
          series: [
            {
              name: '客户状态',
              type: 'pie',
              radius: ['50%', '70%'],
              avoidLabelOverlap: false,
              itemStyle: {
                borderRadius: 10,
                borderColor: '#fff',
                borderWidth: 2
              },
              label: {
                show: false,
                position: 'center'
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: '20',
                  fontWeight: 'bold'
                }
              },
              labelLine: {
                show: false
              },
              data: [
                { value: mockData.statistics.activeCustomers, name: '活跃客户' },
                { value: mockData.statistics.totalCustomers - mockData.statistics.activeCustomers, name: '非活跃客户' }
              ]
            }
          ]
        }
        break
        
      case 'growth':
        option = {
          title: {
            text: '客户增长趋势',
            left: 'center'
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          legend: {
            data: ['新增客户']
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              name: '新增客户',
              type: 'line',
              smooth: true,
              data: [5, 8, 10, 12, 15, 18, 20, 22, 25, 28, 30, 35],
              itemStyle: {
                color: '#409EFF'
              },
              areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  {
                    offset: 0,
                    color: 'rgba(64,158,255,0.3)'
                  },
                  {
                    offset: 1,
                    color: 'rgba(64,158,255,0.1)'
                  }
                ])
              }
            }
          ]
        }
        break
    }
    
    // 在设置新选项之前，先清除之前的图表
    chart.clear()
    chart.setOption(option)
  }
  
  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    chart.resize()
  })
  
  // 监听分析类型变化
  watch(analysisType, () => {
    updateChart()
  })
  
  // 初始化图表
  updateChart()
}

// 生命周期钩子
onMounted(() => {
  fetchCustomers()
  initAnalysisChart()
})

onUnmounted(() => {
  if (analysisChart.value) {
    echarts.dispose(analysisChart.value)
  }
})

// 数据获取
const fetchCustomers = async () => {
  try {
    loading.value = true
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 500))
    total.value = mockData.customers.total
  } catch (error) {
    console.error('获取数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 添加 watch 监听对话框显示状态
watch(showAnalysisDialog, (newVal) => {
  if (newVal) {
    // 对话框显示时初始化图表
    nextTick(() => {
      initAnalysisChart()
    })
  }
})
</script> 