<template>
  <IeModal title="关联校区" confirmText="确认关联" ref="modalRef" width="500px" @beforeClose="handleBeforeClose"
    @confirm="handleConfirm">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="卡号段" prop="cardNoRange" :required="!cardIds || cardIds.length === 0">
        <div class="flex items-center gap-x-3">
          <el-input v-model="form.begin" type="text" maxlength="8" v-number class="w-[160px]!" 
                    placeholder="请输入开始卡号" :disabled="cardIds && cardIds.length > 0" />
          <span class="text-gray-500">-</span>
          <el-input v-model="form.end" type="text" maxlength="8" v-number class="w-[160px]!" 
                    placeholder="请输入结束卡号" :disabled="cardIds && cardIds.length > 0" />
        </div>
        <div v-if="cardIds && cardIds.length > 0" class="text-sm text-gray-500 mt-1">
          已选择 {{ cardIds.length }} 张卡片，将使用选中的卡片进行关联
        </div>
      </el-form-item>
      <el-form-item label="校区" prop="campusId" required>
        <ie-select v-model="selectedCampus" :options="campusList" label-key="name" value-key="id" filterable
          class="w-[350px]!" @change="handleCampusChange" />
      </el-form-item>
      <el-form-item label="校区班级" prop="campusClassId">
        <ie-select v-model="selectedCampusClass" :options="campusClassOptions" label-key="name" value-key="classId" filterable
          clearable class="w-[350px]!" :disabled="!selectedCampus" />
      </el-form-item>
    </el-form>
  </IeModal>
</template>
<script setup>
import useSchool from '@/hooks/useSchool';
import IeModal from '@/components/IeModal/index.vue';
import IeSelect from '@/components/IeSelect/index.vue';

import { associateCampus } from '@/api/dz/cards';
import { getClassesByCampusId } from '@/api/dz/classes';
import { getCurrentInstance, watchEffect, ref } from 'vue';

const { proxy } = getCurrentInstance();

const {
  reset,
  campusList,
  selectedCampus,
  getCampusList
} = useSchool({ autoLoad: false });

const campusClassOptions = ref([]);
const selectedCampusClass = ref(null);

const modalRef = ref(null);
const formRef = ref(null);
const cardIds = ref(null) // 选中的卡片ID列表
const form = ref({
  institutionId: null,
  cardType: null,
  count: 1,
})
// 自定义验证
const validateCardNoRange = (rule, value, callback) => {
  // 如果有选中的卡片ID，则不需要验证卡号段
  if (cardIds.value && cardIds.value.length > 0) {
    callback()
    return
  }
  // 如果没有选中卡片，则需要验证卡号段
  if (!form.value.begin || !form.value.end) {
    callback(new Error('请输入卡号段或选择卡片'))
  } else if (Number(form.value.begin) > Number(form.value.end)) {
    callback(new Error('开始卡号不能大于结束卡号'))
  } else {
    callback()
  }
}

watchEffect(() => {
  form.value.cardNoRange = `${form.value.begin}-${form.value.end}`;
  form.value.campusId = selectedCampus.value;
  form.value.campusClassId = selectedCampusClass.value;
})

/** 校区变化处理 */
function handleCampusChange() {
  selectedCampusClass.value = null;
  campusClassOptions.value = [];
  if (selectedCampus.value) {
    getClassesByCampusId({ campusId: selectedCampus.value }).then(response => {
      campusClassOptions.value = response.data || [];
    });
  }
}

const rules = ref({
  cardNoRange: [
    { validator: validateCardNoRange, trigger: ['blur', 'change'] },
  ],
  campusId: [
    { required: true, message: '请选择校区', trigger: 'change' },
  ],
})

const handleBeforeClose = () => {
  form.value = {};
  cardIds.value = null;
  selectedCampusClass.value = null;
  campusClassOptions.value = [];
  reset();
}


const open = (selectedCardIds = null) => {
  getCampusList();
  form.value = {};
  // 如果传入了选中的卡片ID列表，则使用它
  cardIds.value = selectedCardIds && selectedCardIds.length > 0 ? selectedCardIds : null;
  modalRef.value.open()
}
const close = () => {
  form.value = {};
  cardIds.value = null;
  selectedCampusClass.value = null;
  campusClassOptions.value = [];
  reset();
  modalRef.value.close()
}
const emit = defineEmits(['refresh'])
const handleConfirm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      modalRef.value.showLoading()
      // 如果有选中的卡片ID，使用cardIds；否则使用begin和end
      const params = {
        campusId: form.value.campusId,
        campusClassId: form.value.campusClassId
      }
      
      if (cardIds.value && cardIds.value.length > 0) {
        // 使用选中的卡片ID列表
        params.cardIds = Array.isArray(cardIds.value) ? cardIds.value.join(",") : cardIds.value
      } else {
        // 使用卡号段
        params.begin = form.value.begin
        params.end = form.value.end
      }
      
      associateCampus(params).then(res => {
        proxy.$modal.msgSuccess('关联校区成功')
        close();
        setTimeout(() => {
          emit('refresh')
        }, 300);
      }).finally(() => {
        modalRef.value.hideLoading()
      });
    }
  })
}
defineExpose({
  open,
  close
})
</script>
<style lang="scss" scoped></style>