BusinessRulesManagement.vue 15.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
<template>
  <div class="space-y-6">
    <!-- 页面标题和操作区 -->
    <div class="flex items-center justify-between">
      <h3 class="text-neutral-900 text-[20px] font-bold">业务酬金管理</h3>
      <div class="flex">
        <el-button 
          @click="handleDownloadTemplate"
          class="h-10"
        >
          <Download class="h-4 w-4 mr-1" />
          下载模板
        </el-button>
        <el-button 
          @click="handleBatchUpload"
          class="h-10"
        >
          <Upload class="h-4 w-4 mr-1" />
          批量上传
        </el-button>
        <el-button 
          type="primary"
          @click="handleOpenDialog()"
          class="h-10"
        >
          <Plus class="h-4 w-4 mr-1" />
          新建业务
        </el-button>
      </div>
    </div>

    <!-- 隐藏的文件输入框 -->
    <input
      ref="fileInputRef"
      type="file"
      accept=".csv,.xlsx"
      @change="handleFileChange"
      style="display: none"
    />


    <!-- 业务规则表格 -->
    <el-card class="p-5">
      <div class="rounded-lg overflow-hidden">
        <el-table
          :data="paginatedRules"
          stripe
          class="w-full"
          :header-cell-style="{ backgroundColor: '#f3f4f6', color: '#374151', fontWeight: '500', borderBottom: '1px solid #e5e7eb' }"
          row-class-name="hover:bg-muted/30"
        >
          <el-table-column prop="jobId" label="业务代码" min-width="120">
            <template #default="{ row }">
              <span class="font-mono">{{ row.jobId }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="jobName" label="业务名称" min-width="150" />
          <el-table-column label="预计酬金(元)" min-width="120">
            <template #default="{ row }">
              ¥{{ row.totalPrice.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column label="业务状态" min-width="100">
            <template #default="{ row }">
              <el-tag
                :type="row.status === 1 ? 'success' : 'info'"
                class="border-0"
              >
                {{ row.status===1?'生效中':'已停用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" min-width="150">
            <template #default="{ row }">
              {{ $utils.detailTime(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="updateTime" label="更新时间" min-width="150">
            <template #default="{ row }">
              {{ $utils.detailTime(row.updateTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" min-width="200" fixed="right">
            <template #default="{ row }">
              <div class="flex items-center gap-4">
                <button
                  @click="handleOpenDialog(row)"
                  :disabled="row.status === '已停用'"
                  class="text-brand-primary hover:text-brand-primary-hover disabled:text-neutral-400 disabled:cursor-not-allowed bg-transparent border-none cursor-pointer text-sm font-normal p-0"
                >
                  编辑
                </button>
                <button
                  @click="handleDeleteConfirm(row.id)"
                  class="text-brand-primary hover:text-brand-primary-hover bg-transparent border-none cursor-pointer text-sm font-normal p-0"
                >
                  删除
                </button>
              </div>
            </template>
          </el-table-column>
          
          <!-- 空状态 -->
          <template #empty>
            <div class="text-center py-12 text-neutral-500">
              {{ searchKeyword ? '没有找到匹配的业务' : '暂无业务规则' }}
            </div>
          </template>
        </el-table>
      </div>
    </el-card>

    <!-- 新建/编辑业务规则对话框 -->
    <el-dialog
      v-model="isDialogOpen"
      :title="editingRule ? '编辑业务规则' : '新建业务规则'"
      width="500px"
      :close-on-click-modal="false"
      class="business-rule-dialog"
    >
      <div class="space-y-4">
        <div>
          <label class="block text-sm font-medium text-neutral-700 mb-2">
            业务代码 <span class="text-red-500">*</span>
          </label>
          <el-input
            v-model="formData.businessCode"
            placeholder="请输入业务代码,如:B5G001"
          />
        </div>
        <div>
          <label class="block text-sm font-medium text-neutral-700 mb-2">
            业务名称 <span class="text-red-500">*</span>
          </label>
          <el-input
            v-model="formData.businessName"
            placeholder="请输入业务名称,如:5G套餐办理"
          />
        </div>
        <div>
          <label class="block text-sm font-medium text-neutral-700 mb-2">
            预计酬金(元) <span class="text-red-500">*</span>
          </label>
          <el-input-number
            v-model="formData.estimatedReward"
            :min="0"
            :step="0.01"
            :precision="2"
            placeholder="请输入预计酬金"
            class="w-full"
          />
        </div>
        <div>
          <label class="block text-sm font-medium text-neutral-700 mb-2">状态</label>
          <el-radio-group v-model="formData.status">
            <el-radio label="1">生效</el-radio>
            <el-radio label="0">停用</el-radio>
          </el-radio-group>
        </div>
      </div>
      
      <template #footer>
        <div class="flex gap-2 justify-end">
          <el-button @click="handleCloseDialog">取消</el-button>
          <el-button type="primary" @click="handleSubmit">
            {{ editingRule ? '保存' : '创建' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 批量上传结果对话框 -->
    <el-dialog
      v-model="showUploadResult"
      title="批量上传结果"
      width="600px"
      class="upload-result-dialog"
    >
      <div class="space-y-4">
        <div class="flex items-center gap-4 p-4 bg-neutral-50 rounded-lg">
          <div class="flex items-center gap-2 flex-1">
            <CheckCircle class="h-5 w-5 text-green-500" />
            <span>正常</span>
            <span class="text-green-500">{{ uploadResult?.success || 0 }}</span>
            <span></span>
          </div>
          <div class="flex items-center gap-2 flex-1">
            <AlertCircle class="h-5 w-5 text-red-500" />
            <span>错误</span>
            <span class="text-red-500">{{ uploadResult?.failed || 0 }}</span>
            <span></span>
          </div>
        </div>

        <div v-if="uploadResult && uploadResult.errors.length > 0" class="space-y-2">
          <div class="text-sm text-neutral-600">错误详情:</div>
          <div class="max-h-60 overflow-y-auto border border-neutral-200 rounded p-3 space-y-1 bg-neutral-50">
            <div
              v-for="(error, index) in uploadResult.errors"
              :key="index"
              class="text-sm text-red-500"
            >
              {{ error }}
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <el-button type="primary" @click="submitExcelData">{{(uploadResult?.failed || 0)>0?'确定':'提交'}}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, nextTick ,onMounted,getCurrentInstance} from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Download, Upload, Plus, Search, CheckCircle, AlertCircle } from 'lucide-vue-next'
// import * as XLSX from 'xlsx' // 暂时注释掉,因为没有安装xlsx包
const { $api,$utils } = getCurrentInstance()!.appContext.config.globalProperties
// 业务规则类型定义
interface BusinessRule {
  id: string
  jobId: string
  jobName: string
  totalPrice: number
  status: '1' | '0'
  createTime?: string
  updateTime?: string
}

interface UploadResult {
  success: number
  failed: number
  errors: string[]
}

// Props
interface Props {
  rules: BusinessRule[]
}

const props = withDefaults(defineProps<Props>(), {
  rules: () => []
})

onMounted(() => {
  queryRewardList()
})
const queryRewardList = async ()=>{
  try {
    const response = await $api.queryAllRewardList({})
    
    if (response.c === 0 && response.d) {
      paginatedRules.value = response.d
    } else {
      
    }
  } catch (error) {
    
  }
}

// Emits
const emit = defineEmits<{
  add: [rule: Omit<BusinessRule, 'id' | 'createTime'>]
  update: [id: string, updates: Partial<BusinessRule>]
  toggleStatus: [id: string]
  delete: [id: string]
}>()

// 响应式数据
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const isDialogOpen = ref(false)
const editingRule = ref<BusinessRule | null>(null)
const uploadResult = ref<UploadResult | null>(null)
const showUploadResult = ref(false)
const fileInputRef = ref<HTMLInputElement>()

const formData = ref({
  businessCode: '',
  businessName: '',
  estimatedReward: 0,
  status: '1'
})

const paginatedRules = ref([])

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

const handleOpenDialog = (rule?: BusinessRule) => {
  if (rule) {
    editingRule.value = rule
    formData.value = {
      businessCode: rule.jobId,
      businessName: rule.jobName,
      estimatedReward: rule.totalPrice,
      status: rule.status+''
    }
  } else {
    editingRule.value = null
    formData.value = {
      businessCode: '',
      businessName: '',
      estimatedReward: 0,
      status: '1'
    }
  }
  isDialogOpen.value = true
}

const handleCloseDialog = () => {
  isDialogOpen.value = false
  editingRule.value = null
  formData.value = {
    businessCode: '',
    businessName: '',
    estimatedReward: 0,
    status: '1'
  }
}

const handleSubmit = async () => {
  if (!formData.value.businessCode.trim() || !formData.value.businessName.trim() || formData.value.estimatedReward <= 0) {
    ElMessage.error('请填写完整信息')
    return
  }

  try {
    const response = await $api.updateReward({
      id: editingRule.value?editingRule.value.id:'',
      jobName: formData.value.businessName,
      jobId: formData.value.businessCode,
      totalPrice: formData.value.estimatedReward,
      status: formData.value.status
    })
    if(response.c === 0){
      ElMessage.success('新建成功')

      queryRewardList()
    }else{
      ElMessage.error(response.m)
    }
  } catch (error) {
    ElMessage.error('文件解析失败,请检查文件格式是否正确')
  }

  handleCloseDialog()
}

const handleToggleStatus = (id: string) => {
  emit('toggleStatus', id)
}

const handleDeleteConfirm = async (id: string) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这条业务规则吗?此操作无法撤销。',
      '确认删除',
      {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await $api.delReward({
      id
    })

    if(response.c === 0){
      ElMessage.success('删除成功')
      queryRewardList()
    }else{
      ElMessage.error(response.m || '删除失败')
    }
  } catch {
    // 用户取消删除
  }
}

const handleDownloadTemplate = () => {
  try {
    // 创建下载链接
    const link = document.createElement('a')
    // 使用相对路径,确保本地和线上都能正常访问
    link.href = './static/file/rule_tem.xlsx'
    link.download = '业务酬金批量上传模板.xlsx'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)

    ElMessage.success('模板下载成功')
  } catch (error) {
    console.error('下载模板失败:', error)
    ElMessage.error('模板下载失败,请稍后重试')
  }
}

const handleBatchUpload = () => {
  fileInputRef.value?.click()
}

const handleFileChange = async (e: Event) => {
  const target = e.target as HTMLInputElement
  const file = target.files?.[0]
  if (!file) return

  // 重置文件输入框
  target.value = ''

  // 验证文件大小(2MB)
  const maxSize = 2 * 1024 * 1024
  if (file.size > maxSize) {
    ElMessage.error('文件大小超过2MB限制,请压缩后重新上传')
    return
  }

  // 验证文件格式
  const fileName = file.name.toLowerCase()
  if (!fileName.endsWith('.csv') && !fileName.endsWith('.xlsx')) {
    ElMessage.error('目前仅支持 csv和xlsx 格式的文件')
    return
  }

  try {
      const fd = new FormData()
      fd.append('file', file)

      const response = await $api.uploadReward(fd)
      if(response.c === 0){
        processUploadData(response.d.list)
      }else{
        ElMessage.error(response.m)
      }
  } catch (error) {
    ElMessage.error('文件解析失败,请检查文件格式是否正确')
  }
}

const submitExcelData = async ()=>{
  if((uploadResult.value?.failed || 0) > 0){
    showUploadResult.value = false
    return 
  }

  try {
      const response = await $api.uploadRewardSave({
        list: excelShowdData.value
      })
      if(response.c === 0){
        ElMessage.success('上传成功')
        showUploadResult.value = false
        queryRewardList()
      }else{
        ElMessage.error(response.m)
      }
  } catch (error) {
    ElMessage.error('文件解析失败,请检查文件格式是否正确')
  }
}

const excelShowdData = ref<any[]>([])
const processUploadData = (data: any[]) => {
  const errors: string[] = []
  let successCount = 0
  let failedCount = 0
  excelShowdData.value = data

  // 获取现有的业务代码集合
  const existingCodes = new Set(props.rules.map((r: any) => r.businessCode?.toLowerCase?.() || ''))

  data.forEach((row, index) => {
    const rowNum = index + 3 // Excel行号(从1开始,跳过表头)

    if (row.memo) {
      errors.push(`第${rowNum}行:${row.memo}`)
      failedCount++
      return
    }

    // 验证通过,添加到系统
    try {
      successCount++
    } catch (error) {
      errors.push(`第${rowNum}行:添加失败`)
      failedCount++
    }
  })

  // 显示上传结果
  uploadResult.value = {
    success: successCount,
    failed: failedCount,
    errors: errors
  }
  showUploadResult.value = true
}
</script>

<style scoped>
/* 搜索框样式 */
:deep(.search-input .el-input__wrapper) {
  padding-left: 40px;
  background-color: #f5f5f5;
  border: none;
  box-shadow: none;
}

:deep(.search-input .el-input__inner) {
  background-color: transparent;
}

/* 状态选择器样式 */
:deep(.status-select .el-input__wrapper) {
  background-color: #f5f5f5;
  border: none;
  box-shadow: none;
}

/* 表格样式优化:圆角由全局控制描边,这里仅保持圆角一致 */
:deep(.el-table) {
  border-radius: 8px;
}

:deep(.el-table .el-table__header-wrapper) {
  border-radius: 8px 8px 0 0;
}

:deep(.el-table .bg-blue-50\/50) {
  background-color: rgba(59, 130, 246, 0.05) !important;
}

:deep(.el-table .hover\:bg-muted\/30:hover) {
  background-color: rgba(0, 0, 0, 0.03) !important;
}

/* 分页样式 */
:deep(.el-pagination) {
  justify-content: flex-end;
}

:deep(.el-pagination .el-pager li) {
  min-width: 32px;
  height: 32px;
  line-height: 30px;
}

:deep(.el-pagination .btn-prev),
:deep(.el-pagination .btn-next) {
  height: 32px;
  line-height: 30px;
}

/* 强制修复dialog遮罩层定位问题 */
:deep(.el-overlay-dialog) {
  position: fixed !important;
  top: 0 !important;
  left: 0 !important;
  right: 0 !important;
  bottom: 0 !important;
  width: 100vw !important;
  height: 100vh !important;
  z-index: 10001 !important;
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  margin: 0 !important;
  padding: 0 !important;
}

:deep(.el-overlay-dialog .el-dialog) {
  position: relative !important;
  margin: 0 auto !important;
  transform: none !important;
  top: auto !important;
  left: auto !important;
  z-index: 10002 !important;
}
</style>