<template>
  <AFormPanel
    ref="formPanel"
    :details-loader="detailsLoader"
    :do-submit="doSubmit"
    :rules="rules"
    :title="status === 'add' ? '新建项目' : '修改项目'"
  >
    <template #default="{formData}">
      <div class="form-items">
        <ElFormItem label="仓库名称" prop="warehouseName">
          <ElInput
            v-model="formData.warehouseName"

            placeholder="仓库名称"/>
        </ElFormItem>
        <ElFormItem label="位置" prop="location">
          <ElInput
            v-model="formData.location"

            placeholder="位置"/>
        </ElFormItem>

      </div>
    </template>
  </AFormPanel>
</template>

<script lang="ts" setup>
import WarehouseApi from '@/pages/wh/warehouse/warehouse-api.ts'
import Strings from '@/common/utils/strings.ts'
import { type FormRules } from 'element-plus'
import type { ComponentExposed } from 'vue-component-type-helpers'
import AFormPanel from '@/components/a-form-panel/AFormPanel.tsx'

const props = withDefaults(defineProps<{
  research?: () => void
}>(), {
  research: () => {
  },
})
const rules = reactive<FormRules<WarehouseTypes.SearchWarehouseResult>>({
  id: [ {required: true, message: '请填写Id', trigger: 'blur'} ],
  warehouseName: [ {required: true, message: '请填写仓库名称', trigger: 'blur'} ],
  location: [ {required: true, message: '请填写位置', trigger: 'blur'} ],
  creatorId: [ {required: true, message: '请填写创建人 Id； sys_user.id', trigger: 'blur'} ],
  modifierId: [ {required: true, message: '请填写修改人 Id；sys_user.id', trigger: 'blur'} ],
  createTime: [ {required: true, message: '请填写创建时间', trigger: 'blur'} ],
  modifyTime: [ {required: true, message: '请填写修改时间', trigger: 'blur'} ],
  deleted: [ {required: true, message: '请填写是否删除； 0-->未删除、1-->已删除', trigger: 'blur'} ],
})

const formPanelIns = useTemplateRef<ComponentExposed<typeof AFormPanel>>('formPanel')
const status = ref<'add' | 'modify'>('add')

function detailsLoader(id?: string) {
  if (Strings.isBlank(id)) {
    status.value = 'add'
    return Promise.resolve()
  } else {
    status.value = 'modify'
    return WarehouseApi
      .detail(id!)
      .then(res => res.data)
  }
}

function doSubmit(data: WarehouseTypes.SearchWarehouseResult) {
  if (status.value === 'add') {
    return WarehouseApi.add(data)
      .then(props.research)
  } else {
    return WarehouseApi.modify(data)
      .then(props.research)
  }
}

defineExpose({
  open(data?: WarehouseTypes.SearchWarehouseResult) {
    formPanelIns.value?.open(data?.id)
  },
})
</script>

<style lang="stylus" scoped>
.form-items {
  grid-template-columns: 1fr 1fr;

  :deep(.el-form-item) {
  }
}
</style>
