<template>
  <ElDialog v-model="visible" title="切换SIM卡" width="600px">
    <div v-if="loading" style="padding: 40px; text-align: center">
      <ElIcon class="is-loading" :size="40"><Loading /></ElIcon>
      <div style="margin-top: 16px">加载设备绑定的卡列表中...</div>
    </div>

    <template v-else>
      <ElAlert
        v-if="bindingCards.length === 0"
        title="该设备暂无绑定的SIM卡"
        type="warning"
        :closable="false"
        style="margin-bottom: 20px"
      >
        <template #default>
          <div>当前设备没有绑定任何SIM卡,无法进行切换操作。</div>
          <div>请先为设备绑定SIM卡后再进行切换。</div>
        </template>
      </ElAlert>

      <ElForm
        v-if="bindingCards.length > 0"
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <ElFormItem label="目标ICCID" prop="target_iccid">
          <ElSelect
            v-model="form.target_iccid"
            placeholder="请选择要切换到的目标ICCID"
            style="width: 100%"
            clearable
          >
            <ElOption
              v-for="card in bindingCards"
              :key="card.iccid"
              :label="`${card.iccid} - 插槽${card.slot_position} - ${card.carrier_name}`"
              :value="card.iccid"
            >
              <div style="display: flex; align-items: center; justify-content: space-between">
                <span>{{ card.iccid }}</span>
                <ElTag size="small" style="margin-left: 10px">插槽{{ card.slot_position }}</ElTag>
              </div>
            </ElOption>
          </ElSelect>
          <div style="margin-top: 8px; font-size: 12px; color: #909399">
            当前设备共绑定 {{ bindingCards.length }} 张SIM卡
          </div>
        </ElFormItem>
      </ElForm>
    </template>

    <template #footer>
      <ElButton @click="handleCancel">取消</ElButton>
      <ElButton
        v-if="bindingCards.length > 0"
        type="primary"
        @click="handleConfirm"
        :loading="confirmLoading"
      >
        确认切换
      </ElButton>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, watch } from 'vue'
  import {
    ElDialog,
    ElForm,
    ElFormItem,
    ElSelect,
    ElOption,
    ElButton,
    ElAlert,
    ElIcon,
    ElTag,
    ElMessage
  } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'
  import { Loading } from '@element-plus/icons-vue'
  import { DeviceService } from '@/api/modules'

  interface Props {
    modelValue: boolean
    deviceId: number
  }

  interface Emits {
    (e: 'update:modelValue', value: boolean): void
    (e: 'confirm', data: { target_iccid: string }): void
  }

  const props = defineProps<Props>()
  const emit = defineEmits<Emits>()

  const formRef = ref<FormInstance>()
  const loading = ref(false)
  const confirmLoading = ref(false)
  const bindingCards = ref<any[]>([])

  const form = reactive({
    target_iccid: ''
  })

  const rules: FormRules = {
    target_iccid: [{ required: true, message: '请选择目标ICCID', trigger: 'change' }]
  }

  const visible = computed({
    get: () => props.modelValue,
    set: (value) => emit('update:modelValue', value)
  })

  // 监听对话框打开，加载绑定卡列表
  watch(visible, async (newVal) => {
    if (newVal) {
      form.target_iccid = ''
      bindingCards.value = []
      await loadDeviceCards()
    }
  })

  const loadDeviceCards = async () => {
    if (!props.deviceId) return

    try {
      loading.value = true
      const res = await DeviceService.getDeviceCards(props.deviceId)
      if (res.code === 0 && res.data) {
        bindingCards.value = res.data.bindings || []
        if (bindingCards.value.length === 0) {
          ElMessage.warning('该设备暂无绑定的SIM卡')
        }
      }
    } catch (error) {
      console.error('加载设备绑定卡列表失败:', error)
      console.log('加载卡列表失败')
    } finally {
      loading.value = false
    }
  }

  const handleCancel = () => {
    visible.value = false
  }

  const handleConfirm = async () => {
    if (!formRef.value) return

    try {
      await formRef.value.validate()
      emit('confirm', {
        target_iccid: form.target_iccid
      })
    } catch (error) {
      console.error('表单验证失败:', error)
    }
  }
</script>

<style lang="scss" scoped></style>
