<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>
          </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="120"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
          <template #default>
            <ElTableColumn v-for="col in columns" :key="col.prop || col.type" v-bind="col" />
          </template>
        </ArtTable>

        <!-- 创建换货单对话框 -->
        <ElDialog
          v-model="createDialogVisible"
          title="创建换货单"
          width="600px"
          :close-on-click-modal="false"
          @closed="handleCloseCreateDialog"
        >
          <ElForm ref="createFormRef" :model="createForm" :rules="createRules" label-width="120px">
            <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"
              >
                <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>
            </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"
              >
                <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>
            </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
              >
                <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>
            </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
              >
                <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>
            </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="600px"
          :close-on-click-modal="false"
          @closed="handleCloseShipDialog"
        >
          <ElForm ref="shipFormRef" :model="shipForm" :rules="shipRules" label-width="120px">
            <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
              >
                <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>
            </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
              >
                <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>
            </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 { 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 { formatDateTime } from '@/utils/business/format'
  import {
    getApprovalStatusText,
    getCurrentApproverSummaryText,
    getProcessingStatusText
  } from '@/utils/business/approvalSummary'
  import { RoutesAlias } from '@/router/routesAlias'

  defineOptions({ name: 'ExchangeManagement' })

  const { hasAuth } = useAuth()
  const router = useRouter()

  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 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({
    status: undefined,
    flow_type: undefined, // 流程类型筛选
    old_asset_keyword: '',
    new_asset_keyword: '',
    created_at_range: [],
    created_at_start: '',
    created_at_end: ''
  })

  // 创建换货单表单
  const createForm = reactive({
    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)

  // 发货表单
  const shipForm = reactive({
    new_identifier: '',
    express_company: '',
    express_no: '',
    migrate_data: true
  })

  const shipRules = reactive<FormRules>({
    new_identifier: [{ required: true, message: '请输入新资产标识符', trigger: 'blur' }],
    express_company: [{ required: true, message: '请输入快递公司', trigger: 'blur' }],
    express_no: [{ required: true, message: '请输入快递单号', trigger: 'blur' }]
  })

  type ShopSelectableOption = {
    shop_id?: number | null
    shop_name?: string | null
  }

  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: 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: 'input',
      config: {
        placeholder: '请输入旧资产标识',
        clearable: true
      }
    },
    {
      label: '新资产',
      prop: 'new_asset_keyword',
      type: 'input',
      config: {
        placeholder: '请输入新资产标识',
        clearable: true
      }
    },
    {
      label: '创建时间',
      prop: 'created_at_range',
      type: 'date',
      config: {
        type: 'daterange',
        rangeSeparator: '至',
        startPlaceholder: '开始日期',
        endPlaceholder: '结束日期',
        valueFormat: 'YYYY-MM-DD'
      }
    }
  ]

  // 动态列配置
  const { columnChecks, columns } = useCheckedColumns(() => [
    {
      prop: 'exchange_no',
      label: '换货单号',
      width: 220,
      formatter: (row: any) =>
        h(
          ElButton,
          {
            type: 'primary',
            link: true,
            onClick: () => handleViewDetail(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: '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 getAssetTypeName = (assetType?: string | null) => {
    if (assetType === 'iot_card') return '物联网卡'
    if (assetType === 'device') return '设备'
    return '--'
  }

  // 加载换货单列表
  const loadExchangeList = async () => {
    loading.value = true
    try {
      // 过滤掉空值参数
      const params: any = {
        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.created_at_start) {
        params.created_at_start = searchForm.created_at_start
      }
      if (searchForm.created_at_end) {
        params.created_at_end = searchForm.created_at_end
      }

      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.created_at_start = searchForm.created_at_range[0] || ''
      searchForm.created_at_end = searchForm.created_at_range[1] || ''
    } else {
      searchForm.created_at_start = ''
      searchForm.created_at_end = ''
    }
    pagination.page = 1
    loadExchangeList()
  }

  // 重置
  const handleReset = () => {
    searchForm.old_asset_keyword = ''
    searchForm.new_asset_keyword = ''
    searchForm.created_at_range = []
    searchForm.created_at_start = ''
    searchForm.created_at_end = ''
    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 || []
        if (oldIotCardOptions.value.length === 0) {
          ElMessage.info('暂无可用的IoT卡')
        }
      }
    } 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 || []
        if (oldDeviceOptions.value.length === 0) {
          ElMessage.info('暂无可用的设备')
        }
      }
    } 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 || []
        if (oldIotCardOptions.value.length === 0) {
          ElMessage.info('未找到匹配的IoT卡')
        }
      }
    } 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 || []
        if (oldDeviceOptions.value.length === 0) {
          ElMessage.info('未找到匹配的设备')
        }
      }
    } 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 = []
      ElMessage.warning('请先选择旧资产')
      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 || []
        if (newIotCardOptions.value.length === 0) {
          ElMessage.info('未找到匹配的IoT卡')
        }
      }
    } 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 || []
        if (newIotCardOptions.value.length === 0) {
          ElMessage.info('未找到匹配的IoT卡')
        }
      }
    } 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 || []
        if (newIotCardOptions.value.length === 0) {
          ElMessage.info('暂无同店铺可用的新资产')
        }
      }
    } 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 && res.data) {
        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 = []
      ElMessage.warning('请先选择旧资产')
      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 || []
        if (newDeviceOptions.value.length === 0) {
          ElMessage.info('未找到匹配的设备')
        }
      }
    } 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 || []
        if (newDeviceOptions.value.length === 0) {
          ElMessage.info('未找到匹配的设备')
        }
      }
    } 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 || []
        if (newDeviceOptions.value.length === 0) {
          ElMessage.info('暂无同店铺可用的新资产')
        }
      }
    } 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 && res.data) {
        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

      createLoading.value = true
      try {
        const exchangeReason =
          createForm.exchange_reason === EXCHANGE_REASON_OTHER
            ? createForm.exchange_reason_other.trim()
            : createForm.exchange_reason

        const requestData: any = {
          exchange_reason: exchangeReason,
          old_asset_type: createForm.old_asset_type,
          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)
        if (res.code === 0) {
          ElMessage.success('换货单创建成功')
          createDialogVisible.value = false
          await loadExchangeList()
          return
        }

        ElMessage.error(res.msg || '换货单创建失败')
      } catch (error: any) {
        console.error('创建换货单失败:', error)
      } finally {
        createLoading.value = false
      }
    })
  }

  // 关闭创建对话框
  const handleCloseCreateDialog = () => {
    createFormRef.value?.resetFields()
    // 清空搜索选项
    oldIotCardOptions.value = []
    oldDeviceOptions.value = []
    newIotCardOptions.value = []
    newDeviceOptions.value = []
  }

  // 查看详情
  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' // 历史数据兼容

    // 直接换货不支持任何操作（发货、确认完成、取消）
    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) {
      if (hasAuth('exchange:complete')) {
        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 = (row: ExchangeResponse) => {
    if (completeLoadingId.value === row.id) return

    completeLoadingId.value = row.id

    ElMessageBox.confirm('确定要确认换货完成吗？', '确认操作', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      beforeClose: async (action, instance, done) => {
        if (action !== 'confirm') {
          done()
          return
        }

        instance.confirmButtonLoading = true
        instance.confirmButtonText = '提交中...'

        try {
          const res = await ExchangeService.completeExchange(row.id)
          if (res.code === 0) {
            await refreshExchangeDetail(row.id)
            await loadExchangeList()
            ElMessage.success('操作成功')
            done()
            return
          }

          ElMessage.error(res.msg || '确认完成失败')
        } catch (error) {
          console.error('确认完成失败:', error)
        } finally {
          instance.confirmButtonLoading = false
          instance.confirmButtonText = '确定'
        }
      }
    })
      .then(() => {})
      .finally(() => {
        completeLoadingId.value = null
      })
      .catch(() => {})
  }

  // 旧资产转新
  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()
  })
</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;
    }
  }
</style>
