<template>
  <div>
    <h1>无纸化服务</h1>
    
    <!-- 搜索和操作栏 -->
    <a-card style="margin-bottom: 16px;">
      <div style="display: flex; flex-wrap: wrap; gap: 16px; align-items: center;">
        <a-input v-model:value="searchKeyword" placeholder="输入服务名称或编号" style="width: 250px;">
          <template #prefix>
            <span class="iconfont icon-sousuo"></span>
          </template>
        </a-input>
        
        <a-select v-model:value="serviceTypeFilter" placeholder="服务类型" style="width: 120px;">
          <a-select-option value="">全部</a-select-option>
          <a-select-option value="approval">审批服务</a-select-option>
          <a-select-option value="certificate">证件办理</a-select-option>
          <a-select-option value="report">报告申请</a-select-option>
          <a-select-option value="consultation">咨询服务</a-select-option>
        </a-select>
        
        <a-select v-model:value="statusFilter" placeholder="服务状态" style="width: 120px;">
          <a-select-option value="">全部</a-select-option>
          <a-select-option value="active">启用</a-select-option>
          <a-select-option value="inactive">禁用</a-select-option>
          <a-select-option value="developing">开发中</a-select-option>
        </a-select>
        
        <a-button type="primary" @click="handleSearch" style="margin-left: auto;">
          <span class="iconfont icon-sousuo"></span> 搜索
        </a-button>
        
        <a-button type="default" @click="handleReset">重置</a-button>
        
        <a-button type="primary" danger @click="handleAddService">
          <span class="iconfont icon-tianjia"></span> 新增服务
        </a-button>
      </div>
    </a-card>
    
    <!-- 数据统计卡片 -->
    <a-row gutter={24} style="margin-bottom: 16px;">
      <a-col :span="6">
        <a-statistic title="服务总数" :value="totalServices" suffix="项" />
      </a-col>
      <a-col :span="6">
        <a-statistic title="已启用服务" :value="activeServices" suffix="项" :valueStyle="{ color: '#52c41a' }" />
      </a-col>
      <a-col :span="6">
        <a-statistic title="本月服务量" :value="monthlyVolume" suffix="次" :valueStyle="{ color: '#1890ff' }" />
      </a-col>
      <a-col :span="6">
        <a-statistic title="平均办理时长" :value="avgProcessingTime" suffix="天" />
      </a-col>
    </a-row>
    
    <!-- 服务量统计图表 -->
    <a-card title="服务量趋势统计" style="margin-bottom: 16px;">
      <div style="height: 300px;" ref="serviceChartRef"></div>
    </a-card>
    
    <!-- 服务列表 -->
    <a-card>
      <a-table
        :columns="columns"
        :data-source="servicesData"
        :pagination="pagination"
        row-key="id"
        :row-selection="{ selectedRowKeys, onChange: onSelectChange }"
     :scroll="{ x: 'max-content' }"
      >
        <!-- 状态列 -->
        <template #bodyCell:status="{ record }">
          <a-tag :color="getStatusColor(record.status)">{{ getStatusText(record.status) }}</a-tag>
        </template>
        
        <!-- 操作列 -->
        <template #bodyCell:action="{ record }">
          <div style="display: flex; gap: 8px;">
            <a-button size="small" @click="handleView(record)">查看</a-button>
            <a-button size="small" type="primary" @click="handleEdit(record)">编辑</a-button>
            <a-button size="small" danger @click="handleDelete(record.id)">删除</a-button>
            <a-button size="small" @click="handleToggleStatus(record)">
              {{ record.status === 'active' ? '禁用' : '启用' }}
            </a-button>
          </div>
        </template>
      </a-table>
    </a-card>
    
    <!-- 新增/编辑服务模态框 -->
    <a-modal
      v-model:open="isAddEditModalOpen"
      title="新增/编辑无纸化服务"
      :footer="null"
      width={700}
    >
      <a-form
        :model="currentService"
        layout="vertical"
        style="max-width: 500px; margin: 0 auto;"
      >
        <a-row gutter={24}>
          <a-col :span="12">
            <a-form-item label="服务编号" name="code" :rules="[{ required: true, message: '请输入服务编号' }]">
              <a-input v-model:value="currentService.code" placeholder="请输入服务编号" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="服务名称" name="name" :rules="[{ required: true, message: '请输入服务名称' }]">
              <a-input v-model:value="currentService.name" placeholder="请输入服务名称" />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row gutter={24}>
          <a-col :span="12">
            <a-form-item label="服务类型" name="serviceType" :rules="[{ required: true, message: '请选择服务类型' }]">
              <a-select v-model:value="currentService.serviceType" placeholder="请选择服务类型">
                <a-select-option value="approval">审批服务</a-select-option>
                <a-select-option value="certificate">证件办理</a-select-option>
                <a-select-option value="report">报告申请</a-select-option>
                <a-select-option value="consultation">咨询服务</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="服务状态" name="status" :rules="[{ required: true, message: '请选择服务状态' }]">
              <a-select v-model:value="currentService.status" placeholder="请选择服务状态">
                <a-select-option value="active">启用</a-select-option>
                <a-select-option value="inactive">禁用</a-select-option>
                <a-select-option value="developing">开发中</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row gutter={24}>
          <a-col :span="12">
            <a-form-item label="预计办理时长" name="estimatedTime" :rules="[{ required: true, message: '请输入预计办理时长' }]">
              <a-input-number v-model:value="currentService.estimatedTime" min={1} style="width: 100%;" placeholder="预计办理时长" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="收费标准" name="feeStandard">
              <a-input v-model:value="currentService.feeStandard" placeholder="请输入收费标准" />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-form-item label="服务简介" name="description" :rules="[{ required: true, message: '请输入服务简介' }]">
          <a-input.TextArea v-model:value="currentService.description" placeholder="请输入服务简介" :rows="3" />
        </a-form-item>
        
        <a-form-item label="办理流程" name="process" :rules="[{ required: true, message: '请输入办理流程' }]">
          <a-input.TextArea v-model:value="currentService.process" placeholder="请输入办理流程" :rows="4" />
        </a-form-item>
        
        <a-form-item label="所需材料" name="requiredMaterials" :rules="[{ required: true, message: '请输入所需材料' }]">
          <a-input.TextArea v-model:value="currentService.requiredMaterials" placeholder="请输入所需材料" :rows="3" />
        </a-form-item>
        
        <a-form-item label="注意事项" name="notes">
          <a-input.TextArea v-model:value="currentService.notes" placeholder="请输入注意事项" :rows="2" />
        </a-form-item>
        
        <div style="display: flex; justify-content: flex-end; gap: 16px;">
          <a-button @click="isAddEditModalOpen = false">取消</a-button>
          <a-button type="primary" @click="handleSave">保存</a-button>
        </div>
      </a-form>
    </a-modal>
    
    <!-- 查看服务详情模态框 -->
    <a-modal
      v-model:open="isViewModalOpen"
      title="服务详情"
      :footer="null"
      width={800}
    >
      <div v-if="viewService" class="service-detail">
        <div class="detail-row">
          <div class="detail-label">服务编号：</div>
          <div class="detail-value">{{ viewService.code }}</div>
        </div>
        <div class="detail-row">
          <div class="detail-label">服务名称：</div>
          <div class="detail-value">{{ viewService.name }}</div>
        </div>
        <div class="detail-row">
          <div class="detail-label">服务类型：</div>
          <div class="detail-value">{{ getServiceTypeText(viewService.serviceType) }}</div>
        </div>
        <div class="detail-row">
          <div class="detail-label">服务状态：</div>
          <div class="detail-value">
            <a-tag :color="getStatusColor(viewService.status)">{{ getStatusText(viewService.status) }}</a-tag>
          </div>
        </div>
        <div class="detail-row">
          <div class="detail-label">预计办理时长：</div>
          <div class="detail-value">{{ viewService.estimatedTime }} 天</div>
        </div>
        <div class="detail-row">
          <div class="detail-label">收费标准：</div>
          <div class="detail-value">{{ viewService.feeStandard || '免费' }}</div>
        </div>
        <div class="detail-row">
          <div class="detail-label">服务简介：</div>
          <div class="detail-value">{{ viewService.description }}</div>
        </div>
        <div class="detail-row">
          <div class="detail-label">办理流程：</div>
          <div class="detail-value">{{ viewService.process }}</div>
        </div>
        <div class="detail-row">
          <div class="detail-label">所需材料：</div>
          <div class="detail-value">{{ viewService.requiredMaterials }}</div>
        </div>
        <div class="detail-row">
          <div class="detail-label">注意事项：</div>
          <div class="detail-value">{{ viewService.notes || '无' }}</div>
        </div>
        <div class="detail-row">
          <div class="detail-label">累计办理次数：</div>
          <div class="detail-value">{{ viewService.processedCount || 0 }} 次</div>
        </div>
        <div class="detail-row">
          <div class="detail-label">平均办理时长：</div>
          <div class="detail-value">{{ viewService.averageTime || 0 }} 天</div>
        </div>
      </div>
      <div style="text-align: center; margin-top: 24px;">
        <a-button @click="isViewModalOpen = false">关闭</a-button>
      </div>
    </a-modal>
    
    <!-- 确认对话框 -->
    <a-popconfirm
      v-model:open="isConfirmModalOpen"
      title="确认操作"
      :description="confirmMessage"
      ok-text="确认"
      cancel-text="取消"
      @confirm="handleConfirmAction"
    >
      <template #reference>
        <!-- 这里是空的，通过其他按钮触发 -->
      </template>
    </a-popconfirm>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import * as echarts from 'echarts'

