<template>
  <el-drawer v-model="open" :title="`申购清单`" :before-close="handleClose" direction="rtl" class="demo-drawer"
    modal-class="el-subscribe-drawer" size="80%">

    <el-form ref="applyPurchaseRef" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="申购说明" prop="applyPurchaseExplain">
        <el-input maxlength="300" v-model="form.applyPurchaseExplain" type="textarea" placeholder="请输入申购说明" autofocus/>
      </el-form-item>
      <el-divider content-position="center">物料管理-物料申购详情信息</el-divider>

    </el-form>

    <Index :editable="false" :list="[...Object.values($store.state.data.applyPurchaseDetails),...$store.state.data.applyPurchaseDetailsCustomList]" />
    <template #footer>
      <el-button plain @click="handleClose">取 消</el-button>
      <el-button :disabled="loading" type="primary" @click="submitForm">提 交</el-button>
    </template>
  </el-drawer>
</template>

<script setup>
import { clearApplyPurchaseDetails } from "@/utils/applyPurchaseDetails";
import { listApplyPurchase, getApplyPurchase, delApplyPurchase, addApplyPurchaseDetails, updateApplyPurchaseDetails } from "@/api/applyPurchase/applyPurchase";
import Index from "@/components/ApplyPurchaseDetails/index";
const { proxy, ctx } = getCurrentInstance();
const open = ref(false);
const loading = ref(true);
const store = useStore();
const emit = defineEmits();

const data = reactive({
  form: {},

  rules: {
    applyPurchaseExplain: [
      {
        required: true,
        message: "申购说明不能为空",
        trigger: "blur",
      },
    ],
  }
})

const { form, rules } = toRefs(data);

const applyPurchaseNumTotal = computed(() => {
  let total = 0;
  Object.values(store.state.data.applyPurchaseDetails).map((item) => {
    total += item.applyPurchaseNum;
  });
  return total;
});





// 显示弹框
function show() {
  open.value = true;
  loading.value = false;
}

// 关闭按钮
function handleClose() {
  form.value = {}
  open.value = false;
  emit("close")
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["applyPurchaseRef"].validate(valid => {
    if (valid) {
      form.value.applyPurchaseDetailsList = [...Object.values(store.state.data.applyPurchaseDetails),...store.state.data.applyPurchaseDetailsCustomList];
      if (form.value.applyPurchaseId != null) {
        updateApplyPurchaseDetails(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          handleClose()
        });
      } else {
        addApplyPurchaseDetails(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          handleClose()
          clearApplyPurchaseDetails(false)
        });
      }
    }
  });
}



defineExpose({
  show,
handleClose,
});
</script>