<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="deptId" required>
        <ie-institution-select v-model="form.deptId" class="w-[350px]!" clearable />
      </el-form-item>
      <el-form-item label="卡类型" prop="cardType">
        <ie-select v-model="form.cardType" :options="card_type" class="w-[350px]!" clearable />
      </el-form-item>
      <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" :deptId="form.deptId" class="w-[350px]!" filterable clearable />
      </el-form-item>
      <el-form-item label="省份" prop="provinceId">
        <ie-select v-model="area.selected" v-model:selectedItem="area.selectedItem" :options="area.list"
          label-key="areaName" value-key="areaId" class="w-[350px]!" clearable />
      </el-form-item>
      <el-form-item label="学校" prop="schoolId">
        <ie-select v-model="selectedSchool" :options="schoolList" label-key="name" value-key="id" filterable
          class="w-[350px]!" clearable />
      </el-form-item>
      <el-form-item label="考生类型" prop="assignExamType">
        <ie-select v-model="selectedExamType" :options="examTypeList" label-key="dictLabel" value-key="dictValue"
          class="w-[350px]!" clearable />
      </el-form-item>
      <el-form-item v-if="form.cardType === '9'" label="有效期" prop="days">
        <el-input-number v-model="form.days" :min="1" :max="10000" :step="1" :precision="0" class="w-full!">
          <template #suffix>天</template>
        </el-input-number>
      </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 { assignCard } from '@/api/dz/cards';
import { getCurrentInstance, watchEffect } from 'vue';


const { proxy } = getCurrentInstance();
const {
  card_type,
  exam_type,
} = proxy.useDict("card_type", "exam_type");
const {
  init,
  reset,
  area,
  schoolList,
  selectedSchool,
  examTypeList,
  selectedExamType
} = useSchool({ autoLoad: false, loadExamType: true, loadClass: false });

const modalRef = ref(null);
const formRef = ref(null);
const defaultForm = {
  deptId: null,
  agentId: null,
  cardType: '',
  count: 1,
  assignExamType: '',
  days: 1,
};

const form = ref({ ...defaultForm })
// 自定义验证
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.selected;
  form.value.location = area.selectedItem?.shortName;
  form.value.schoolId = selectedSchool.value;
  form.value.assignExamType = selectedExamType.value;
});

const rules = ref({
  deptId: [
    { required: true, message: '请选择平台机构', trigger: 'change' },
  ],
  cardType: [
    { required: true, message: '请选择卡类型', trigger: 'change' },
  ],
  cardNoRange: [
    { validator: validateCardNoRange, trigger: ['blur', 'change'] },
  ],
  agentId: [
    { required: true, message: '请选择代理商', trigger: 'change' },
  ],
  days: [
    { required: true, message: '请输入有效期', trigger: 'change' },
  ],
})

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

const open = () => {
  init();
  form.value = { ...defaultForm };
  modalRef.value.open()
}
const close = () => {
  modalRef.value.close()
}
const emit = defineEmits(['refresh'])
const handleConfirm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      let { cardType, agentId, location, assignExamType, schoolId, days } = form.value;
      modalRef.value.showLoading()
      if (cardType !== '9') {
        days = undefined;
      }
      
      // 构建参数对象
      const params = {
        cardType,
        agentId,
        location,
        assignExamType,
        schoolId,
        days,
        begin: form.value.begin,
        end: form.value.end
      }
      
      assignCard(params).then(res => {
        proxy.$modal.msgSuccess('分配卡成功')
        close();
        setTimeout(() => {
          emit('refresh')
        }, 300);
      }).finally(() => {
        modalRef.value.hideLoading()
      });
    }
  })
}
defineExpose({
  open,
  close
})
</script>
<style lang="scss" scoped></style>