<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>
        <div class="flex items-center gap-x-3">
          <el-input v-model="form.begin" type="text" maxlength="8" v-number class="w-[160px]!" placeholder="请输入开始卡号" />
          <span class="text-gray-500">-</span>
          <el-input v-model="form.end" type="text" maxlength="8" v-number class="w-[160px]!" placeholder="请输入结束卡号" />
        </div>
      </el-form-item>
      <el-form-item label="代理商" prop="agentId" required>
        <ie-agent-select v-model="form.agentId" class="w-[350px]!" filterable />
      </el-form-item>
      <el-form-item label="省份" prop="provinceId" required>
        <ie-select v-model="area.selected" v-model:selectedItem="area.selectedItem" :options="area.list" label-key="areaName" value-key="areaId"
          class="w-[350px]!" />
      </el-form-item>
      <el-form-item label="学校" prop="schoolId" required>
        <ie-select v-model="selectedSchool" :options="schoolList" label-key="name" value-key="id" filterable
          class="w-[350px]!" />
      </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 IeAgentSelect from '@/components/IeAgentSelect/index.vue';
import IeInstitutionSelect from '@/components/IeInstitutionSelect/index.vue';
import { requestOpenCard } from '@/api/dz/cards';
import { getCurrentInstance, watchEffect } from 'vue';

const { proxy } = getCurrentInstance();

const {
  init,
  reset,
  area,
  schoolList,
  selectedSchool,
} = useSchool({ autoLoad: false, loadExamType: true });

const modalRef = ref(null);
const formRef = ref(null);
const form = ref({
  institutionId: null,
  cardType: null,
  count: 1,
})
// 自定义验证
const validateCardNoRange = (rule, value, callback) => {
  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.provinceId = area.selectedItem?.shortName;
  form.value.location = area.selectedItem?.shortName;
  form.value.schoolId = selectedSchool.value;
})

const rules = ref({
  cardNoRange: [
    { validator: validateCardNoRange, trigger: ['blur', 'change'] },
  ],
  agentId: [
    { required: true, message: '请选择代理商', trigger: 'change' },
  ],
  provinceId: [
    { required: true, message: '请选择省份', trigger: 'change' },
  ],
  schoolId: [
    { required: true, message: '请选择学校', trigger: 'change' },
  ],
})

const handleBeforeClose = () => {
  form.value = {};
  reset();
}


const open = () => {
  init();
  form.value = {};
  modalRef.value.open()
}
const close = () => {
  reset();
  modalRef.value.close()
}
const emit = defineEmits(['refresh'])
const handleConfirm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      modalRef.value.showLoading()
      const { agentId, location, schoolId, begin, end } = form.value;
      requestOpenCard(agentId, location, schoolId, begin, end).then(res => {
        proxy.$modal.msgSuccess('开卡申请成功')
        close();
        setTimeout(() => {
          emit('refresh')
        }, 300);
      }).finally(() => {
        modalRef.value.hideLoading()
      });
    }
  })
}
defineExpose({
  open,
  close
})
</script>
<style lang="scss" scoped></style>