<script setup lang="ts">
import { ref } from "vue";
import Modal from "./components/modal.vue";
import contentConfig from "./config/content.config";
import searchConfig from "./config/search.config";
import { usePageSearch, type PageHooks, type PageEvents } from "/@/hooks/page";
import { httpAdd, httpUpdate } from "/@/api/serviceParam/unusualReason";

import { ElMessage } from "element-plus"

const PageName = "unusualReason";
const instance = ref<any>(null);

const disabled = ref(false)
const visible = ref(false)
const data = ref<any>({})

const hooks: PageHooks = {
  pageSearchHook: () => usePageSearch(undefined, undefined, searchConfig)
};

const events: PageEvents = {
  content: {
    create: () => {
      disabled.value = false
      visible.value = true
    },
    preview: _data => {
      const { id, type, result, result_desc } = _data
      data.value = { id, type, result, result_desc }
      disabled.value = true
      visible.value = true
    },
    update: _data => {
      const { id, type, result, result_desc } = _data
      data.value = { id, type, result, result_desc }
      disabled.value = false
      visible.value = true
    }
  }
};

async function onSubmit() {
  const { id, type, result, result_desc } = data.value;
  const isCreate = id === undefined || !id
  const params = { id, type, result, result_desc }
  if (isCreate) delete params['id']
  const api = isCreate ? httpAdd : httpUpdate
  const res = await api(params)
  if (res.code === 0) {
    visible.value = false
    ElMessage.success(`${isCreate ? '添加' : '更新'}成功`)
    instance.value!.onSearch()
  } else {
    ElMessage.warning(`${isCreate ? '添加' : '更新'}失败`)
  }
}
</script>

<template>
  <PageAuth :pageName="PageName">
    <PageContainer :hooks="hooks" :events="events" :contentConfig="contentConfig" :search-config="searchConfig"
      :get-content-ref="ref => (instance = ref)" />
    <Modal v-model:visible="visible" v-model:data="data" :disabled="disabled" @submit="onSubmit" />
  </PageAuth>
</template>
