<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    width="500px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    destroy-on-close
    draggable
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      @submit.prevent
    >
      <el-form-item label="细胞编号" prop="cellNo">
        <el-input v-model="form.cellNo" placeholder="请输入细胞编号" />
      </el-form-item>
      <el-form-item label="细胞名称" prop="cellName">
        <el-input v-model="form.cellName" placeholder="请输入细胞名称" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-switch v-model="form.status" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="onSubmit">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, watch } from 'vue'
import { CellDto } from '/@/api/admin/data-contracts'
import { ItemDefCellApi } from '/@/api/admin/item-def-cell'
import eventBus from '/@/utils/mitt'

const props = defineProps({
  title: {
    type: String,
    default: ''
  }
})

const dialogVisible = ref(false)
const formRef = ref()

const form = reactive<Partial<CellDto>>({
  cellNo: '',
  cellName: '',
  status: true
})

const rules = {
  cellNo: [{ required: true, message: '请输入细胞编号', trigger: 'blur' }],
  cellName: [{ required: true, message: '请输入细胞名称', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

const open = (row: Partial<CellDto>) => {
  dialogVisible.value = true
  Object.assign(form, row)
}

const onSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      const submitData = {
        ...form,
        id: form.id || 0
      }
      if (submitData.id) {
        await new ItemDefCellApi().update(submitData as CellDto, { loading: true })
      } else {
        await new ItemDefCellApi().add(submitData as CellDto, { loading: true })
      }
      dialogVisible.value = false
      eventBus.emit('refreshCell')
    }
  })
}

defineExpose({
  open
})
</script>

<style scoped lang="scss">
:deep(.el-form-item__label) {
  text-align: right;
  padding-right: 12px;
}
</style>
