Files
one-pipe-system/src/views/asset-management/exchange-management/index.vue
luo 16effb69f3
All checks were successful
构建并部署前端到测试环境 / deploy (push) Successful in 55s
fix: some
2026-10-13 17:43:38 +08:00

1914 lines
61 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<template>
<ArtTableFullScreen>
<div class="exchange-management-page" id="table-full-screen">
<!-- 搜索栏 -->
<ArtSearchBar
v-model:filter="searchForm"
:items="searchFormItems"
:show-expand="true"
label-width="90"
@reset="handleReset"
@search="handleSearch"
></ArtSearchBar>
<ElCard shadow="never" class="art-table-card">
<!-- 表格头部 -->
<ArtTableHeader v-model:columns="columnChecks" @refresh="handleRefresh">
<template #left>
<ElButton type="primary" @click="showCreateDialog" v-permission="'exchange:create'">
创建换货单
</ElButton>
<ElButton v-if="hasAuth('exchange:export')" @click="exportDialogVisible = true">
导出
</ElButton>
</template>
</ArtTableHeader>
<!-- 表格 -->
<ArtTable
ref="tableRef"
row-key="id"
:loading="loading"
:data="exchangeList"
:currentPage="pagination.page"
:pageSize="pagination.page_size"
:total="pagination.total"
:marginTop="10"
:actions="getActions"
:actionsWidth="160"
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
>
<template #default>
<ElTableColumn v-for="col in columns" :key="col.prop || col.type" v-bind="col" />
</template>
</ArtTable>
<ExportTaskCreateDialog
v-model="exportDialogVisible"
scene="exchange"
:query="exportQuery"
confirm-permission="exchange:export"
title="导出换货"
/>
<!-- 创建换货单对话框 -->
<ElDialog
v-model="createDialogVisible"
title="创建换货单"
width="40%"
:close-on-click-modal="false"
@closed="handleCloseCreateDialog"
>
<ElForm ref="createFormRef" :model="createForm" :rules="createRules" label-width="110px">
<ElFormItem label="流程类型" prop="flow_type">
<ElSelect
v-model="createForm.flow_type"
placeholder="请选择流程类型"
style="width: 100%"
@change="handleFlowTypeChange"
>
<ElOption label="物流换货" value="shipping" />
<ElOption label="直接换货" value="direct" />
</ElSelect>
<div style="margin-top: 4px; font-size: 12px; color: #909399">
<span v-if="createForm.flow_type === 'shipping'">
物流换货:需要填写收货信息、发货等步骤
</span>
<span v-else-if="createForm.flow_type === 'direct'">
直接换货:创建后自动完成,无需物流环节
</span>
</div>
</ElFormItem>
<ElFormItem label="换货原因" prop="exchange_reason">
<ElSelect
v-model="createForm.exchange_reason"
placeholder="请选择换货原因"
clearable
style="width: 100%"
@change="handleExchangeReasonChange"
>
<ElOption
v-for="item in exchangeReasonOptions"
:key="item.value"
:label="item.label"
:value="item.value"
/>
</ElSelect>
</ElFormItem>
<ElFormItem
v-if="createForm.exchange_reason === EXCHANGE_REASON_OTHER"
label="其他原因"
prop="exchange_reason_other"
>
<ElInput
v-model="createForm.exchange_reason_other"
type="textarea"
:rows="3"
placeholder="请输入其他换货原因"
/>
</ElFormItem>
<ElFormItem label="旧资产类型" prop="old_asset_type">
<ElSelect
v-model="createForm.old_asset_type"
placeholder="请选择旧资产类型"
style="width: 100%"
@change="handleOldAssetTypeChange"
>
<ElOption label="IoT卡" value="iot_card" />
<ElOption label="设备" value="device" />
</ElSelect>
</ElFormItem>
<ElFormItem
v-if="createForm.old_asset_type === 'iot_card'"
label="旧资产标识"
prop="old_identifier"
>
<ElSelect
v-model="createForm.old_identifier"
filterable
remote
reserve-keyword
placeholder="请输入ICCID搜索"
:remote-method="searchOldIotCards"
:loading="oldCardSearchLoading"
no-data-text="暂无可用的旧资产"
style="width: 100%"
clearable
@change="handleOldIdentifierChange"
@focus="handleOldIotCardsFocus"
>
<ElOption
v-for="card in oldIotCardOptions"
:key="card.id"
:label="`${card.iccid} (${card.msisdn || '无接入号'})`"
:value="card.iccid"
>
<div style="display: flex; justify-content: space-between">
<span>{{ card.iccid }}</span>
<span style="font-size: 12px; color: var(--el-text-color-secondary)">
{{ card.msisdn || '无接入号' }}
</span>
</div>
</ElOption>
</ElSelect>
<div v-if="oldIotCardEmptyMessage" class="exchange-field-error">
{{ oldIotCardEmptyMessage }}
</div>
</ElFormItem>
<ElFormItem
v-if="createForm.old_asset_type === 'device'"
label="旧资产标识符"
prop="old_identifier"
>
<ElSelect
v-model="createForm.old_identifier"
filterable
remote
reserve-keyword
placeholder="请输入虚拟号或IMEI搜索"
:remote-method="searchOldDevices"
:loading="oldDeviceSearchLoading"
no-data-text="暂无可用的旧资产"
style="width: 100%"
clearable
@change="handleOldIdentifierChange"
@focus="handleOldDevicesFocus"
>
<ElOption
v-for="device in oldDeviceOptions"
:key="device.id"
:label="`${device.virtual_no} (${device.device_name || device.imei})`"
:value="device.virtual_no"
>
<div style="display: flex; justify-content: space-between">
<span>{{ device.virtual_no }}</span>
<span style="font-size: 12px; color: var(--el-text-color-secondary)">
{{ device.device_name || device.imei }}
</span>
</div>
</ElOption>
</ElSelect>
<div v-if="oldDeviceEmptyMessage" class="exchange-field-error">
{{ oldDeviceEmptyMessage }}
</div>
</ElFormItem>
<ElFormItem v-if="createOldAssetShopDisplay" label="旧资产店铺">
<ElInput :model-value="createOldAssetShopDisplay" readonly disabled />
</ElFormItem>
<ElFormItem
v-if="createForm.flow_type === 'direct' && createForm.old_asset_type === 'iot_card'"
label="新资产标识符"
prop="new_identifier"
>
<ElSelect
v-model="createForm.new_identifier"
filterable
remote
reserve-keyword
placeholder="请输入ICCID搜索"
:remote-method="searchNewIotCards"
:loading="newCardSearchLoading"
no-data-text="暂无同店铺可用的新资产"
style="width: 100%"
clearable
@focus="handleCreateNewIotCardsFocus"
>
<ElOption
v-for="card in newIotCardOptions"
:key="card.id"
:label="`${card.iccid} (${card.msisdn || '无接入号'})`"
:value="card.iccid"
>
<div style="display: flex; justify-content: space-between">
<span>{{ card.iccid }}</span>
<span style="font-size: 12px; color: var(--el-text-color-secondary)">
{{ card.msisdn || '无接入号' }}
</span>
</div>
</ElOption>
</ElSelect>
<div v-if="createNewIotCardEmptyMessage" class="exchange-field-error">
{{ createNewIotCardEmptyMessage }}
</div>
</ElFormItem>
<ElFormItem
v-if="createForm.flow_type === 'direct' && createForm.old_asset_type === 'device'"
label="新资产标识符"
prop="new_identifier"
>
<ElSelect
v-model="createForm.new_identifier"
filterable
remote
reserve-keyword
placeholder="请输入虚拟号或IMEI搜索"
:remote-method="searchNewDevices"
:loading="newDeviceSearchLoading"
no-data-text="暂无同店铺可用的新资产"
style="width: 100%"
clearable
@focus="handleCreateNewDevicesFocus"
>
<ElOption
v-for="device in newDeviceOptions"
:key="device.id"
:label="`${device.virtual_no} (${device.device_name || device.imei})`"
:value="device.virtual_no"
>
<div style="display: flex; justify-content: space-between">
<span>{{ device.virtual_no }}</span>
<span style="font-size: 12px; color: var(--el-text-color-secondary)">
{{ device.device_name || device.imei }}
</span>
</div>
</ElOption>
</ElSelect>
<div v-if="createNewDeviceEmptyMessage" class="exchange-field-error">
{{ createNewDeviceEmptyMessage }}
</div>
</ElFormItem>
<ElFormItem v-if="createDirectInheritedShopHint" label="归属提示">
<div class="exchange-shop-hint">{{ createDirectInheritedShopHint }}</div>
</ElFormItem>
<ElFormItem v-if="createForm.flow_type === 'direct'" label="是否迁移数据">
<ElSwitch v-model="createForm.migrate_data" />
<div style="margin-top: 4px; margin-left: 8px; font-size: 12px; color: #909399">
开启后将迁移钱包余额、套餐记录到新资产
</div>
</ElFormItem>
<ElFormItem label="备注">
<ElInput
v-model="createForm.remark"
type="textarea"
:rows="2"
placeholder="请输入备注(可选)"
/>
</ElFormItem>
</ElForm>
<template #footer>
<div class="dialog-footer">
<ElButton @click="createDialogVisible = false" :disabled="createLoading"
>取消</ElButton
>
<ElButton type="primary" @click="handleConfirmCreate" :loading="createLoading">
确认创建
</ElButton>
</div>
</template>
</ElDialog>
<!-- 发货对话框 -->
<ElDialog
v-model="shipDialogVisible"
title="换货发货"
width="40%"
:close-on-click-modal="false"
@closed="handleCloseShipDialog"
>
<ElForm ref="shipFormRef" :model="shipForm" :rules="shipRules" label-width="100px">
<ElFormItem
v-if="shipAssetType === 'iot_card'"
label="新资产标识"
prop="new_identifier"
>
<ElSelect
v-model="shipForm.new_identifier"
filterable
remote
reserve-keyword
placeholder="请输入ICCID搜索"
:remote-method="searchShipNewIotCards"
:loading="newCardSearchLoading"
no-data-text="暂无可用的新资产"
style="width: 100%"
clearable
@change="handleShipNewIdentifierChange"
@focus="handleShipNewIotCardsFocus"
>
<ElOption
v-for="card in newIotCardOptions"
:key="card.id"
:label="`${card.iccid} (${card.msisdn || '无接入号'})`"
:value="card.iccid"
>
<div style="display: flex; justify-content: space-between">
<span>{{ card.iccid }}</span>
<span style="font-size: 12px; color: var(--el-text-color-secondary)">
{{ card.msisdn || '无接入号' }}
</span>
</div>
</ElOption>
</ElSelect>
<div v-if="shipNewIotCardEmptyMessage" class="exchange-field-error">
{{ shipNewIotCardEmptyMessage }}
</div>
</ElFormItem>
<ElFormItem
v-else-if="shipAssetType === 'device'"
label="新资产标识"
prop="new_identifier"
>
<ElSelect
v-model="shipForm.new_identifier"
filterable
remote
reserve-keyword
placeholder="请输入虚拟号或IMEI搜索"
:remote-method="searchShipNewDevices"
:loading="newDeviceSearchLoading"
no-data-text="暂无可用的新资产"
style="width: 100%"
clearable
@change="handleShipNewIdentifierChange"
@focus="handleShipNewDevicesFocus"
>
<ElOption
v-for="device in newDeviceOptions"
:key="device.id"
:label="`${device.virtual_no} (${device.device_name || device.imei})`"
:value="device.virtual_no"
>
<div style="display: flex; justify-content: space-between">
<span>{{ device.virtual_no }}</span>
<span style="font-size: 12px; color: var(--el-text-color-secondary)">
{{ device.device_name || device.imei }}
</span>
</div>
</ElOption>
</ElSelect>
<div v-if="shipNewDeviceEmptyMessage" class="exchange-field-error">
{{ shipNewDeviceEmptyMessage }}
</div>
</ElFormItem>
<ElFormItem v-if="shipInheritedShopDisplayText" label="归属提示">
<div class="exchange-shop-hint">{{ shipInheritedShopDisplayText }}</div>
</ElFormItem>
<ElFormItem label="快递公司" prop="express_company">
<ElInput v-model="shipForm.express_company" placeholder="请输入快递公司" />
</ElFormItem>
<ElFormItem label="快递单号" prop="express_no">
<ElInput v-model="shipForm.express_no" placeholder="请输入快递单号" />
</ElFormItem>
<ElFormItem label="是否迁移数据">
<ElSwitch v-model="shipForm.migrate_data" />
<div style="margin-top: 4px; font-size: 12px; color: #909399">
开启后将迁移钱包余额、套餐记录到新资产
</div>
</ElFormItem>
</ElForm>
<template #footer>
<div class="dialog-footer">
<ElButton @click="shipDialogVisible = false" :disabled="shipLoading">取消</ElButton>
<ElButton type="primary" @click="handleConfirmShip" :loading="shipLoading">
确认发货
</ElButton>
</div>
</template>
</ElDialog>
</ElCard>
</div>
</ArtTableFullScreen>
</template>
<script setup lang="ts">
import { h } from 'vue'
import { useRouter } from 'vue-router'
import { ExchangeService, CardService, DeviceService } from '@/api/modules'
import type {
CreateExchangeRequest,
ExchangeAssetType,
ExchangeFlowType,
ExchangeQueryParams,
ExchangeResponse
} from '@/api/modules/exchange'
import type { StandaloneIotCard, Device } from '@/types/api'
import { ElMessage, ElTag, ElButton, ElMessageBox, ElSwitch } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import type { SearchFormItem } from '@/types'
import { useCheckedColumns } from '@/composables/useCheckedColumns'
import { useAuth } from '@/composables/useAuth'
import ExportTaskCreateDialog from '@/components/business/ExportTaskCreateDialog.vue'
import { formatDateTime } from '@/utils/business/format'
import {
getApprovalStatusText,
getCurrentApproverSummaryText,
getProcessingStatusText
} from '@/utils/business/approvalSummary'
import { RoutesAlias } from '@/router/routesAlias'
import { useUserStore } from '@/store/modules/user'
import { AUDIT_PERMISSIONS } from '@/config/constants/audit'
import { resolveAuditResourceTarget } from '@/utils/business/auditNavigation'
import { openAuditInvestigation } from '@/components/business/audit/investigationController'
import { AUGUST_PERMISSIONS } from '@/config/constants/augustIteration'
import { normalizeApiError } from '@/utils/business/apiError'
import {
getExchangePhoneConflictMessage,
getExchangeBusinessErrorMessage,
getExchangePhoneAssociationQuery,
type ExchangeNewAssetContext
} from '@/utils/business/exchangeError'
defineOptions({ name: 'ExchangeManagement' })
const { hasAuth } = useAuth()
const userStore = useUserStore()
const router = useRouter()
const handleExchangeFailure = async (
failure: unknown,
fallback: string,
newAsset: ExchangeNewAssetContext = {}
) => {
const conflictMessage = getExchangePhoneConflictMessage(failure)
if (!conflictMessage) {
const normalized = normalizeApiError(failure)
if (normalized.kind === 'auth') return // 登录失效由统一 HTTP 层反馈。
ElMessage.error(
getExchangeBusinessErrorMessage(failure) ||
(normalized.kind === 'unknown' ? fallback : normalized.message)
)
return
}
const associationQuery = getExchangePhoneAssociationQuery(failure, newAsset)
const canManageAssociations =
!!associationQuery && hasAuth(AUGUST_PERMISSIONS.phoneAssetAssociation.list)
try {
if (!canManageAssociations) {
await ElMessageBox.alert(conflictMessage, '换货提示', {
type: 'warning',
confirmButtonText: '知道了',
dangerouslyUseHTMLString: false
})
return
}
await ElMessageBox.confirm(conflictMessage, '新资产手机号绑定冲突', {
type: 'warning',
confirmButtonText: '前往手机号资产关联',
cancelButtonText: '暂不处理',
showCancelButton: true,
dangerouslyUseHTMLString: false
})
if (canManageAssociations)
await router.push({ path: RoutesAlias.PhoneAssetAssociation, query: associationQuery })
} catch {
// 用户关闭提示,不执行解绑或改写换货状态。
}
}
const currentExchangeRow = ref<ExchangeResponse | null>(null)
const loading = ref(false)
const shipDialogVisible = ref(false)
const shipLoading = ref(false)
const shipFormRef = ref<FormInstance>()
const createDialogVisible = ref(false)
const createLoading = ref(false)
const exportDialogVisible = ref(false)
const tableRef = ref()
const createFormRef = ref<FormInstance>()
const exchangeList = ref<ExchangeResponse[]>([])
const EXCHANGE_REASON_OTHER = '其他'
const exchangeReasonOptions = [
{ label: '管控转卡', value: '管控转卡' },
{ label: '原卡丢失', value: '原卡丢失' },
{ label: '网络问题', value: '网络问题' },
{ label: '锁卡换卡', value: '锁卡换卡' },
{ label: '卡片损坏', value: '卡片损坏' },
{ label: EXCHANGE_REASON_OTHER, value: EXCHANGE_REASON_OTHER }
]
// 搜索表单
const searchForm = reactive<ExchangeQueryParams & { created_at_range: string[] }>({
status: undefined,
flow_type: undefined, // 流程类型筛选
old_asset_keyword: '',
new_asset_keyword: '',
created_at_range: [],
start_time: '',
end_time: ''
})
const exportQuery = computed(() => {
const [startDate, endDate] = searchForm.created_at_range || []
return {
status: searchForm.status,
flow_type: searchForm.flow_type,
old_asset_keyword: searchForm.old_asset_keyword || undefined,
new_asset_keyword: searchForm.new_asset_keyword || undefined,
start_time: startDate || searchForm.start_time || undefined,
end_time: endDate || searchForm.end_time || undefined
}
})
// 创建换货单表单
const createForm = reactive<{
exchange_reason: string
exchange_reason_other: string
old_asset_type: ExchangeAssetType | ''
old_identifier: string
flow_type: ExchangeFlowType
new_identifier: string
migrate_data: boolean
remark: string
}>({
exchange_reason: '',
exchange_reason_other: '',
old_asset_type: '',
old_identifier: '',
flow_type: 'shipping', // 流程类型,默认物流换货
new_identifier: '', // 新资产标识符(direct 时必填)
migrate_data: false, // 是否迁移数据(默认 false)
remark: ''
})
const validateOtherExchangeReason = (_rule: any, value: string, callback: any) => {
if (createForm.exchange_reason !== EXCHANGE_REASON_OTHER) {
callback()
return
}
if (!value || !value.trim()) {
callback(new Error('请输入其他换货原因'))
return
}
callback()
}
const validateNewIdentifier = (_rule: any, value: string, callback: any) => {
if (createForm.flow_type !== 'direct') {
callback()
return
}
if (!value || !value.trim()) {
callback(new Error('请输入新资产标识符'))
return
}
callback()
}
const createRules = reactive<FormRules>({
exchange_reason: [{ required: true, message: '请选择换货原因', trigger: 'change' }],
exchange_reason_other: [{ validator: validateOtherExchangeReason, trigger: 'blur' }],
old_asset_type: [{ required: true, message: '请选择旧资产类型', trigger: 'change' }],
old_identifier: [{ required: true, message: '请选择旧资产标识符', trigger: 'change' }],
flow_type: [{ required: true, message: '请选择流程类型', trigger: 'change' }],
new_identifier: [{ validator: validateNewIdentifier, trigger: 'blur' }]
})
// 旧资产搜索相关
const oldIotCardOptions = ref<StandaloneIotCard[]>([])
const oldCardSearchLoading = ref(false)
const oldDeviceOptions = ref<Device[]>([])
const oldDeviceSearchLoading = ref(false)
// 新资产搜索相关(直接换货使用)
const newIotCardOptions = ref<StandaloneIotCard[]>([])
const newCardSearchLoading = ref(false)
const newDeviceOptions = ref<Device[]>([])
const newDeviceSearchLoading = ref(false)
const completeLoadingId = ref<number | null>(null)
type AssetFilterOption = {
label: string
value: string
}
const oldAssetFilterOptions = ref<AssetFilterOption[]>([])
const newAssetFilterOptions = ref<AssetFilterOption[]>([])
const oldAssetFilterLoading = ref(false)
const newAssetFilterLoading = ref(false)
const oldIotCardEmptyMessage = computed(() =>
oldCardSearchLoading.value || oldIotCardOptions.value.length > 0 ? '' : '暂无可用的旧资产'
)
const oldDeviceEmptyMessage = computed(() =>
oldDeviceSearchLoading.value || oldDeviceOptions.value.length > 0 ? '' : '暂无可用的旧资产'
)
const createNewIotCardEmptyMessage = computed(() => {
if (newCardSearchLoading.value || newIotCardOptions.value.length > 0) return ''
return createForm.old_identifier ? '暂无同店铺可用的新资产' : '请先选择旧资产'
})
const createNewDeviceEmptyMessage = computed(() => {
if (newDeviceSearchLoading.value || newDeviceOptions.value.length > 0) return ''
return createForm.old_identifier ? '暂无同店铺可用的新资产' : '请先选择旧资产'
})
const shipNewIotCardEmptyMessage = computed(() =>
newCardSearchLoading.value || newIotCardOptions.value.length > 0 ? '' : '暂无可用的新资产'
)
const shipNewDeviceEmptyMessage = computed(() =>
newDeviceSearchLoading.value || newDeviceOptions.value.length > 0 ? '' : '暂无可用的新资产'
)
// 发货表单
const shipForm = reactive({
new_identifier: '',
express_company: '',
express_no: '',
migrate_data: true
})
const shipRules = reactive<FormRules>({
new_identifier: [{ required: true, message: '请选择新资产标识符', trigger: 'change' }],
express_company: [{ required: true, message: '请输入快递公司', trigger: 'blur' }],
express_no: [{ required: true, message: '请输入快递单号', trigger: 'blur' }]
})
const handleShipNewIdentifierChange = () => {
shipFormRef.value?.clearValidate('new_identifier')
}
const handleShipNewIotCardsFocus = async () => {
if (newCardSearchLoading.value || newIotCardOptions.value.length > 0) return
await loadDefaultShipNewIotCards()
}
const handleShipNewDevicesFocus = async () => {
if (newDeviceSearchLoading.value || newDeviceOptions.value.length > 0) return
await loadDefaultShipNewDevices()
}
const handleOldIotCardsFocus = async () => {
if (oldCardSearchLoading.value || oldIotCardOptions.value.length > 0) return
await loadDefaultIotCards()
}
const handleOldDevicesFocus = async () => {
if (oldDeviceSearchLoading.value || oldDeviceOptions.value.length > 0) return
await loadDefaultDevices()
}
const handleCreateNewIotCardsFocus = async () => {
if (newCardSearchLoading.value || newIotCardOptions.value.length > 0) return
await loadDefaultNewIotCards()
}
const handleCreateNewDevicesFocus = async () => {
if (newDeviceSearchLoading.value || newDeviceOptions.value.length > 0) return
await loadDefaultNewDevices()
}
const searchFilterAssets = async (query: string, target: 'old' | 'new') => {
const options = target === 'old' ? oldAssetFilterOptions : newAssetFilterOptions
const loading = target === 'old' ? oldAssetFilterLoading : newAssetFilterLoading
loading.value = true
try {
const keyword = query.trim() || undefined
const [cardRes, deviceRes] = await Promise.all([
CardService.getStandaloneIotCards({
is_standalone: true,
keyword,
page: 1,
page_size: 10
}),
DeviceService.getDevices({
keyword,
page: 1,
page_size: 10
})
])
const cardOptions: AssetFilterOption[] =
cardRes.code === 0
? (cardRes.data?.items || []).map((card) => ({
label: `${card.iccid} (IoT卡)`,
value: card.iccid
}))
: []
const deviceOptions: AssetFilterOption[] =
deviceRes.code === 0
? (deviceRes.data?.items || []).map((device) => ({
label: `${device.virtual_no} (设备)`,
value: device.virtual_no
}))
: []
options.value = [...cardOptions, ...deviceOptions]
} catch (error) {
console.error('加载资产筛选选项失败:', error)
options.value = []
} finally {
loading.value = false
}
}
type ShopSelectableOption = {
shop_id?: number | null
shop_name?: string | null
associated_phones?: string[]
}
const getShopDisplayName = (option?: ShopSelectableOption | null) => {
if (!option) return ''
if (option.shop_name) return option.shop_name
return '库存'
}
const createSelectedOldAsset = computed<ShopSelectableOption | null>(() => {
if (!createForm.old_identifier) return null
if (createForm.old_asset_type === 'iot_card') {
return (
oldIotCardOptions.value.find((card) => card.iccid === createForm.old_identifier) || null
)
}
if (createForm.old_asset_type === 'device') {
return (
oldDeviceOptions.value.find((device) => device.virtual_no === createForm.old_identifier) ||
null
)
}
return null
})
const createSelectedNewAsset = computed<ShopSelectableOption | null>(() => {
if (!createForm.new_identifier) return null
if (createForm.old_asset_type === 'iot_card') {
return (
newIotCardOptions.value.find((card) => card.iccid === createForm.new_identifier) || null
)
}
if (createForm.old_asset_type === 'device') {
return (
newDeviceOptions.value.find((device) => device.virtual_no === createForm.new_identifier) ||
null
)
}
return null
})
const shipAssetType = computed(() => currentExchangeRow.value?.old_asset_type || '')
const shipSelectedNewAsset = computed<ShopSelectableOption | null>(() => {
if (!shipForm.new_identifier) return null
if (shipAssetType.value === 'iot_card') {
return newIotCardOptions.value.find((card) => card.iccid === shipForm.new_identifier) || null
}
if (shipAssetType.value === 'device') {
return (
newDeviceOptions.value.find((device) => device.virtual_no === shipForm.new_identifier) ||
null
)
}
return null
})
const createOldAssetShopDisplay = computed(() => getShopDisplayName(createSelectedOldAsset.value))
const getCreateOldAssetShopId = () => {
const shopId = createSelectedOldAsset.value?.shop_id
if (typeof shopId === 'number') return shopId
if (shopId === null) return 0
return undefined
}
const createDirectInheritedShopHint = computed(() => {
const shopName = getShopDisplayName(createSelectedNewAsset.value)
return shopName ? `换货完成后将归属:${shopName}` : ''
})
const shipInheritedShopDisplayText = computed(() => {
const shopName = getShopDisplayName(shipSelectedNewAsset.value)
return shopName ? `换货完成后将归属:${shopName}` : ''
})
// 分页
const pagination = reactive({
page: 1,
page_size: 20,
total: 0
})
// 搜索表单配置
const searchFormItems = computed<SearchFormItem[]>(() => [
{
label: '换货状态',
prop: 'status',
type: 'select',
config: {
clearable: true,
placeholder: '全部'
},
options: () => [
{ label: '待填写信息', value: 1 },
{ label: '待发货', value: 2 },
{ label: '已发货待确认', value: 3 },
{ label: '已完成', value: 4 },
{ label: '已取消', value: 5 }
]
},
{
label: '流程类型',
prop: 'flow_type',
type: 'select',
config: {
clearable: true,
placeholder: '全部'
},
options: () => [
{ label: '物流换货', value: 'shipping' },
{ label: '直接换货', value: 'direct' }
]
},
{
label: '旧资产',
prop: 'old_asset_keyword',
type: 'select',
options: () => oldAssetFilterOptions.value,
config: {
placeholder: '请选择或搜索旧资产标识',
clearable: true,
filterable: true,
remote: true,
reserveKeyword: true,
loading: oldAssetFilterLoading.value,
remoteMethod: (query: string) => searchFilterAssets(query, 'old')
}
},
{
label: '新资产',
prop: 'new_asset_keyword',
type: 'select',
options: () => newAssetFilterOptions.value,
config: {
placeholder: '请选择或搜索新资产标识',
clearable: true,
filterable: true,
remote: true,
reserveKeyword: true,
loading: newAssetFilterLoading.value,
remoteMethod: (query: string) => searchFilterAssets(query, 'new')
}
},
{
label: '起止时间',
prop: 'created_at_range',
type: 'datetimerange',
config: {
type: 'datetimerange',
rangeSeparator: '至',
startPlaceholder: '开始日期',
endPlaceholder: '结束日期',
valueFormat: 'YYYY-MM-DDTHH:mm:ssZ'
}
}
])
// 动态列配置
const { columnChecks, columns } = useCheckedColumns(() => [
{
prop: 'exchange_no',
label: '换货单号',
width: 230,
showOverflowTooltip: true,
fixed: true,
formatter: (row: any) =>
h(
ElButton,
{
type: 'primary',
link: true,
onClick: () => handleNameClick(row)
},
() => row.exchange_no || '--'
)
},
{
prop: 'exchange_reason',
label: '换货原因',
minWidth: 150,
showOverflowTooltip: true
},
{
prop: 'flow_type',
label: '流程类型',
width: 120,
formatter: (row: any) =>
row.flow_type_name || (row.flow_type === 'direct' ? '直接换货' : '物流换货')
},
{
prop: 'old_asset_type',
label: '旧资产类型',
width: 120,
formatter: (row: ExchangeResponse) => getAssetTypeName(row.old_asset_type)
},
{
prop: 'old_asset_identifier',
label: '旧资产标识符',
width: 220,
formatter: (row: ExchangeResponse) => row.old_asset_identifier || '--'
},
{
prop: 'new_asset_type',
label: '新资产类型',
width: 120,
formatter: (row: ExchangeResponse) => getAssetTypeName(row.new_asset_type)
},
{
prop: 'new_asset_identifier',
label: '新资产标识符',
width: 220,
formatter: (row: ExchangeResponse) => row.new_asset_identifier || '--'
},
{
prop: 'submitter_name',
label: '提交人',
width: 120,
showOverflowTooltip: true,
formatter: (row: ExchangeResponse) => row.submitter_name || '-'
},
{
prop: 'approval_status',
label: '审批状态',
width: 120,
formatter: (row: ExchangeResponse) => getApprovalStatusText(row)
},
{
prop: 'current_approver_summary',
label: '当前审批人摘要',
minWidth: 180,
showOverflowTooltip: true,
formatter: (row: ExchangeResponse) => getCurrentApproverSummaryText(row)
},
{
prop: 'processing_status_name',
label: '业务处理状态',
width: 140,
showOverflowTooltip: true,
formatter: (row: ExchangeResponse) => getProcessingStatusText(row)
},
{
prop: 'recipient_name',
label: '收货人姓名',
width: 120,
showOverflowTooltip: true,
formatter: (row: any) => row.recipient_name || '--'
},
{
prop: 'recipient_phone',
label: '收货人电话',
width: 140,
showOverflowTooltip: true,
formatter: (row: any) => row.recipient_phone || '--'
},
{
prop: 'recipient_address',
label: '收货地址',
minWidth: 260,
showOverflowTooltip: true,
formatter: (row: any) => row.recipient_address || '--'
},
{
prop: 'express_company',
label: '快递公司',
width: 160,
showOverflowTooltip: true,
formatter: (row: any) => row.express_company || '--'
},
{
prop: 'express_no',
label: '快递单号',
width: 180,
showOverflowTooltip: true,
formatter: (row: any) => row.express_no || '--'
},
{
prop: 'status',
label: '状态',
width: 130,
formatter: (row: ExchangeResponse) =>
h(ElTag, { type: getStatusType(row.status) }, () => row.status_name || '--')
},
{
prop: 'migration_status',
label: '迁移状态',
width: 130,
formatter: (row: ExchangeResponse) =>
row.migration_status
? h(
ElTag,
{ type: getMigrationStatusType(row.migration_status) },
() => row.migration_status_name || '--'
)
: '--'
},
{
prop: 'created_at',
label: '创建时间',
width: 180,
formatter: (row: any) => formatDateTime(row.created_at)
}
])
const getStatusType = (status: number): 'success' | 'info' | 'warning' | 'danger' | 'primary' => {
const types: Record<number, 'success' | 'info' | 'warning' | 'danger' | 'primary'> = {
1: 'warning',
2: 'info',
3: 'primary',
4: 'success',
5: 'danger'
}
return types[status] || 'info'
}
const getMigrationStatusType = (
migrationStatus?: string
): 'success' | 'info' | 'warning' | 'danger' | 'primary' => {
const types: Record<string, 'success' | 'info' | 'warning' | 'danger' | 'primary'> = {
not_migrated: 'info',
pending: 'warning',
migrated: 'success',
failed: 'danger'
}
return types[migrationStatus || ''] || 'info'
}
const getAssetTypeName = (assetType?: string | null) => {
if (assetType === 'iot_card') return '物联网卡'
if (assetType === 'device') return '设备'
return '--'
}
// 加载换货单列表
const loadExchangeList = async () => {
loading.value = true
try {
// 过滤掉空值参数
const params: ExchangeQueryParams = {
page: pagination.page,
page_size: pagination.page_size
}
if (searchForm.status !== undefined && searchForm.status !== null) {
params.status = searchForm.status
}
if (searchForm.flow_type) {
params.flow_type = searchForm.flow_type
}
if (searchForm.old_asset_keyword) {
params.old_asset_keyword = searchForm.old_asset_keyword
}
if (searchForm.new_asset_keyword) {
params.new_asset_keyword = searchForm.new_asset_keyword
}
if (searchForm.start_time) {
params.start_time = searchForm.start_time
}
if (searchForm.end_time) {
params.end_time = searchForm.end_time
}
const res = await ExchangeService.getExchanges(params)
if (res.code === 0 && res.data) {
exchangeList.value = res.data.items || []
pagination.total = res.data.total || 0
}
} catch (error) {
console.error('加载换货单列表失败:', error)
} finally {
loading.value = false
}
}
// 搜索
const handleSearch = () => {
// 处理日期范围
if (searchForm.created_at_range && Array.isArray(searchForm.created_at_range)) {
searchForm.start_time = searchForm.created_at_range[0] || ''
searchForm.end_time = searchForm.created_at_range[1] || ''
} else {
searchForm.start_time = ''
searchForm.end_time = ''
}
pagination.page = 1
loadExchangeList()
}
// 重置
const handleReset = () => {
searchForm.old_asset_keyword = ''
searchForm.new_asset_keyword = ''
searchForm.created_at_range = []
searchForm.start_time = ''
searchForm.end_time = ''
pagination.page = 1
loadExchangeList()
}
// 刷新
const handleRefresh = () => {
loadExchangeList()
}
// 分页
const handleSizeChange = (size: number) => {
pagination.page_size = size
loadExchangeList()
}
const handleCurrentChange = (page: number) => {
pagination.page = page
loadExchangeList()
}
// 显示创建对话框
const showCreateDialog = () => {
createDialogVisible.value = true
}
const handleExchangeReasonChange = () => {
if (createForm.exchange_reason !== EXCHANGE_REASON_OTHER) {
createForm.exchange_reason_other = ''
createFormRef.value?.clearValidate('exchange_reason_other')
}
}
// 流程类型变更
const handleFlowTypeChange = async () => {
// 清空新资产标识符和数据迁移选项
createForm.new_identifier = ''
createForm.migrate_data = false
newIotCardOptions.value = []
newDeviceOptions.value = []
createFormRef.value?.clearValidate('new_identifier')
// 如果选择直接换货且已选择旧资产类型,加载默认新资产列表
if (createForm.flow_type === 'direct' && createForm.old_asset_type) {
if (createForm.old_asset_type === 'iot_card') {
await loadDefaultNewIotCards()
} else if (createForm.old_asset_type === 'device') {
await loadDefaultNewDevices()
}
}
}
// 旧资产类型变更
const handleOldAssetTypeChange = async () => {
// 清空旧资产标识符
createForm.old_identifier = ''
oldIotCardOptions.value = []
oldDeviceOptions.value = []
// 清空新资产标识符(如果是直接换货)
if (createForm.flow_type === 'direct') {
createForm.new_identifier = ''
newIotCardOptions.value = []
newDeviceOptions.value = []
}
// 根据类型加载默认数据
if (createForm.old_asset_type === 'iot_card') {
await loadDefaultIotCards()
// 如果是直接换货,也加载新资产列表
if (createForm.flow_type === 'direct' && createForm.old_identifier) {
await loadDefaultNewIotCards()
}
} else if (createForm.old_asset_type === 'device') {
await loadDefaultDevices()
// 如果是直接换货,也加载新资产列表
if (createForm.flow_type === 'direct' && createForm.old_identifier) {
await loadDefaultNewDevices()
}
}
}
const handleOldIdentifierChange = async () => {
createFormRef.value?.clearValidate('old_identifier')
createForm.new_identifier = ''
newIotCardOptions.value = []
newDeviceOptions.value = []
createFormRef.value?.clearValidate('new_identifier')
if (createForm.flow_type !== 'direct' || !createForm.old_identifier) return
if (createForm.old_asset_type === 'iot_card') {
await loadDefaultNewIotCards()
} else if (createForm.old_asset_type === 'device') {
await loadDefaultNewDevices()
}
}
const refreshExchangeDetail = async (id: number) => {
try {
const res = await ExchangeService.getExchangeDetail(id)
if (res.code === 0 && res.data) {
return res.data
}
} catch (error) {
console.error('刷新换货详情失败:', error)
}
return null
}
// 加载默认IoT卡列表
const loadDefaultIotCards = async () => {
oldCardSearchLoading.value = true
try {
const res = await CardService.getStandaloneIotCards({
is_standalone: true,
page: 1,
page_size: 10
})
if (res.code === 0 && res.data) {
oldIotCardOptions.value = res.data.items || []
}
} catch (error) {
console.error('加载IoT卡列表失败:', error)
oldIotCardOptions.value = []
} finally {
oldCardSearchLoading.value = false
}
}
// 加载默认设备列表
const loadDefaultDevices = async () => {
oldDeviceSearchLoading.value = true
try {
const res = await DeviceService.getDevices({
page: 1,
page_size: 10
})
if (res.code === 0 && res.data) {
oldDeviceOptions.value = res.data.items || []
}
} catch (error) {
console.error('加载设备列表失败:', error)
oldDeviceOptions.value = []
} finally {
oldDeviceSearchLoading.value = false
}
}
// 搜索旧IoT卡
const searchOldIotCards = async (query: string) => {
if (!query) {
// 如果清空搜索,加载默认列表
await loadDefaultIotCards()
return
}
oldCardSearchLoading.value = true
try {
const res = await CardService.getStandaloneIotCards({
is_standalone: true,
keyword: query,
page: 1,
page_size: 20
})
if (res.code === 0 && res.data) {
oldIotCardOptions.value = res.data.items || []
}
} catch (error) {
console.error('搜索IoT卡失败:', error)
oldIotCardOptions.value = []
} finally {
oldCardSearchLoading.value = false
}
}
// 搜索旧设备
const searchOldDevices = async (query: string) => {
if (!query) {
// 如果清空搜索,加载默认列表
await loadDefaultDevices()
return
}
oldDeviceSearchLoading.value = true
try {
const res = await DeviceService.getDevices({
keyword: query,
page: 1,
page_size: 20
})
if (res.code === 0 && res.data) {
oldDeviceOptions.value = res.data.items || []
}
} catch (error) {
console.error('搜索设备失败:', error)
oldDeviceOptions.value = []
} finally {
oldDeviceSearchLoading.value = false
}
}
// 搜索新IoT卡(直接换货使用)
const searchNewIotCards = async (query: string) => {
if (!query) {
// 清空搜索时加载默认列表
await loadDefaultNewIotCards()
return
}
const shopId = getCreateOldAssetShopId()
if (shopId === undefined) {
newIotCardOptions.value = []
return
}
newCardSearchLoading.value = true
try {
const res = await CardService.getStandaloneIotCards({
is_standalone: true,
keyword: query,
page: 1,
page_size: 20
})
if (res.code === 0 && res.data) {
newIotCardOptions.value = res.data.items || []
}
} catch (error) {
console.error('搜索IoT卡失败:', error)
newIotCardOptions.value = []
} finally {
newCardSearchLoading.value = false
}
}
const searchShipNewIotCards = async (query: string) => {
if (!query) {
await loadDefaultShipNewIotCards()
return
}
newCardSearchLoading.value = true
try {
const res = await CardService.getStandaloneIotCards({
is_standalone: true,
status: 1,
keyword: query,
page: 1,
page_size: 20
})
if (res.code === 0 && res.data) {
newIotCardOptions.value = res.data.items || []
}
} catch (error) {
console.error('搜索IoT卡失败:', error)
newIotCardOptions.value = []
} finally {
newCardSearchLoading.value = false
}
}
// 加载默认新IoT卡列表
const loadDefaultNewIotCards = async () => {
const shopId = getCreateOldAssetShopId()
if (shopId === undefined) {
newIotCardOptions.value = []
return
}
newCardSearchLoading.value = true
try {
const res = await CardService.getStandaloneIotCards({
is_standalone: true,
page: 1,
page_size: 10
})
if (res.code === 0 && res.data) {
newIotCardOptions.value = res.data.items || []
}
} catch (error) {
console.error('加载IoT卡列表失败:', error)
newIotCardOptions.value = []
} finally {
newCardSearchLoading.value = false
}
}
const loadDefaultShipNewIotCards = async () => {
newCardSearchLoading.value = true
try {
const res = await CardService.getStandaloneIotCards({
is_standalone: true,
status: 1,
page: 1,
page_size: 10
})
if (res.code === 0) {
newIotCardOptions.value = res.data?.items || []
}
} catch (error) {
console.error('加载IoT卡列表失败:', error)
newIotCardOptions.value = []
} finally {
newCardSearchLoading.value = false
}
}
// 搜索新设备(直接换货使用)
const searchNewDevices = async (query: string) => {
if (!query) {
// 清空搜索时加载默认列表
await loadDefaultNewDevices()
return
}
const shopId = getCreateOldAssetShopId()
if (shopId === undefined) {
newDeviceOptions.value = []
return
}
newDeviceSearchLoading.value = true
try {
const res = await DeviceService.getDevices({
keyword: query,
page: 1,
page_size: 20
})
if (res.code === 0 && res.data) {
newDeviceOptions.value = res.data.items || []
}
} catch (error) {
console.error('搜索设备失败:', error)
newDeviceOptions.value = []
} finally {
newDeviceSearchLoading.value = false
}
}
const searchShipNewDevices = async (query: string) => {
if (!query) {
await loadDefaultShipNewDevices()
return
}
newDeviceSearchLoading.value = true
try {
const res = await DeviceService.getDevices({
status: 1,
keyword: query,
page: 1,
page_size: 20
})
if (res.code === 0 && res.data) {
newDeviceOptions.value = res.data.items || []
}
} catch (error) {
console.error('搜索设备失败:', error)
newDeviceOptions.value = []
} finally {
newDeviceSearchLoading.value = false
}
}
// 加载默认新设备列表
const loadDefaultNewDevices = async () => {
const shopId = getCreateOldAssetShopId()
if (shopId === undefined) {
newDeviceOptions.value = []
return
}
newDeviceSearchLoading.value = true
try {
const res = await DeviceService.getDevices({
page: 1,
page_size: 10
})
if (res.code === 0 && res.data) {
newDeviceOptions.value = res.data.items || []
}
} catch (error) {
console.error('加载设备列表失败:', error)
newDeviceOptions.value = []
} finally {
newDeviceSearchLoading.value = false
}
}
const loadDefaultShipNewDevices = async () => {
newDeviceSearchLoading.value = true
try {
const res = await DeviceService.getDevices({
status: 1,
page: 1,
page_size: 10
})
if (res.code === 0) {
newDeviceOptions.value = res.data?.items || []
}
} catch (error) {
console.error('加载设备列表失败:', error)
newDeviceOptions.value = []
} finally {
newDeviceSearchLoading.value = false
}
}
// 确认创建
const handleConfirmCreate = () => {
createFormRef.value?.validate(async (valid) => {
if (!valid || createLoading.value) return
// 提交时冻结新资产上下文;请求或提示期间改动表单也不能跳到其他资产。
const newAsset: ExchangeNewAssetContext = {
asset_identifier: createForm.new_identifier,
associated_phones: [...(createSelectedNewAsset.value?.associated_phones || [])]
}
createLoading.value = true
try {
const exchangeReason =
createForm.exchange_reason === EXCHANGE_REASON_OTHER
? createForm.exchange_reason_other.trim()
: createForm.exchange_reason
const requestData: CreateExchangeRequest = {
exchange_reason: exchangeReason,
old_asset_type: createForm.old_asset_type as ExchangeAssetType,
old_identifier: createForm.old_identifier,
flow_type: createForm.flow_type,
remark: createForm.remark || undefined
}
// 直接换货时需要传递新资产标识符和数据迁移标志
if (createForm.flow_type === 'direct') {
requestData.new_identifier = createForm.new_identifier
requestData.migrate_data = createForm.migrate_data
}
const res = await ExchangeService.createExchange(requestData, {
requestOptions: { errorMessageMode: 'none' }
})
if (res.code === 0) {
ElMessage.success('换货单创建成功')
createDialogVisible.value = false
await loadExchangeList()
return
}
await handleExchangeFailure(res, '换货单创建失败', newAsset)
} catch (error) {
await handleExchangeFailure(error, '换货单创建失败', newAsset)
} finally {
createLoading.value = false
}
})
}
// 关闭创建对话框
const handleCloseCreateDialog = () => {
createFormRef.value?.resetFields()
// 清空搜索选项
oldIotCardOptions.value = []
oldDeviceOptions.value = []
newIotCardOptions.value = []
newDeviceOptions.value = []
}
// 查看详情
const handleNameClick = (row: ExchangeResponse) => {
if (hasAuth('exchange:detail')) {
handleViewDetail(row)
} else {
ElMessage.warning('您没有查看详情的权限')
}
}
const handleViewDetail = (row: any) => {
router.push(`${RoutesAlias.ExchangeDetail}/${row.id}`)
}
// 获取操作按钮
const getActions = (row: ExchangeResponse) => {
const actions: any[] = []
const status = row.status
const flowType = row.flow_type || 'shipping' // 历史数据兼容
const userType = Number(userStore.info.user_type)
const entryPermission =
userType === 3 ? AUDIT_PERMISSIONS.agentExchangeActivity : AUDIT_PERMISSIONS.exchangeEntry
if ([1, 2, 3].includes(userType) && hasAuth(entryPermission)) {
const exchangeTarget = resolveAuditResourceTarget({
userType,
resourceType: 'exchange_order',
internalId: row.id,
businessIdentifier: row.exchange_no
})
if (exchangeTarget)
actions.push({
label: userType === 3 ? '活动记录' : '换货审计',
handler: () => openAuditInvestigation(exchangeTarget),
type: 'primary'
})
if ([1, 2].includes(userType)) {
const oldAssetTarget = resolveAuditResourceTarget({
resourceType: row.old_asset_type,
internalId: row.old_asset_id
})
if (oldAssetTarget && hasAuth(AUDIT_PERMISSIONS.exchangeOldAssetEntry))
actions.push({
label: '旧资产审计',
handler: () => openAuditInvestigation(oldAssetTarget),
type: 'primary'
})
const newAssetTarget = resolveAuditResourceTarget({
resourceType: row.new_asset_type || '',
internalId: row.new_asset_id
})
if (newAssetTarget && hasAuth(AUDIT_PERMISSIONS.exchangeNewAssetEntry))
actions.push({
label: '新资产审计',
handler: () => openAuditInvestigation(newAssetTarget),
type: 'primary'
})
}
}
// 直接换货不支持任何操作(发货、确认完成、取消)
if (flowType === 'direct') {
// 状态4(已完成):旧资产转新(direct 也支持)
if (status === 4 && hasAuth('exchange:renew')) {
actions.push({
label: '旧资产转新',
handler: () => handleRenewExchange(row),
type: 'warning'
})
}
return actions
}
// 物流换货流程
// 状态1(待填写信息):取消换货
if (status === 1) {
if (hasAuth('exchange:cancel')) {
actions.push({
label: '取消换货',
handler: () => handleCancelExchange(row),
type: 'danger'
})
}
}
// 状态2(待发货):发货、取消换货
if (status === 2) {
if (hasAuth('exchange:ship')) {
actions.push({
label: '发货',
handler: () => handleShipExchange(row),
type: 'primary'
})
}
if (hasAuth('exchange:cancel')) {
actions.push({
label: '取消换货',
handler: () => handleCancelExchange(row),
type: 'danger'
})
}
}
// 状态3(已发货待确认):确认完成
if (status === 3) {
// migration_status=failed 的重试仅超管/平台账号可操作,代理/企业不渲染入口(后端以 403/1005 兜底)
const canRetryFailed = row.migration_status !== 'failed' || userType === 1 || userType === 2
if (hasAuth('exchange:complete') && canRetryFailed) {
actions.push({
label: '确认完成',
handler: () => handleCompleteExchange(row),
type: 'success'
})
}
}
// 状态4(已完成):旧资产转新
if (status === 4) {
if (hasAuth('exchange:renew')) {
actions.push({
label: '旧资产转新',
handler: () => handleRenewExchange(row),
type: 'warning'
})
}
}
return actions
}
// 取消换货
const handleCancelExchange = (row: ExchangeResponse) => {
ElMessageBox.prompt('请输入取消备注', '取消换货', {
confirmButtonText: '确定',
cancelButtonText: '取消',
inputType: 'textarea'
})
.then(async ({ value }) => {
try {
const res = await ExchangeService.cancelExchange(row.id, { remark: value })
if (res.code === 0) {
ElMessage.success('取消成功')
await loadExchangeList()
}
} catch (error) {
console.error('取消换货失败:', error)
}
})
.catch(() => {})
}
// 发货
const handleShipExchange = async (row: ExchangeResponse) => {
currentExchangeRow.value = row
// 重置表单
shipForm.new_identifier = ''
shipForm.express_company = ''
shipForm.express_no = ''
shipForm.migrate_data = true
newIotCardOptions.value = []
newDeviceOptions.value = []
shipDialogVisible.value = true
if (row.old_asset_type === 'iot_card') {
await loadDefaultShipNewIotCards()
} else if (row.old_asset_type === 'device') {
await loadDefaultShipNewDevices()
}
}
// 确认发货
const handleConfirmShip = () => {
shipFormRef.value?.validate(async (valid) => {
if (!valid || !currentExchangeRow.value || shipLoading.value) return
shipLoading.value = true
try {
const res = await ExchangeService.shipExchange(currentExchangeRow.value.id, shipForm)
if (res.code === 0) {
const latestDetail = await refreshExchangeDetail(currentExchangeRow.value.id)
if (latestDetail) {
currentExchangeRow.value = latestDetail
}
ElMessage.success('发货成功')
shipDialogVisible.value = false
await loadExchangeList()
return
}
ElMessage.error(res.msg || '发货失败')
} catch (error) {
console.error('发货失败:', error)
} finally {
shipLoading.value = false
}
})
}
// 关闭发货对话框
const handleCloseShipDialog = () => {
shipFormRef.value?.resetFields()
currentExchangeRow.value = null
newIotCardOptions.value = []
newDeviceOptions.value = []
}
// 确认完成
const handleCompleteExchange = async (row: ExchangeResponse) => {
if (completeLoadingId.value === row.id) return
const newAsset: ExchangeNewAssetContext = {
asset_identifier: row.new_asset_identifier || undefined
}
completeLoadingId.value = row.id
try {
await ElMessageBox.confirm('确定要确认换货完成吗?', '确认操作', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
})
} catch {
completeLoadingId.value = null
return
}
try {
const res = await ExchangeService.completeExchange(row.id, {
requestOptions: { errorMessageMode: 'none' }
})
// 刷新失败也不能吞掉原操作的 1202 业务响应。
await Promise.allSettled([refreshExchangeDetail(row.id), loadExchangeList()])
if (res.code === 0) ElMessage.success('操作成功')
else await handleExchangeFailure(res, '确认完成失败', newAsset)
} catch (error) {
// 仅重新读取原单状态,不乐观标记完成,错误对象可能包含完整手机号,不输出日志。
await Promise.allSettled([refreshExchangeDetail(row.id), loadExchangeList()])
await handleExchangeFailure(error, '确认完成失败', newAsset)
} finally {
completeLoadingId.value = null
}
}
// 旧资产转新
const handleRenewExchange = (row: ExchangeResponse) => {
ElMessageBox.confirm('确定要将旧资产转为新资产吗?', '确认操作', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
})
.then(async () => {
try {
const res = await ExchangeService.renewExchange(row.id)
if (res.code === 0) {
ElMessage.success('操作成功')
await loadExchangeList()
}
} catch (error) {
console.error('旧资产转新失败:', error)
}
})
.catch(() => {})
}
// 初始化
onMounted(() => {
loadExchangeList()
searchFilterAssets('', 'old')
searchFilterAssets('', 'new')
})
</script>
<style lang="scss" scoped>
.exchange-management-page {
height: 100%;
.exchange-shop-hint {
width: 100%;
padding: 10px 12px;
line-height: 1.5;
color: var(--el-color-primary);
background: var(--el-color-primary-light-9);
border: 1px solid var(--el-color-primary-light-7);
border-radius: 6px;
}
.exchange-field-error {
width: 100%;
margin-top: 4px;
font-size: 12px;
line-height: 1.2;
color: var(--el-color-danger);
}
}
</style>