<template>
  <el-dialog
    title="直接申请"
    v-model="visible"
    width="500px"
    append-to-body
    align-center
    :center="true"
    :destroy-on-close="true"
  >
    <div class="apply-card-content">
      <el-form
        ref="applyCardFormRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <!-- 卡号段 -->
        <el-form-item label="卡号段" :required="true">
          <div style="display: flex; align-items: center; gap: 10px">
            <el-form-item prop="beginCardNo" style="flex: 1; margin-bottom: 0">
              <el-input
                v-model="form.beginCardNo"
                placeholder="开始卡号"
                style="width: 100%"
              />
            </el-form-item>
            <span>-</span>
            <el-form-item prop="endCardNo" style="flex: 1; margin-bottom: 0">
              <el-input
                v-model="form.endCardNo"
                placeholder="结束卡号"
                style="width: 100%"
              />
            </el-form-item>
          </div>
        </el-form-item>

        <!-- 学校 -->
        <el-form-item label="学校" prop="schoolId">
          <el-select
            v-model="form.schoolId"
            placeholder="请选择学校"
            style="width: 100%"
          >
            <el-option
              v-for="school in campusList"
              :key="school.id"
              :label="school.name"
              :value="school.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          <svg-icon
            icon-class="lightning"
            class="mr-1"
            style="font-size: 14px"
          />
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from "vue";
import { requestOpenCard } from "@/api/dz/cards";
import { listUniversity } from "@/api/dz/school";
import { associateCampus, getCampusList } from "@/api/dz/cards";

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  selectedCards: {
    type: Array,
    default: () => [],
  },
});

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

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

const applyCardFormRef = ref();
const loading = ref(false);
const schoolList = ref([]);
const campusList = ref([]);

const form = ref({
  beginCardNo: "",
  endCardNo: "",
  schoolId: null,
});

const rules = {
  beginCardNo: [
    { required: true, message: "开始卡号不能为空", trigger: "blur" },
  ],
  endCardNo: [{ required: true, message: "结束卡号不能为空", trigger: "blur" }],
  schoolId: [{ required: true, message: "学校不能为空", trigger: "change" }],
};

// 获取校区列表
async function getCampusListData() {
  try {
    const response = await getCampusList({ pageNum: 1, pageSize: 1000 });
    if (response.code === 200) {
      campusList.value = response.data || [];
    }
  } catch (error) {
    console.error("获取校区列表失败:", error);
  }
}

// 获取所有学校列表
async function getAllSchools() {
  try {
    const response = await listUniversity({
      pageNum: 1,
      pageSize: 1000,
    });
    if (response.code === 200) {
      // 处理API返回的数据结构
      let schoolData = [];

      // 检查是否有rows字段（直接在response中）
      if (response.rows) {
        schoolData = response.rows;
      }
      // 检查是否有data.rows字段
      else if (response.data && response.data.rows) {
        schoolData = response.data.rows;
      }
      // 检查是否有data数组
      else if (response.data && Array.isArray(response.data)) {
        schoolData = response.data;
      }
      // 检查是否有data对象
      else if (response.data && response.data.id) {
        schoolData = [response.data];
      }

      schoolList.value = schoolData;
      console.log("所有学校数据:", schoolData);
    }
  } catch (error) {
    console.error("获取所有学校列表失败:", error);
    schoolList.value = [];
  }
}

// 自动填充卡号段
function autoFillCardRange() {
  if (props.selectedCards && props.selectedCards.length > 0) {
    const cardNos = props.selectedCards
      .map((card) => card.cardNo || card.id)
      .filter((cardNo) => cardNo && cardNo !== "未知")
      .sort();

    if (cardNos.length > 0) {
      const minCardNo = cardNos[0];
      const maxCardNo = cardNos[cardNos.length - 1];

      // 开始卡号段是最小卡号段的整十数部分
      const minCardNoNum = parseInt(minCardNo);
      const beginCardNo = Math.floor(minCardNoNum / 10) * 10;

      form.value.beginCardNo = beginCardNo.toString();
      form.value.endCardNo = maxCardNo;
    }
  }
}

// 重置表单
function resetForm() {
  form.value = {
    beginCardNo: "",
    endCardNo: "",
    schoolId: null,
  };
}

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

// 提交申请
async function handleSubmit() {
  applyCardFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true;
        const begin = form.value.beginCardNo;
        const end = form.value.endCardNo;
        const schoolId = form.value.schoolId;

        if (!begin || !end) {
          throw new Error("请填写完整的卡号段");
        }
        if (!schoolId) {
          throw new Error("请选择学校");
        }

        await requestOpenCard(schoolId, begin, end);
        emit("success", "申请开卡成功!");
        visible.value = false;
        resetForm();
      } catch (error) {
        console.error("申请开卡失败:", error);
        emit("confirm", { error: error.message });
      } finally {
        loading.value = false;
      }
    }
  });
}

// 监听弹窗关闭，重置表单
watch(visible, (newVal) => {
  if (!newVal) {
    resetForm();
  } else {
    getCampusListData();
    autoFillCardRange();
  }
});
</script>

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

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