<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="800">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="80px"
    >
      <el-form-item label="地图名称" prop="mapId">
        <el-select v-model="formData.mapId" placeholder="地图名称" class="!w-280px">
          <el-option
            v-for="item in mapOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="地图类型" prop="mapType">
        <el-select v-model="formData.mapType" placeholder="地图类型" class="!w-280px">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.MAP_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="formData.mapType === '1'" label="实体" prop="entityId">
        <el-tree-select
          v-model="formData.entityId"
          :data="deptOptions"
          :props="{
        value: 'id',
        label: 'workstationName',
        children: 'children'
      }"
          placeholder="请选择实体"
          class="!w-280px"
          :check-strictly="true"
          node-key="id"
          default-expand-all
          clearable
          filterable
        />
      </el-form-item>
      <el-form-item v-if="formData.mapType === '2'" label="实体" prop="entityId">
        <el-select v-model="formData.entityId" placeholder="实体" class="!w-280px">
          <el-option
            v-for="item in spmOptions"
            :key="item.id"
            :label="item.pointName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="横坐标" prop="x">
        <el-input v-model="formData.x" placeholder="请输入横坐标" />
      </el-form-item>
      <el-form-item label="纵坐标" prop="y">
        <el-input v-model="formData.y" placeholder="请输入纵坐标" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import * as MapPointApi from '@/api/basic/mappoint'
import {insertIsMapPoint, selectIsMapPointById, updateIsMapPoint} from "@/api/basic/mappoint";

defineOptions({ name: 'SystemMapPointForm' })

interface DeptOption {
  workstationId: number
  workstationName: string
  children?: DeptOption[]
}

interface Props {
  mapOptions: Array<{ id: number; name: string }>
  deptOptions: DeptOption[]
  spmOptions: Array<{ pointId: number; pointName: string }>
}

const props = defineProps<Props>()

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined as number | undefined,
  mapId: undefined as number | undefined,
  mapType: undefined as string | undefined,
  entityId: undefined as number | undefined,
  x: undefined as number | undefined,
  y: undefined as number | undefined
})
const formRules = reactive({
  mapId: [{ required: true, message: '地图名称不能为空', trigger: 'blur' }],
  mapType: [{ required: true, message: '地图类型不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await MapPointApi.selectIsMapPointById(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value
    if (formType.value === 'create') {
      await MapPointApi.insertIsMapPoint(data)
      message.success(t('common.createSuccess'))
    } else {
      await MapPointApi.updateIsMapPoint(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    mapId: undefined,
    mapType: undefined,
    entityId: undefined,
    x: undefined,
    y: undefined
  }
  formRef.value?.resetFields()
}

/** 处理岗位变更 */
const handleWorkstationChange = (value: number) => {
  formData.value.entityId = value
}
</script>
