<template>
  <ArtTableFullScreen>
    <div class="manual-trigger-page" id="table-full-screen">
      <!-- 搜索栏 -->
      <ArtSearchBar
        v-model:filter="searchForm"
        :items="searchFormItems"
        :show-expand="false"
        label-width="100px"
        @reset="handleReset"
        @search="handleSearch"
      />

      <el-card shadow="never" class="art-table-card">
        <!-- 表格头部 -->
        <ArtTableHeader
          :columnList="columnOptions"
          v-model:columns="columnChecks"
          @refresh="handleRefresh"
        >
          <template #left>
            <el-button
              type="primary"
              @click="showBatchTriggerDialog"
              v-permission="'polling_manual_trigger_batch'"
            >
              批量触发
            </el-button>
            <el-button
              type="success"
              @click="showConditionTriggerDialog"
              v-permission="'polling_manual_trigger_condition'"
            >
              条件触发
            </el-button>
            <el-button
              type="info"
              @click="showSingleTriggerDialog"
              v-permission="'polling_manual_trigger_single'"
            >
              单卡触发
            </el-button>
          </template>
        </ArtTableHeader>

        <!-- 表格 -->
        <ArtTable
          ref="tableRef"
          row-key="id"
          :loading="loading"
          :data="tableData"
          :currentPage="pagination.page"
          :pageSize="pagination.page_size"
          :total="pagination.total"
          :marginTop="10"
          :actions="getActions"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
          <template #default>
            <el-table-column v-for="col in columns" :key="col.prop || col.type" v-bind="col">
              <template v-if="col.slots?.default === 'progress'" #default="scope">
                <div style="display: flex; gap: 8px; align-items: center">
                  <el-progress
                    :percentage="getProgressPercentage(scope.row)"
                    :stroke-width="6"
                    :show-text="false"
                    style="flex: 1"
                  />
                  <span style="width: 50px; font-size: 12px"
                    >{{ getProgressPercentage(scope.row) }}%</span
                  >
                </div>
              </template>
            </el-table-column>
          </template>
        </ArtTable>
      </el-card>

      <!-- 批量触发弹窗 -->
      <el-dialog
        v-model="batchDialogVisible"
        title="批量触发"
        width="80%"
        :close-on-click-modal="false"
        @close="handleBatchDialogClose"
      >
        <el-form ref="batchFormRef" :model="batchForm" :rules="batchRules" label-width="120">
          <div class="card-selection-wrapper">
            <div class="card-search-bar">
              <ArtSearchBar
                v-model:filter="cardSearchForm"
                :items="cardSearchFormItems"
                label-width="100"
                show-expand
                @reset="handleCardSearchReset"
                @search="handleCardSearch"
              />
            </div>
            <div class="card-table-header">
              <span>已选择 {{ selectedBatchCards.length }} 张卡</span>
              <el-form-item
                label="任务类型"
                prop="task_type"
                label-width="80"
                style="width: 300px; margin-bottom: 0"
              >
                <el-select
                  v-model="batchForm.task_type"
                  placeholder="请选择任务类型"
                  style="width: 100%"
                >
                  <el-option label="实名认证轮询" value="polling:realname" />
                  <el-option label="卡数据轮询" value="polling:carddata" />
                  <el-option label="套餐轮询" value="polling:package" />
                </el-select>
              </el-form-item>
            </div>
            <ArtTable
              ref="batchCardTableRef"
              row-key="id"
              :loading="batchCardLoading"
              :data="batchCardList"
              :currentPage="batchCardPagination.page"
              :pageSize="batchCardPagination.pageSize"
              :total="batchCardPagination.total"
              height="40vh"
              @size-change="handleBatchCardPageSizeChange"
              @current-change="handleBatchCardPageChange"
              @selection-change="handleBatchCardSelectionChange"
            >
              <template #default>
                <el-table-column type="selection" width="55" />
                <el-table-column v-for="col in batchCardColumns" :key="col.prop" v-bind="col" />
              </template>
            </ArtTable>
          </div>
        </el-form>
        <template #footer>
          <el-button @click="batchDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleBatchSubmit"
            :disabled="selectedBatchCards.length === 0"
          >
            确定
          </el-button>
        </template>
      </el-dialog>

      <!-- 条件触发弹窗 -->
      <el-dialog
        v-model="conditionDialogVisible"
        title="条件触发"
        width="700px"
        :close-on-click-modal="false"
      >
        <el-form
          ref="conditionFormRef"
          :model="conditionForm"
          :rules="conditionRules"
          label-width="120px"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="任务类型" prop="task_type">
                <el-select
                  v-model="conditionForm.task_type"
                  placeholder="请选择任务类型"
                  style="width: 100%"
                >
                  <el-option label="实名认证轮询" value="polling:realname" />
                  <el-option label="卡数据轮询" value="polling:carddata" />
                  <el-option label="套餐轮询" value="polling:package" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="限制数量" prop="limit">
                <el-input-number
                  v-model="conditionForm.limit"
                  :min="1"
                  :max="1000"
                  placeholder="最多1000"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="卡状态">
                <el-select
                  v-model="conditionForm.card_status"
                  placeholder="请选择卡状态"
                  clearable
                  style="width: 100%"
                >
                  <el-option label="未激活" value="inactive" />
                  <el-option label="已激活" value="activated" />
                  <el-option label="已停用" value="suspended" />
                  <el-option label="已注销" value="terminated" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="卡类型">
                <el-select
                  v-model="conditionForm.card_type"
                  placeholder="请选择卡类型"
                  clearable
                  style="width: 100%"
                >
                  <el-option label="普通卡" value="normal" />
                  <el-option label="行业卡" value="industry" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="运营商">
                <el-select
                  v-model="conditionForm.carrier_code"
                  placeholder="请选择运营商"
                  filterable
                  remote
                  :remote-method="remoteSearchCarrier"
                  clearable
                  no-data-text="暂无运营商数据"
                  style="width: 100%"
                >
                  <el-option
                    v-for="carrier in carrierList"
                    :key="carrier.id"
                    :label="carrier.carrier_name"
                    :value="carrier.carrier_code"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="店铺">
                <el-tree-select
                  v-model="conditionForm.shop_id"
                  :data="shopTreeData"
                  placeholder="请选择店铺"
                  filterable
                  clearable
                  check-strictly
                  :render-after-expand="false"
                  no-data-text="暂无店铺数据"
                  :props="{
                    label: 'shop_name',
                    value: 'id',
                    children: 'children'
                  }"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="启用轮询">
                <el-switch v-model="conditionForm.enable_polling" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <el-button @click="conditionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConditionSubmit">确定</el-button>
        </template>
      </el-dialog>

      <!-- 单卡触发弹窗 -->
      <el-dialog
        v-model="singleDialogVisible"
        title="单卡触发"
        width="500px"
        :close-on-click-modal="false"
      >
        <el-form ref="singleFormRef" :model="singleForm" :rules="singleRules" label-width="100px">
          <el-form-item label="卡ICCID" prop="card_id">
            <el-select
              v-model="singleForm.card_id"
              placeholder="请输入ICCID搜索"
              filterable
              remote
              :remote-method="remoteSearchCard"
              clearable
              no-data-text="暂无卡数据，请输入ICCID搜索"
              style="width: 100%"
            >
              <el-option
                v-for="card in cardList"
                :key="card.id"
                :label="card.iccid"
                :value="card.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="任务类型" prop="task_type">
            <el-select
              v-model="singleForm.task_type"
              placeholder="请选择任务类型"
              style="width: 100%"
            >
              <el-option label="实名认证轮询" value="polling:realname" />
              <el-option label="卡数据轮询" value="polling:carddata" />
              <el-option label="套餐轮询" value="polling:package" />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="singleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSingleSubmit">确定</el-button>
        </template>
      </el-dialog>
    </div>
  </ArtTableFullScreen>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, onMounted, nextTick, h } from 'vue'
  import {
    ElMessage,
    ElMessageBox,
    ElTag,
    ElProgress,
    type FormInstance,
    type FormRules
  } from 'element-plus'
  import {
    ManualTriggerService,
    CarrierService,
    ShopService,
    CardService,
    PackageSeriesService
  } from '@/api/modules'
  import type {
    ManualTriggerLog,
    ManualTriggerHistoryQueryParams,
    BatchManualTriggerRequest,
    ConditionManualTriggerRequest,
    TaskType
  } from '@/types/api'
  import type { SearchFormItem } from '@/types'
  import { formatDateTime } from '@/utils/business/format'
  import { useCheckedColumns } from '@/composables/useCheckedColumns'
  import { useAuth } from '@/composables/useAuth'
  const { hasAuth } = useAuth()
  const loading = ref(false)
  const tableData = ref<ManualTriggerLog[]>([])
  const tableRef = ref()

  const batchDialogVisible = ref(false)
  const conditionDialogVisible = ref(false)
  const singleDialogVisible = ref(false)

  const batchFormRef = ref<FormInstance>()
  const conditionFormRef = ref<FormInstance>()
  const singleFormRef = ref<FormInstance>()

  const carrierList = ref<any[]>([])
  const shopTreeData = ref<any[]>([])
  const cardList = ref<any[]>([])

  // 分页数据
  const pagination = reactive({
    page: 1,
    page_size: 10,
    total: 0
  })

  // 搜索表单
  const searchForm = reactive({
    task_type: undefined as TaskType | undefined
  })

  // 批量触发表单
  const batchForm = reactive({
    task_type: '' as TaskType | ''
  })

  // 批量触发弹窗中的卡列表相关数据
  const batchCardList = ref<any[]>([])
  const batchCardLoading = ref(false)
  const batchCardPagination = reactive({
    page: 1,
    pageSize: 20,
    total: 0
  })
  const selectedBatchCards = ref<any[]>([])
  const batchCardTableRef = ref()

  // 远程搜索相关
  const carrierLoading = ref(false)
  const searchCarrierOptions = ref<any[]>([])
  const searchSeriesOptions = ref<any[]>([])
  const seriesLoading = ref(false)

  // 卡搜索表单初始值
  const initialCardSearchState = {
    iccid: '',
    carrier_name: '',
    status: undefined,
    virtual_no: '',
    msisdn: '',
    device_virtual_no: '',
    series_id: undefined,
    is_distributed: undefined,
    is_replaced: undefined,
    iccid_start: '',
    iccid_end: ''
  }

  const cardSearchForm = reactive({ ...initialCardSearchState })

  // 卡列表搜索表单配置
  const cardSearchFormItems = computed<SearchFormItem[]>(() => [
    {
      label: 'ICCID',
      prop: 'iccid',
      type: 'input',
      config: {
        clearable: true,
        placeholder: '请输入ICCID'
      }
    },
    {
      label: '运营商名称',
      prop: 'carrier_name',
      type: 'select',
      config: {
        clearable: true,
        filterable: true,
        remote: true,
        remoteMethod: handleSearchCarrier,
        loading: carrierLoading.value,
        placeholder: '请选择或搜索运营商名称'
      },
      options: () =>
        searchCarrierOptions.value.map((c) => ({
          label: c.carrier_name,
          value: c.carrier_name
        }))
    },
    {
      label: '状态',
      prop: 'status',
      type: 'select',
      config: {
        clearable: true,
        placeholder: '全部'
      },
      options: () => [
        { label: '在库', value: 1 },
        { label: '已分销', value: 2 },
        { label: '已激活', value: 3 },
        { label: '已停用', value: 4 }
      ]
    },
    {
      label: '卡虚拟号',
      prop: 'virtual_no',
      type: 'input',
      config: {
        clearable: true,
        placeholder: '请输入卡虚拟号'
      }
    },
    {
      label: 'MSISDN',
      prop: 'msisdn',
      type: 'input',
      config: {
        clearable: true,
        placeholder: '请输入MSISDN'
      }
    },
    {
      label: '绑定设备虚拟号',
      prop: 'device_virtual_no',
      type: 'input',
      config: {
        clearable: true,
        placeholder: '请输入绑定设备虚拟号'
      }
    },
    {
      label: '套餐系列',
      prop: 'series_id',
      type: 'select',
      config: {
        clearable: true,
        filterable: true,
        remote: true,
        remoteMethod: handleSearchSeries,
        placeholder: '请选择或搜索套餐系列'
      },
      options: () =>
        searchSeriesOptions.value.map((s) => ({
          label: s.series_name,
          value: s.id
        }))
    },
    {
      label: '是否已分销',
      prop: 'is_distributed',
      type: 'select',
      config: {
        clearable: true,
        placeholder: '全部'
      },
      options: () => [
        { label: '是', value: true },
        { label: '否', value: false }
      ]
    },
    {
      label: '是否有换卡记录',
      prop: 'is_replaced',
      type: 'select',
      config: {
        clearable: true,
        placeholder: '全部'
      },
      options: () => [
        { label: '有换卡记录', value: true },
        { label: '无换卡记录', value: false }
      ]
    },
    {
      label: '是否绑定设备',
      prop: 'is_standalone',
      type: 'select',
      config: {
        clearable: true,
        placeholder: '全部'
      },
      options: () => [
        { label: '未绑定设备', value: true },
        { label: '已绑定设备', value: false }
      ]
    },
    {
      label: 'ICCID起始号',
      prop: 'iccid_start',
      type: 'input',
      config: {
        clearable: true,
        placeholder: '请输入ICCID起始号'
      }
    },
    {
      label: 'ICCID结束号',
      prop: 'iccid_end',
      type: 'input',
      config: {
        clearable: true,
        placeholder: '请输入ICCID结束号'
      }
    }
  ])

  // 卡列表列配置
  const batchCardColumns = computed(() => [
    {
      prop: 'iccid',
      label: 'ICCID',
      minWidth: 200
    },
    {
      prop: 'msisdn',
      label: 'MSISDN',
      width: 160
    },
    {
      prop: 'virtual_no',
      label: '卡虚拟号',
      width: 180,
      showOverflowTooltip: true,
      formatter: (row: any) => row.virtual_no || '-'
    },
    {
      prop: 'device_virtual_no',
      label: '绑定设备虚拟号',
      width: 180,
      showOverflowTooltip: true,
      formatter: (row: any) => row.device_virtual_no || '-'
    },
    {
      prop: 'card_category',
      label: '卡业务类型',
      width: 100,
      formatter: (row: any) => getCardCategoryText(row.card_category)
    },
    {
      prop: 'carrier_name',
      label: '运营商',
      width: 150,
      showOverflowTooltip: true
    },
    {
      prop: 'shop_name',
      label: '店铺名称',
      minWidth: 150,
      formatter: (row: any) => row.shop_name || '-'
    },
    {
      prop: 'series_name',
      label: '套餐系列',
      width: 150,
      formatter: (row: any) => row.series_name || '-'
    },
    {
      prop: 'status_name',
      label: '状态',
      width: 100
    },
    {
      prop: 'activation_status',
      label: '激活状态',
      width: 100,
      formatter: (row: any) => {
        const type = row.activation_status === 1 ? 'success' : 'info'
        const text = row.activation_status === 1 ? '已激活' : '未激活'
        return h(ElTag, { type }, () => text)
      }
    },
    {
      prop: 'network_status',
      label: '网络状态',
      width: 100,
      formatter: (row: any) => {
        const type = row.network_status === 1 ? 'success' : 'danger'
        const text = row.network_status === 1 ? '正常' : '停机'
        return h(ElTag, { type }, () => text)
      }
    },
    {
      prop: 'real_name_status',
      label: '实名状态',
      width: 100,
      formatter: (row: any) => {
        const type = row.real_name_status === 1 ? 'success' : 'warning'
        const text = row.real_name_status === 1 ? '已实名' : '未实名'
        return h(ElTag, { type }, () => text)
      }
    }
  ])

  // 获取批量触发弹窗中的卡列表
  const getBatchCardList = async () => {
    batchCardLoading.value = true
    try {
      const params: any = {
        page: batchCardPagination.page,
        page_size: batchCardPagination.pageSize,
        ...cardSearchForm
      }
      Object.keys(params).forEach((key) => {
        if (params[key] === '' || params[key] === undefined) {
          delete params[key]
        }
      })
      const res = await CardService.getStandaloneIotCards(params)
      if (res.code === 0) {
        batchCardList.value = res.data.items || []
        batchCardPagination.total = res.data.total || 0
      }
    } catch (error) {
      console.error(error)
    } finally {
      batchCardLoading.value = false
    }
  }

  // 搜索运营商
  const handleSearchCarrier = async (query: string) => {
    try {
      const params: any = { page: 1, page_size: 20 }
      if (query) {
        params.carrier_name = query
      }
      const res = await CarrierService.getCarriers(params)
      if (res.code === 0) {
        searchCarrierOptions.value = res.data.items || []
      }
    } catch (error) {
      console.error(error)
    }
  }

  // 搜索套餐系列
  const handleSearchSeries = async (query: string) => {
    seriesLoading.value = true
    try {
      const params: any = { page: 1, page_size: 20, status: 1 }
      if (query) {
        params.series_name = query
      }
      const res = await PackageSeriesService.getPackageSeries(params)
      if (res.code === 0) {
        searchSeriesOptions.value = res.data.items || []
      }
    } catch (error) {
      console.error(error)
    } finally {
      seriesLoading.value = false
    }
  }

  // 卡搜索
  const handleCardSearch = () => {
    batchCardPagination.page = 1
    getBatchCardList()
  }

  // 卡搜索重置
  const handleCardSearchReset = () => {
    Object.assign(cardSearchForm, { ...initialCardSearchState })
    batchCardPagination.page = 1
    getBatchCardList()
  }

  // 批量卡选择变化
  const handleBatchCardSelectionChange = (selection: any[]) => {
    if (selection.length > 1000) {
      ElMessage.warning('最多只能选择1000张卡')
      // 取消最后一个选择
      const lastSelected = selection[selection.length - 1]
      batchCardTableRef.value?.toggleRowSelection(lastSelected, false)
      return
    }
    selectedBatchCards.value = selection
  }

  // 批量卡分页大小变化
  const handleBatchCardPageSizeChange = () => {
    batchCardPagination.page = 1
    getBatchCardList()
  }

  // 批量卡分页页码变化
  const handleBatchCardPageChange = () => {
    getBatchCardList()
  }

  // 关闭批量触发弹窗
  const handleBatchDialogClose = () => {
    selectedBatchCards.value = []
    Object.assign(cardSearchForm, { ...initialCardSearchState })
    batchCardPagination.page = 1
    batchCardPagination.pageSize = 20
  }

  // 获取卡业务类型文本
  const getCardCategoryText = (category: string) => {
    const categoryMap: Record<string, string> = {
      normal: '普通卡',
      industry: '行业卡'
    }
    return categoryMap[category] || category
  }

  // 条件触发表单
  const conditionForm = reactive<ConditionManualTriggerRequest>({
    task_type: undefined as unknown as TaskType,
    limit: 100,
    card_status: undefined,
    card_type: undefined,
    carrier_code: undefined,
    enable_polling: undefined,
    package_ids: undefined,
    shop_id: undefined
  })

  // 单卡触发表单
  const singleForm = reactive({
    card_id: undefined as number | undefined,
    task_type: '' as TaskType | ''
  })

  const batchRules: FormRules = {
    task_type: [{ required: true, message: '请选择任务类型', trigger: 'change' }]
  }

  const conditionRules: FormRules = {
    task_type: [{ required: true, message: '请选择任务类型', trigger: 'change' }],
    limit: [{ required: true, message: '请输入限制数量', trigger: 'blur' }]
  }

  const singleRules: FormRules = {
    card_id: [{ required: true, message: '请输入卡ID', trigger: 'blur' }],
    task_type: [{ required: true, message: '请选择任务类型', trigger: 'change' }]
  }

  // 搜索表单配置
  const searchFormItems = computed<SearchFormItem[]>(() => [
    {
      label: '任务类型',
      prop: 'task_type',
      type: 'select',
      config: {
        clearable: true,
        placeholder: '请选择任务类型'
      },
      options: () => [
        { label: '实名认证轮询', value: 'polling:realname' },
        { label: '卡数据轮询', value: 'polling:carddata' },
        { label: '套餐轮询', value: 'polling:package' }
      ]
    }
  ])

  const getProgressPercentage = (row: ManualTriggerLog) => {
    if (row.total_count === 0) return 0
    return Math.round((row.processed_count / row.total_count) * 100)
  }

  // 动态列配置
  const { columnChecks, columns } = useCheckedColumns(() => [
    {
      prop: 'task_type_name',
      label: '任务类型',
      minWidth: 150
    },
    {
      prop: 'trigger_type_name',
      label: '触发类型',
      minWidth: 120
    },
    {
      prop: 'status_name',
      label: '状态',
      minWidth: 100
    },
    {
      label: '进度',
      minWidth: 200,
      slots: { default: 'progress' }
    },
    {
      prop: 'success_count',
      label: '成功数',
      minWidth: 100
    },
    {
      prop: 'failed_count',
      label: '失败数',
      minWidth: 100
    },
    {
      prop: 'triggered_at',
      label: '触发时间',
      minWidth: 180,
      formatter: (row: any) => formatDateTime(row.triggered_at)
    },
    {
      prop: 'completed_at',
      label: '完成时间',
      minWidth: 180,
      formatter: (row: any) => (row.completed_at ? formatDateTime(row.completed_at) : '-')
    }
  ])

  const columnOptions = computed(() =>
    columns.value.map((col) => ({
      label: col.label,
      prop: col.prop || col.label,
      visible: true
    }))
  )

  const loadData = async () => {
    loading.value = true
    try {
      const queryParams: ManualTriggerHistoryQueryParams = {
        page: pagination.page,
        page_size: pagination.page_size,
        ...searchForm
      }
      const { data } = await ManualTriggerService.getHistory(queryParams)
      tableData.value = data.items
      pagination.total = data.total
    } catch {
      console.log('加载触发历史失败')
    } finally {
      loading.value = false
    }
  }

  const handleSearch = () => {
    pagination.page = 1
    loadData()
  }

  const handleReset = () => {
    Object.assign(searchForm, {
      task_type: undefined
    })
    pagination.page = 1
    loadData()
  }

  const getActions = (row: ManualTriggerLog) => {
    const actions: any[] = []
    if (row.status === 'pending' || row.status === 'processing') {
      if (hasAuth('polling_manual:trigger_cancel')) {
        actions.push({
          label: '取消任务',
          type: 'warning',
          handler: () => handleCancelTask(row)
        })
      }
    }
    if (hasAuth('polling_manual:refresh')) {
      actions.push({
        label: '刷新',
        type: 'primary',
        handler: () => handleRefresh()
      })
    }
    return actions
  }

  const handleRefresh = () => {
    loadData()
  }

  const handleSizeChange = (size: number) => {
    pagination.page_size = size
    loadData()
  }

  const handleCurrentChange = (page: number) => {
    pagination.page = page
    loadData()
  }

  const showBatchTriggerDialog = () => {
    Object.assign(batchForm, {
      task_type: ''
    })
    selectedBatchCards.value = []
    batchCardPagination.page = 1
    batchCardPagination.pageSize = 20
    Object.assign(cardSearchForm, { ...initialCardSearchState })
    batchDialogVisible.value = true
    nextTick(() => {
      batchFormRef.value?.clearValidate()
      handleSearchCarrier('')
      handleSearchSeries('')
      getBatchCardList()
    })
  }

  const showConditionTriggerDialog = () => {
    Object.assign(conditionForm, {
      task_type: '',
      limit: 100,
      card_status: undefined,
      card_type: undefined,
      carrier_code: undefined,
      enable_polling: undefined,
      package_ids: undefined,
      shop_id: undefined
    })
    conditionDialogVisible.value = true
    nextTick(() => {
      conditionFormRef.value?.clearValidate()
    })
  }

  const showSingleTriggerDialog = () => {
    Object.assign(singleForm, {
      card_id: undefined,
      task_type: ''
    })
    singleDialogVisible.value = true
    loadCards() // 加载初始卡列表
    nextTick(() => {
      singleFormRef.value?.clearValidate()
    })
  }

  const handleBatchSubmit = async () => {
    if (!batchFormRef.value) return
    await batchFormRef.value.validate(async (valid) => {
      if (!valid) return

      try {
        const cardIds = selectedBatchCards.value.map((card) => card.id)

        if (cardIds.length === 0) {
          ElMessage.warning('请选择要触发的卡')
          return
        }

        if (cardIds.length > 1000) {
          ElMessage.warning('卡ID数量不能超过1000个')
          return
        }

        const requestData: BatchManualTriggerRequest = {
          task_type: batchForm.task_type as TaskType,
          card_ids: cardIds.length > 0 ? cardIds : undefined
        }

        await ManualTriggerService.batchTrigger(requestData)
        ElMessage.success('批量触发成功')
        batchDialogVisible.value = false
        await loadData()
      } catch {
        console.log('批量触发失败')
      }
    })
  }

  const handleConditionSubmit = async () => {
    if (!conditionFormRef.value) return
    await conditionFormRef.value.validate(async (valid) => {
      if (!valid) return

      try {
        const requestData: ConditionManualTriggerRequest = {
          task_type: conditionForm.task_type as TaskType,
          limit: conditionForm.limit,
          card_status: conditionForm.card_status,
          card_type: conditionForm.card_type,
          carrier_code: conditionForm.carrier_code,
          enable_polling: conditionForm.enable_polling,
          package_ids: conditionForm.package_ids,
          shop_id: conditionForm.shop_id
        }

        await ManualTriggerService.conditionTrigger(requestData)
        ElMessage.success('条件触发成功')
        conditionDialogVisible.value = false
        await loadData()
      } catch {
        console.log('条件触发失败')
      }
    })
  }

  const handleSingleSubmit = async () => {
    if (!singleFormRef.value) return
    await singleFormRef.value.validate(async (valid) => {
      if (!valid) return

      try {
        await ManualTriggerService.singleTrigger({
          card_id: singleForm.card_id!,
          task_type: singleForm.task_type as TaskType
        })
        ElMessage.success('单卡触发成功')
        singleDialogVisible.value = false
        await loadData()
      } catch {
        console.log('单卡触发失败')
      }
    })
  }

  const handleCancelTask = async (row: ManualTriggerLog) => {
    try {
      await ElMessageBox.confirm('确定要取消该任务吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })

      await ManualTriggerService.cancelTrigger({ trigger_id: row.id })
      ElMessage.success('任务已取消')
      await loadData()
    } catch (error) {
      if (error !== 'cancel') {
        console.log('取消任务失败')
      }
    }
  }

  // 加载运营商列表
  const loadCarriers = async (carrierName?: string) => {
    try {
      const { data } = await CarrierService.getCarriers({
        page: 1,
        page_size: 20,
        carrier_name: carrierName
      })
      carrierList.value = data.items || []
    } catch (error) {
      console.error('加载运营商列表失败', error)
    }
  }

  const remoteSearchCarrier = (query: string) => {
    if (query) {
      loadCarriers(query)
    } else {
      loadCarriers()
    }
  }

  // 加载店铺树形数据
  const loadShops = async () => {
    try {
      const { data } = await ShopService.getShops()
      shopTreeData.value = data.items || []
    } catch (error) {
      console.error('加载店铺列表失败', error)
    }
  }

  // 加载卡列表
  const loadCards = async (iccid?: string) => {
    try {
      const { data } = await CardService.getStandaloneIotCards({
        page: 1,
        page_size: 20,
        iccid: iccid
      })
      cardList.value = data.items || []
    } catch (error) {
      console.error('加载卡列表失败', error)
    }
  }

  const remoteSearchCard = (query: string) => {
    if (query) {
      loadCards(query)
    } else {
      loadCards()
    }
  }

  onMounted(() => {
    loadData()
    loadCarriers()
    loadShops()
  })
</script>

<style scoped lang="scss">
  .manual-trigger-page {
    display: flex;
    flex-direction: column;
    height: 100%;

    .card-selection-wrapper {
      .card-search-bar {
        display: block;
      }

      .card-table-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin: 10px 0;
        font-size: 14px;
        color: var(--el-text-color-primary);
      }
    }
  }
</style>