// 搜索条件
const searchKeyword = ref('')
const serviceTypeFilter = ref('')
const statusFilter = ref('')

// 统计数据
const totalServices = ref(32)
const activeServices = ref(26)
const monthlyVolume = ref(856)
const avgProcessingTime = ref(2.5)

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total) => `共 ${total} 条记录`
})

// 选中的行
const selectedRowKeys = ref([])
const onSelectChange = (newSelectedRowKeys) => {
  selectedRowKeys.value = newSelectedRowKeys
}

// 图表引用
const serviceChartRef = ref(null)

// 模态框状态
const isAddEditModalOpen = ref(false)
const isViewModalOpen = ref(false)
const isConfirmModalOpen = ref(false)
const confirmMessage = ref('')
const confirmAction = ref('')
const confirmTargetId = ref('')

// 当前编辑的服务
const currentService = reactive({
  id: '',
  code: '',
  name: '',
  serviceType: '',
  status: 'active',
  estimatedTime: 3,
  feeStandard: '',
  description: '',
  process: '',
  requiredMaterials: '',
  notes: '',
  processedCount: 0,
  averageTime: 0
})

// 查看的服务
const viewService = ref(null)

// 服务列表数据
const servicesData = ref([
  {
    id: '1',
    code: 'S001',
    name: '动物防疫条件合格证办理',
    serviceType: 'certificate',
    status: 'active',
    estimatedTime: 5,
    feeStandard: '免费',
    description: '为养殖场提供动物防疫条件合格证的申请、审核和发放服务',
    process: '1. 提交申请；2. 资料审核；3. 现场勘查；4. 审核通过；5. 发放证件',
    requiredMaterials: '1. 申请表；2. 养殖场平面图；3. 防疫制度；4. 负责人身份证明；5. 营业执照',
    notes: '现场勘查需提前3天预约',
    processedCount: 256,
    averageTime: 4.2
  },
  {
    id: '2',
    code: 'S002',
    name: '种畜禽生产经营许可证办理',
    serviceType: 'certificate',
    status: 'active',
    estimatedTime: 7,
    feeStandard: '免费',
    description: '为种畜禽养殖场提供生产经营许可证的申请、审核和发放服务',
    process: '1. 提交申请；2. 资料审核；3. 现场评审；4. 审核通过；5. 发放证件',
    requiredMaterials: '1. 申请表；2. 养殖场资质证明；3. 种畜禽来源证明；4. 技术人员资质；5. 防疫条件证明',
    notes: '需提供种畜禽质量检测报告',
    processedCount: 128,
    averageTime: 6.8
  },
  {
    id: '3',
    code: 'S003',
    name: '养殖场建设项目备案',
    serviceType: 'approval',
    status: 'active',
    estimatedTime: 10,
    feeStandard: '免费',
    description: '为新建、扩建、改建养殖场提供项目备案服务',
    process: '1. 提交备案申请；2. 资料审核；3. 现场核查；4. 备案登记；5. 公示',
    requiredMaterials: '1. 备案申请表；2. 项目可行性研究报告；3. 选址意见书；4. 环境影响评价文件；5. 土地使用证明',
    notes: '大型养殖场需提供环评批复',
    processedCount: 95,
    averageTime: 9.3
  },
  {
    id: '4',
    code: 'S004',
    name: '畜禽标识代码申请',
    serviceType: 'approval',
    status: 'active',
    estimatedTime: 3,
    feeStandard: '免费',
    description: '为养殖场提供畜禽标识代码的申请和发放服务',
    process: '1. 提交申请；2. 资料审核；3. 发放标识代码',
    requiredMaterials: '1. 申请表；2. 养殖场资质证明；3. 负责人身份证明',
    notes: '无',
    processedCount: 487,
    averageTime: 2.1
  },
  {
    id: '5',
    code: 'S005',
    name: '动物检疫申报',
    serviceType: 'approval',
    status: 'active',
    estimatedTime: 1,
    feeStandard: '按规定收费',
    description: '为畜禽出栏、运输提供检疫申报和检疫合格证明发放服务',
    process: '1. 网上申报；2. 现场检疫；3. 合格发证',
    requiredMaterials: '1. 检疫申报单；2. 免疫记录；3. 养殖档案；4. 运输工具消毒证明',
    notes: '需提前24小时申报',
    processedCount: 1245,
    averageTime: 0.8
  },
  {
    id: '6',
    code: 'S006',
    name: '养殖污染防治技术指导',
    serviceType: 'consultation',
    status: 'active',
    estimatedTime: 2,
    feeStandard: '免费',
    description: '为养殖场提供养殖污染防治技术咨询和指导服务',
    process: '1. 提交咨询申请；2. 技术专家评估；3. 提供技术方案；4. 现场指导',
    requiredMaterials: '1. 咨询申请表；2. 养殖场基本情况；3. 现有污染处理设施说明',
    notes: '可预约上门服务',
    processedCount: 76,
    averageTime: 3.5
  },
  {
    id: '7',
    code: 'S007',
    name: '畜禽产品质量安全检测报告申请',
    serviceType: 'report',
    status: 'active',
    estimatedTime: 5,
    feeStandard: '按检测项目收费',
    description: '为养殖户提供畜禽产品质量安全检测和报告出具服务',
    process: '1. 提交申请；2. 样品采集；3. 实验室检测；4. 出具报告',
    requiredMaterials: '1. 检测申请表；2. 样品标识；3. 样品来源说明',
    notes: '检测报告有效期为6个月',
    processedCount: 168,
    averageTime: 4.7
  },
  {
    id: '8',
    code: 'S008',
    name: '养殖技术培训申请',
    serviceType: 'consultation',
    status: 'active',
    estimatedTime: 7,
    feeStandard: '免费',
    description: '为养殖户提供养殖技术培训服务',
    process: '1. 提交培训申请；2. 制定培训计划；3. 开展培训；4. 培训考核',
    requiredMaterials: '1. 培训申请表；2. 参训人员名单；3. 培训需求说明',
    notes: '可根据需求定制培训内容',
    processedCount: 324,
    averageTime: 6.2
  },
  {
    id: '9',
    code: 'S009',
    name: '畜牧业扶持政策咨询',
    serviceType: 'consultation',
    status: 'active',
    estimatedTime: 1,
    feeStandard: '免费',
    description: '为养殖户提供畜牧业相关扶持政策的咨询服务',
    process: '1. 提交咨询；2. 政策解读；3. 提供建议',
    requiredMaterials: '无',
    notes: '可通过线上或电话咨询',
    processedCount: 986,
    averageTime: 0.5
  },
  {
    id: '10',
    code: 'S010',
    name: '畜禽养殖保险理赔申请',
    serviceType: 'approval',
    status: 'inactive',
    estimatedTime: 15,
    feeStandard: '免费',
    description: '为参保养殖户提供养殖保险理赔申请和处理服务',
    process: '1. 提交理赔申请；2. 现场勘查；3. 损失评估；4. 理赔核算；5. 赔付',
    requiredMaterials: '1. 理赔申请表；2. 保险单；3. 损失证明材料；4. 其他相关证明',
    notes: '需在事故发生后48小时内报案',
    processedCount: 0,
    averageTime: 0
  }
])

