<template>
  <el-dialog
    title="关联校区"
    v-model="visible"
    width="500px"
    append-to-body
    align-center
    :center="true"
    :destroy-on-close="true"
  >
    <div class="associate-campus-content">
      <el-form
        ref="associateCampusFormRef"
        :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="campusId" :required="true">
          <el-select
            v-model="form.campusId"
            placeholder="请选择校区"
            style="width: 100%"
          >
            <el-option
              v-for="campus in campusList"
              :key="campus.id"
              :label="campus.name"
              :value="campus.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="handleConfirm" :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 { associateCampus, getCampusSchoolList } 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 associateCampusFormRef = ref();
const loading = ref(false);
const campusList = ref([]);

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

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

// 获取校区列表
async function getCampusListData() {
  try {
    const response = await getCampusSchoolList({
      campus: true,
      pageNum: 1,
      pageSize: 9999, // 获取所有校区
    });
    if (response.code === 200) {
      // 处理API返回的数据结构
      let campusData = [];
      if (response.data) {
        campusData = Array.isArray(response.data) ? response.data : [];
      } else if (response.rows) {
        campusData = response.rows;
      } else if (response.list) {
        campusData = response.list;
      }

      // 确保数据格式符合配置要求
      campusData = campusData.map((item) => {
        // 如果API返回的是 {id, name, ...} 格式，直接使用
        if (item.id && item.name) {
          return item;
        }
        // 如果是其他格式，需要转换
        return {
          id: item.id || item.value || item.campusId,
          name: item.name || item.label || item.campusName || item.title,
        };
      });

      campusList.value = campusData;
    }
  } catch (error) {
    console.error("获取校区列表失败:", error);
    campusList.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: "",
    campusId: null,
  };
}

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

// 确认关联
async function handleConfirm() {
  associateCampusFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true;
        const begin = form.value.beginCardNo;
        const end = form.value.endCardNo;
        const campusId = form.value.campusId;

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

        await associateCampus(begin, end, campusId);
        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>
.associate-campus-content {
  padding: 20px 0;
}

.hint-text {
  color: #1890ff;
  font-size: 12px;
  margin-bottom: 20px;
  padding-left: 100px;
}

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