<template>
  <el-dialog draggable append-to-body title="编辑BIN" v-model="show" width="440px" align-center>
    <el-form :model="formData" ref="form" hide-required-asterisk label-position="top">
      <el-form-item
        label="BIN名称"
        prop="name"
        :rules="[{ required: true, message: '名称不能为空', trigger: 'blur' }]"
      >
        <el-input spellcheck="false" v-model="formData.name"></el-input>
      </el-form-item>
      <el-form-item label="BIN路径">
        <el-input spellcheck="false" v-model="formData.path"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="show = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import type { Bin } from '@/types/bins'

import { ref } from 'vue'
import { useProjectStore } from '@/store/modules/project'

const show = ref(false)
const form = ref<FormInstance>()
const formData = ref<Bin>({
  id: '',
  name: '',
  path: ''
})
const { project } = useProjectStore()
defineExpose({
  edit: (binId: string) => {
    show.value = true
    const bin = project?.bins.find((bin) => bin.id === binId)
    if (bin) {
      formData.value.id = bin.id
      formData.value.name = bin.name
      formData.value.path = bin.path
    }
  }
})

const handleSubmit = () => {
  form.value?.validate((valid) => {
    if (valid) {
      project?.bins.find((bin) => {
        if (bin.id === formData.value.id) {
          bin.name = formData.value.name
          bin.path = formData.value.path
        }
      })
      show.value = false
    }
  })
}
</script>

<style scoped></style>
