<template>
  <IeModal :title="title" :confirmText="confirmButtonText" ref="modalRef" width="500px" @confirm="handleConfirm">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="平台机构" prop="institutionId" :required="true">
        <ie-institution-select v-model="form.institutionId" />
      </el-form-item>
      <el-form-item label="卡类型" prop="cardType">
        <ie-select v-model="form.cardType" :options="card_type" />
      </el-form-item>
      <el-form-item label="卡数量" prop="count">
        <el-input-number v-model="form.count" :min="1" :max="10000" :step="1" :precision="0" class="w-full!" />
      </el-form-item>
    </el-form>
  </IeModal>
</template>
<script setup>
import IeModal from '@/components/IeModal/index.vue';
import IeSelect from '@/components/IeSelect/index.vue';
import IeInstitutionSelect from '@/components/IeInstitutionSelect/index.vue';
import { issueCard } from '@/api/dz/cards';
import { getCurrentInstance } from 'vue';

const { proxy } = getCurrentInstance();
const {
  card_type,
} = proxy.useDict("card_type");

const modalRef = ref(null);
const formRef = ref(null);
const form = ref({
  institutionId: null,
  cardType: null,
  count: 1,
})
const operation = ref('add')
const rules = ref({
  institutionId: [{ required: true, message: '请选择平台机构', trigger: 'change' }],
  cardType: [{ required: true, message: '请选择卡类型', trigger: 'change' }],
  count: [{ required: true, message: '请输入卡数量', trigger: 'blur' }],
})
const title = computed(() => {
  return operation.value === 'add' ? '制卡' : '修改';
})
const confirmButtonText = computed(() => {
  return operation.value === 'add' ? '确认制卡' : '确认修改';
})

const open = (type = 'add', data = { institutionId: null, cardType: null, count: 1 }) => {
  operation.value = type;
  form.value = data;
  modalRef.value.open()
}
const close = () => {
  modalRef.value.close()
}
const emit = defineEmits(['refresh'])
const handleConfirm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      const { institutionId, cardType, count } = form.value;
      modalRef.value.showLoading()
      issueCard(institutionId, cardType, count).then(res => {
        proxy.$modal.msgSuccess('制卡成功')
        close();
        setTimeout(() => {
          emit('refresh')
        }, 300);
      }).finally(() => {
        modalRef.value.hideLoading()
      })
    }
  })
}
defineExpose({
  open,
  close
})
</script>
<style lang="scss" scoped></style>