// 表格列定义
const columns = [
  {
    title: '服务编号',
    dataIndex: 'code',
    key: 'code',
    width: 100
  },
  {
    title: '服务名称',
    dataIndex: 'name',
    key: 'name',
    ellipsis: true
  },
  {
    title: '服务类型',
    dataIndex: 'serviceType',
    key: 'serviceType',
    width: 100,
    customRender: ({ text }) => getServiceTypeText(text)
  },
  {
    title: '预计办理时长',
    dataIndex: 'estimatedTime',
    key: 'estimatedTime',
    width: 100,
    customRender: ({ text }) => `${text} 天`
  },
  {
    title: '收费标准',
    dataIndex: 'feeStandard',
    key: 'feeStandard',
    width: 100,
    customRender: ({ text }) => text || '免费'
  },
  {
    title: '服务状态',
    dataIndex: 'status',
    key: 'status',
    width: 80
  },
  {
    title: '累计办理次数',
    dataIndex: 'processedCount',
    key: 'processedCount',
    width: 100
  },
  {
    title: '操作',
    key: 'action',
    width: 180,
    fixed: 'right'
  }
]

// 获取状态颜色
const getStatusColor = (status) => {
  switch (status) {
    case 'active': return 'green'
    case 'inactive': return 'default'
    case 'developing': return 'orange'
    default: return 'default'
  }
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'active': return '启用'
    case 'inactive': return '禁用'
    case 'developing': return '开发中'
    default: return status
  }
}

