<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="450">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="120px"
    >
      <el-form-item label="锁定站名称" prop="lotoName">
        <el-input
          v-model="formData.lotoName"
          placeholder="请输入锁定站名称"
        />
      </el-form-item>
      <el-form-item label="排序" prop="orderNum">
        <el-input-number v-model="formData.orderNum" />
      </el-form-item>
      <el-form-item label="岗位" prop="workstationId">
        <el-tree-select
          v-model="formData.workstationId"
          :data="marsOptions"
          :props="{ label: 'workstationName', value: 'id', children: 'children' }"
          placeholder="选择岗位"
        />
      </el-form-item>
      <el-form-item label="所属硬件" prop="lotoSerialNumber">
        <el-select
          v-model="formData.lotoSerialNumber"
          placeholder="请选择所属硬件"
          clearable
        >
          <el-option
            v-for="dict in hardWareList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="地图名称" prop="mapId">
        <el-select
          v-model="formData.mapId"
          placeholder="地图名称"
        >
          <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="map">
        <el-input
          v-model="formData.map"
          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 } from '@/utils/dict'
import * as LotoStationApi from '@/api/dv/lotoStation/index'
// import { genCode } from '@/api/system/autocode/rule'
import * as MapconfigApi from '@/api/basic/mapconfig/index'
import * as  HardwareApi from '@/api/hw/hardware/information/index'
import * as  MarsDeptApi from '@/api/system/marsdept'
import {  handleTree } from '@/utils/tree'

defineOptions({ name: 'LotoStationForm' })

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

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const autoGenFlag = ref(false) // 是否自动生成编码

const formData = ref({
  lotoId: undefined,
  lotoName: '',
  orderNum: 0,
  workstationId: undefined,
  lotoSerialNumber: undefined,
  mapId: undefined,
  map: ''
})

const formRules = reactive({
  lotoName: [{ required: true, message: '锁定站名称不能为空', trigger: 'blur' }],
  workstationId: [{ required: true, message: '岗位不能为空', trigger: 'blur' }],
  mapId:[{required:true,message:'地图名称不能为空',trigger:'blur'}],
})

const formRef = ref() // 表单 Ref
const marsOptions = ref([]) // 岗位树选项
const mapOptions = ref([]) // 地图选项
const hardWareList = ref([]) // 硬件列表

/** 打开弹窗 */
const open = async (type: string, id?: number,mapId?:number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await LotoStationApi.selectIsLotoStationById(id)
    } finally {
      formLoading.value = false
    }
  }
  // 获取岗位数据
  const deptRes = await MarsDeptApi.listMarsDept({ pageNo: 1, pageSize: -1 })
  marsOptions.value = handleTree(deptRes.list)

  // 获取地图数据 (getNotUsedMap这个接口可以筛选已经被使用的就不再出现 未被使用的才出现)
  const mapRes = await MapconfigApi.getNotUsedMap(mapId)
  mapOptions.value = mapRes

  // 获取硬件数据
  const hwRes = await HardwareApi.listHardware({ pageNo: 1, pageSize: -1 })
  hardWareList.value = hwRes.list.map(item => ({
    value: item.serialNumber,
    label: item.hardwareName
  }))
}
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 LotoStationApi.addLoto(data)
      message.success(t('common.createSuccess'))
    } else {
      await LotoStationApi.updateLoto(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    lotoId: undefined,
    lotoName: '',
    orderNum: 0,
    workstationId: undefined,
    lotoSerialNumber: undefined,
    mapId: undefined,
    map: ''
  }
  autoGenFlag.value = false
  formRef.value?.resetFields()
}

/** 自动生成编码 */
// const handleAutoGenChange = async (value: boolean) => {
//   if (value) {
//     formData.value.lotoCode = await genCode('LOTO_STATION_CODE')
//   } else {
//     formData.value.lotoCode = ''
//   }
// }
</script>
