<template>
  <BasicDialog ref="basicDialogRef" title="报废" @refresh="refreshFromData">
    <template #form>
      <BasicForm
        ref="basicFormRef"
        :formData="ruleFormData"
        :formRules="formRules"
        :formConfig="ruleFormConfig"
        style="margin-bottom: 15px"
      >
        <template #quantity>
          <el-input v-model.number="ruleFormData.quantity" placeholder="请输入报废数量" type="number" min="1" step="1">
          </el-input>
        </template>
      </BasicForm>
      <div class="discard-note">最多可报废数量：{{ supply?.currentQuantity }}</div>
    </template>
    <template #footer>
      <el-button type="primary" @click="handleSumbit">提交</el-button>
      <el-button @click="basicDialogRef?.closeDialog">取消</el-button>
    </template>
  </BasicDialog>
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  import { ElMessage } from 'element-plus';
  import BasicDialog from '@/components/BasicDialog.vue';
  import BasicForm from '@/components/BasicForm.vue';
  import { useFormConfigHook } from '@/hooks/useFormConfigHook';
  import { DiscardSuppliesForm, EmergencySupplyListResponse } from '@/types/emergency-supplier';
  import { discardEmergencySupply } from '@/api/emergency-supplier';
  import { SUPPLIES_DISCARD_FROM_CONFIG, SUPPLIES_DISCARD_FROM_DATA, SUPPLIES_DISCARD_FROM_RULES } from '../config';

  const emit = defineEmits<{
    (e: 'refreshList'): void;
  }>();

  const basicDialogRef = ref<InstanceType<typeof BasicDialog>>();
  const basicFormRef = ref<InstanceType<typeof BasicForm>>();
  const { ruleFormConfig, ruleFormData, formRules } = useFormConfigHook<DiscardSuppliesForm>(
    SUPPLIES_DISCARD_FROM_CONFIG,
    SUPPLIES_DISCARD_FROM_DATA,
    SUPPLIES_DISCARD_FROM_RULES,
  );

  const supply = ref<EmergencySupplyListResponse>();

  const openDialog = (item: EmergencySupplyListResponse) => {
    supply.value = item;
    basicDialogRef.value?.openDialog();
    (formRules.quantity as Array<any>).push({
      validator: (_rule, value, callback) => {
        if (!supply.value) {
          ElMessage.error('物资报废失败，请重新选择报废物资');
          return callback(new Error('请重新选择报废物资'));
        }
        if (value == null) return callback(new Error('请输入报废数量'));
        if (!Number.isInteger(value)) return callback(new Error('请输入正整数'));
        if (value > supply.value?.currentQuantity) {
          callback(new Error('报废数量不能超过物资当前数量'));
        } else if (value <= 0) {
          callback(new Error('数量不能小于1'));
        } else {
          callback();
        }
      },
      trigger: 'blur',
    });
  };
  const handleSumbit = async () => {
    const validate = await basicFormRef.value?.validateForm();
    if (!validate) return;
    if (!supply.value) return;
    try {
      await discardEmergencySupply(supply.value.id, ruleFormData.quantity!);
      ElMessage.success('物资报废成功');
      emit('refreshList');
      basicDialogRef.value?.closeDialog();
    } catch (error) {
      ElMessage.error('物资报废失败');
    }
  };
  const refreshFromData = () => {
    basicFormRef.value?.clearValidate();
  };
  defineExpose({
    openDialog,
  });
</script>

<style scoped lang="scss">
  .discard-note {
    padding-left: 80px;
  }
</style>