// 获取服务类型文本
const getServiceTypeText = (serviceType) => {
  switch (serviceType) {
    case 'approval': return '审批服务'
    case 'certificate': return '证件办理'
    case 'report': return '报告申请'
    case 'consultation': return '咨询服务'
    default: return serviceType
  }
}

// 搜索处理
const handleSearch = () => {
  console.log('搜索条件:', {
    keyword: searchKeyword.value,
    serviceType: serviceTypeFilter.value,
    status: statusFilter.value
  })
  // 这里应该有实际的搜索逻辑
  // 模拟搜索后的总数
  pagination.total = servicesData.value.length
}

// 重置处理
const handleReset = () => {
  searchKeyword.value = ''
  serviceTypeFilter.value = ''
  statusFilter.value = ''
  selectedRowKeys.value = []
}

// 新增服务
const handleAddService = () => {
  // 重置当前服务数据
  Object.assign(currentService, {
    id: '',
    code: '',
    name: '',
    serviceType: '',
    status: 'active',
    estimatedTime: 3,
    feeStandard: '',
    description: '',
    process: '',
    requiredMaterials: '',
    notes: '',
    processedCount: 0,
    averageTime: 0
  })
  isAddEditModalOpen.value = true
}

// 编辑服务
const handleEdit = (record) => {
  // 复制记录数据到当前服务
  Object.assign(currentService, JSON.parse(JSON.stringify(record)))
  isAddEditModalOpen.value = true
}

