<template>
  <el-dialog
    title="重开"
    v-model="visible"
    width="400px"
    append-to-body
    align-center
    :center="true"
    :destroy-on-close="true"
  >
    <div class="reopen-card-confirm-content">
      <div class="confirm-item">
        <el-icon class="warning-icon">
          <Warning />
        </el-icon>
        <span class="confirm-text">
          {{ getConfirmMessage() }}
        </span>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm" :loading="loading"
          >确定</el-button
        >
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed } from "vue";
import { Warning } from "@element-plus/icons-vue";
import { reopenCard, listCards } from "@/api/dz/cards";

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  cardNo: {
    type: [String, Number, Array],
    default: "",
    // 卡号（字符串），重开时会自动转换为 cardId
  },
  cardIds: {
    type: Array,
    default: () => [],
    // 卡ID（数字数组），直接用于重开API
  },
});

const emit = defineEmits(["update:modelValue", "confirm", "success"]);

const loading = ref(false);

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

// 获取确认消息
function getConfirmMessage() {
  // 处理 cardNo 为数组的情况
  if (Array.isArray(props.cardNo) && props.cardNo.length > 0) {
    if (props.cardNo.length === 1) {
      return `是否确认重开VIP卡编号为${props.cardNo[0]}的数据项？`;
    } else {
      return `是否确认重开以下${
        props.cardNo.length
      }张VIP卡？\n${props.cardNo.join("、")}`;
    }
  }
  // 处理 cardNo 为单个值的情况
  else if (props.cardNo) {
    return `是否确认重开VIP卡编号为${props.cardNo}的数据项？`;
  }
  // 处理 cardIds 的情况
  else if (props.cardIds && props.cardIds.length > 0) {
    return `是否确认重开选中的${props.cardIds.length}张学习卡？`;
  }
  return "是否确认重开？";
}

// 取消
function handleCancel() {
  visible.value = false;
}

// 确认重开
async function handleConfirm() {
  try {
    loading.value = true;

    // 确定要重开的卡ID
    let cardIdsToReopen = [];

    // 处理 cardNo 为数组的情况
    if (Array.isArray(props.cardNo) && props.cardNo.length > 0) {
      // 根据 cardNo 数组查询对应的 cardId
      for (const cardNo of props.cardNo) {
        const cardInfo = await getCardIdByCardNo(cardNo);
        if (cardInfo) {
          cardIdsToReopen.push(cardInfo.cardId);
        }
      }
    }
    // 处理 cardNo 为单个值的情况
    else if (props.cardNo) {
      const cardInfo = await getCardIdByCardNo(props.cardNo);
      if (cardInfo) {
        cardIdsToReopen.push(cardInfo.cardId);
      }
    }
    // 处理 cardIds 的情况（直接使用 cardId）
    else if (props.cardIds && props.cardIds.length > 0) {
      cardIdsToReopen = props.cardIds;
    }

    if (cardIdsToReopen.length === 0) {
      throw new Error("没有选择要重开的卡片");
    }

    // 调用重开API
    await reopenCard(cardIdsToReopen);

    emit("success", "重开成功!");
    visible.value = false;
  } catch (error) {
    console.error("重开失败:", error);
    emit("confirm", { error: error.message });
  } finally {
    loading.value = false;
  }
}

// 根据 cardNo 查询 cardId
async function getCardIdByCardNo(cardNo) {
  try {
    const response = await listCards({ cardNo: cardNo });
    if (response.code === 200 && response.rows && response.rows.length > 0) {
      return response.rows[0]; // 返回第一个匹配的卡片信息
    }
    return null;
  } catch (error) {
    console.error(`根据卡号 ${cardNo} 查询卡片信息失败:`, error);
    return null;
  }
}
</script>

<style scoped>
.reopen-card-confirm-content {
  padding: 20px 0;
}

.confirm-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.warning-icon {
  color: #e6a23c;
  font-size: 20px;
  margin-top: 2px;
  flex-shrink: 0;
}

.confirm-text {
  font-size: 14px;
  line-height: 1.5;
  color: #ffffff;
}

.dialog-footer {
  text-align: right;
}
</style>
