<template>
  <ArtTableFullScreen>
    <div class="exchange-management-page" id="table-full-screen">
      <!-- 搜索栏 -->
      <ArtSearchBar
        v-model:filter="searchForm"
        :items="searchFormItems"
        :show-expand="false"
        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="exchange_reason">
              <ElInput
                v-model="createForm.exchange_reason"
                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"
                style="width: 100%"
                clearable
              >
                <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"
                style="width: 100%"
                clearable
              >
                <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 label="备注">
              <ElInput
                v-model="createForm.remark"
                type="textarea"
                :rows="2"
                placeholder="请输入备注（可选）"
              />
            </ElFormItem>
          </ElForm>

          <template #footer>
            <div class="dialog-footer">
              <ElButton @click="createDialogVisible = false">取消</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 label="新资产标识符" prop="new_identifier">
              <ElInput
                v-model="shipForm.new_identifier"
                placeholder="请输入新资产标识符(ICCID/虚拟号/IMEI/SN)"
              />
            </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">取消</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 { 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 searchForm = reactive({
    status: undefined,
    identifier: '',
    created_at_start: '',
    created_at_end: ''
  })

  // 创建换货单表单
  const createForm = reactive({
    exchange_reason: '',
    old_asset_type: '',
    old_identifier: '',
    remark: ''
  })

  const createRules = reactive<FormRules>({
    exchange_reason: [{ required: true, message: '请输入换货原因', trigger: 'blur' }],
    old_asset_type: [{ required: true, message: '请选择旧资产类型', trigger: 'change' }],
    old_identifier: [{ required: true, message: '请选择旧资产标识符', trigger: 'change' }]
  })

  // 旧资产搜索相关
  const oldIotCardOptions = ref<StandaloneIotCard[]>([])
  const oldCardSearchLoading = ref(false)
  const oldDeviceOptions = ref<Device[]>([])
  const oldDeviceSearchLoading = ref(false)

  // 发货表单
  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' }]
  })

  // 分页
  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: 'identifier',
      type: 'input',
      config: {
        placeholder: '请输入资产标识符',
        clearable: true
      }
    },
    {
      label: '创建时间',
      prop: 'created_at_range',
      type: 'date',
      config: {
        type: 'datetimerange',
        rangeSeparator: '至',
        startPlaceholder: '开始时间',
        endPlaceholder: '结束时间',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    }
  ]

  // 动态列配置
  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: 'old_asset_type',
      label: '旧资产类型',
      width: 120,
      formatter: (row: any) => (row.old_asset_type === 'iot_card' ? 'IoT卡' : '设备')
    },
    {
      prop: 'old_asset_identifier',
      label: '旧资产标识符',
      width: 220
    },
    {
      prop: 'new_asset_identifier',
      label: '新资产标识符',
      width: 180,
      formatter: (row: any) => row.new_asset_identifier
    },
    {
      prop: 'status',
      label: '状态',
      width: 130,
      formatter: (row: any) => h(ElTag, { type: getStatusType(row.status) }, () => row.status_text)
    },
    {
      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 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.identifier) {
        params.identifier = searchForm.identifier
      }
      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 = () => {
    pagination.page = 1
    loadExchangeList()
  }

  // 重置
  const handleReset = () => {
    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 handleOldAssetTypeChange = async () => {
    // 清空旧资产标识符
    createForm.old_identifier = ''
    oldIotCardOptions.value = []
    oldDeviceOptions.value = []

    // 根据类型加载默认数据
    if (createForm.old_asset_type === 'iot_card') {
      await loadDefaultIotCards()
    } else if (createForm.old_asset_type === 'device') {
      await loadDefaultDevices()
    }
  }

  // 加载默认IoT卡列表
  const loadDefaultIotCards = async () => {
    oldCardSearchLoading.value = true
    try {
      const res = await CardService.getStandaloneIotCards({
        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({
        iccid: 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
    }
  }

  // 确认创建
  const handleConfirmCreate = () => {
    createFormRef.value?.validate(async (valid) => {
      if (!valid) return

      createLoading.value = true
      try {
        const res = await ExchangeService.createExchange(createForm)
        if (res.code === 0) {
          ElMessage.success('换货单创建成功')
          createDialogVisible.value = false
          await loadExchangeList()
        }
      } catch (error) {
        console.error('创建换货单失败:', error)
      } finally {
        createLoading.value = false
      }
    })
  }

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

  // 查看详情
  const handleViewDetail = (row: any) => {
    router.push(`${RoutesAlias.ExchangeDetail}/${row.id}`)
  }

  // 获取操作按钮
  const getActions = (row: ExchangeResponse) => {
    const actions: any[] = []
    const status = row.status

    // 状态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 = (row: ExchangeResponse) => {
    currentExchangeRow.value = row
    // 重置表单
    shipForm.new_identifier = ''
    shipForm.express_company = ''
    shipForm.express_no = ''
    shipForm.migrate_data = true
    shipDialogVisible.value = true
  }

  // 确认发货
  const handleConfirmShip = () => {
    shipFormRef.value?.validate(async (valid) => {
      if (!valid || !currentExchangeRow.value) return

      shipLoading.value = true
      try {
        const res = await ExchangeService.shipExchange(currentExchangeRow.value.id, shipForm)
        if (res.code === 0) {
          ElMessage.success('发货成功')
          shipDialogVisible.value = false
          await loadExchangeList()
        }
      } catch (error) {
        console.error('发货失败:', error)
      } finally {
        shipLoading.value = false
      }
    })
  }

  // 关闭发货对话框
  const handleCloseShipDialog = () => {
    shipFormRef.value?.resetFields()
  }

  // 确认完成
  const handleCompleteExchange = (row: ExchangeResponse) => {
    ElMessageBox.confirm('确定要确认换货完成吗？', '确认操作', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        try {
          const res = await ExchangeService.completeExchange(row.id)
          if (res.code === 0) {
            ElMessage.success('操作成功')
            await loadExchangeList()
          }
        } catch (error) {
          console.error('确认完成失败:', error)
        }
      })
      .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%;
  }
</style>