// 查看服务
const handleView = (record) => {
  viewService.value = JSON.parse(JSON.stringify(record))
  isViewModalOpen.value = true
}

// 删除服务 - 弹出确认对话框
const handleDelete = (id) => {
  confirmMessage.value = '确定要删除该服务吗？'
  confirmAction.value = 'delete'
  confirmTargetId.value = id
  isConfirmModalOpen.value = true
}

// 切换服务状态 - 弹出确认对话框
const handleToggleStatus = (record) => {
  const newStatus = record.status === 'active' ? 'inactive' : 'active'
  confirmMessage.value = `确定要${newStatus === 'active' ? '启用' : '禁用'}该服务吗？`
  confirmAction.value = 'toggleStatus'
  confirmTargetId.value = record.id
  isConfirmModalOpen.value = true
}

// 确认操作
const handleConfirmAction = () => {
  if (confirmAction.value === 'delete') {
    console.log('删除服务:', confirmTargetId.value)
    // 这里应该有实际的删除逻辑
    // 模拟删除成功
    alert(`成功删除服务ID: ${confirmTargetId.value}`)
  } else if (confirmAction.value === 'toggleStatus') {
    console.log('切换服务状态:', confirmTargetId.value)
    // 这里应该有实际的状态切换逻辑
    // 模拟切换成功
    alert(`成功切换服务状态`)
  }
  isConfirmModalOpen.value = false
}

// 保存服务
const handleSave = () => {
  console.log('保存服务:', currentService)
  // 这里应该有实际的保存逻辑
  // 模拟保存成功
  isAddEditModalOpen.value = false
  alert('保存成功')
}

// 初始化服务量趋势图表
const initServiceChart = () => {
  if (!serviceChartRef.value) return
  
  const chart = echarts.init(serviceChartRef.value)
  
  const option = {
    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',
        stack: '总量',
        areaStyle: {},
        emphasis: {
          focus: 'series'
        },
        data: [120, 132, 101, 134, 90, 230, 210, 230, 180, 230, 210, 120]
      },
      {
        name: '证件办理',
        type: 'line',
        stack: '总量',
        areaStyle: {},
        emphasis: {
          focus: 'series'
        },
        data: [220, 182, 191, 234, 290, 330, 310, 210, 230, 280, 270, 220]
      },
      {
        name: '报告申请',
        type: 'line',
        stack: '总量',
        areaStyle: {},
        emphasis: {
          focus: 'series'
        },
        data: [150, 232, 201, 154, 190, 330, 410, 310, 280, 320, 340, 300]
      },
      {
        name: '咨询服务',
        type: 'line',
        stack: '总量',
        areaStyle: {},
        emphasis: {
          focus: 'series'
        },
        data: [320, 332, 301, 334, 390, 330, 320, 350, 320, 340, 380, 390]
      }
    ]
  }
  
  chart.setOption(option)
  
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 组件挂载时初始化图表
onMounted(() => {
  setTimeout(() => {
    initServiceChart()
  }, 100)
})

// 初始化数据
pagination.total = servicesData.value.length
</script>

<style scoped>
  .service-detail {
    padding: 16px;
  }
  
  .detail-row {
    display: flex;
    margin-bottom: 16px;
    align-items: flex-start;
  }
  
  .detail-label {
    width: 120px;
    font-weight: bold;
    color: #666;
  }
  
  .detail-value {
    flex: 1;
    color: #333;
  }
</style>