<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="960">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="110px"
    >
      <el-row>
<!--        <el-col :span="7">-->
<!--          <el-form-item label="隔离点编号" prop="pointCode">-->
<!--            <el-input-->
<!--              v-model="formData.pointCode"-->
<!--              placeholder="请输入隔离点编号"-->
<!--            />-->
<!--          </el-form-item>-->
<!--        </el-col>-->
<!--        <el-col :span="4">-->
<!--          <el-form-item label-width="80">-->
<!--            <el-switch-->
<!--              v-model="autoGenFlag"-->
<!--              active-color="#13ce66"-->
<!--              active-text="自动生成"-->
<!--              @change="handleAutoGenChange"-->
<!--              v-if="formType !== 'view'"-->
<!--            />-->
<!--          </el-form-item>-->
<!--        </el-col>-->
        <el-col :span="11">
          <el-form-item label="隔离点名称" prop="pointName">
            <el-input
              v-model="formData.pointName"
              placeholder="请输入隔离点名称"
            />
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="隔离点NFC" prop="rfidId">
            <el-select v-model="formData.rfidId" >
              <el-option
                v-for="dict in rfidTokenData"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

      </el-row>
      <el-row>
        <el-col :span="11">
          <el-form-item label="锁定站" prop="lotoId">
            <el-select
              v-model="formData.lotoId"
              placeholder="请选择锁定站"
            >
              <el-option
                v-for="dict in lotoOptions"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="岗位" prop="workstationId">
            <el-tree-select
              v-model="formData.workstationId"
              :data="deptOptions"
              :props="{ label: 'workstationName', value: 'id', children: 'children' }"
              placeholder="选择岗位"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="11">
          <el-form-item label="能量源" prop="powerType">
            <el-select
              v-model="formData.powerType"
              placeholder="请选择能量源"
            >
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.POWER_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="隔离点序列号" prop="pointSerialNumber">
            <el-input
              v-model="formData.pointSerialNumber"
              placeholder="请输入隔离点序列号"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>

        <el-col :span="11">
          <el-form-item label="作用" prop="remark">
            <el-input
              v-model="formData.remark"
              placeholder="请输入作用"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="隔离点图标" prop="pointIcon">
            <div class="image-grid">
              <div
                v-for="(imageUrl, index) in imageMap"
                :key="index"
                class="image-item"
                :class="{ 'selected': selectedImageIndex === index }"
                @click="selectIcon(imageUrl, index)"
              >
                <img :src="imageUrl" alt="Isolation Icon" style="width: 50px; height: 50px;" />
              </div>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="隔离点图片" prop="pointPicture">
            <UploadImg
              v-model="formData.pointPicture"
              :limit="1"
              :is-show-tip="false"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </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 SegregationPointApi from '@/api/dv/spm/index'
// import { genCode } from '@/api/system/autocode/rule'
import { getIsSystemAttributeByKey } from '@/api/basic/configuration/index'
import * as RfidApi from '@/api/hw/hardware/rfid/index'
import * as MarsDeptApi from '@/api/system/marsdept/index'
import * as LotoApi from '@/api/dv/lotoStation/index'
import {  handleTree } from '@/utils/tree'


defineOptions({ name: 'SegregationPointForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const machineryOptions = ref([]) // 设备工艺树选项
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const autoGenFlag = ref(false) // 是否自动生成编码
const selectedImageIndex = ref(-1) // 选中的图片索引

const formData = ref({
  pointId: undefined,
  pointCode: '',
  pointName: '',
  pointIcon: '',
  pointPicture: '',
  pointNfc: '',
  workstationId: undefined,
  lotoId: undefined,
  powerType: undefined,
  pointSerialNumber: '',
  remark: '',

})

const formRules = reactive({
  // pointCode: [{ required: true, message: '隔离点编号不能为空', trigger: 'blur' }],
  pointName: [{ required: true, message: '隔离点名称不能为空', trigger: 'blur' }],
  workstationId: [{ required: true, message: '岗位不能为空', trigger: 'blur' }],
  lotoId: [{ required: true, message: '锁定站不能为空', trigger: 'blur' }],
  pointNfc: [{ required: true, message: '隔离点NFC不能为空', trigger: 'blur' }]
})

const formRef = ref() // 表单 Ref
const deptOptions = ref([]) // 部门树选项
const lotoOptions = ref([]) // 锁定站选项
const rfidTokenData = ref([]) // RFID Token数据
const imageMap = 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 SegregationPointApi.selectIsIsolationPointById(id)
      // 获取隔离点图标
      const sysAttrKey1 = 'sys.icon_set.isolation'
      const iconRes = await getIsSystemAttributeByKey(sysAttrKey1)
      console.log(iconRes,'aaaaa')
      const values = iconRes.sysAttrValue.split(',').map(value => value.trim())
      const iconPromises = values.map(value => getIsSystemAttributeByKey(value))
      const iconResponses = await Promise.all(iconPromises)
      iconResponses.forEach((response, index) => {
        imageMap.value[index] = response.sysAttrValue
      })
      // 确定选中的图片索引
      selectedImageIndex.value = getImageIndexByIcon(formData.value.pointIcon)
      console.log(selectedImageIndex.value,'aaa')
    } finally {
      formLoading.value = false
    }
  }
  // 获取岗位数据
  const deptRes = await MarsDeptApi.listMarsDept({ pageNo: 1, pageSize: -1 })

  deptOptions.value = handleTree(deptRes.list, 'id', 'parentId')

  // 获取锁定站数据
  const lotoRes = await LotoApi.listLoto({ pageNo: 1, pageSize: -1 })
  lotoOptions.value = lotoRes.list.map(item => ({
    value: item.id,
    label: item.lotoName
  }))

  // 获取RFID Token数据
  const rfidRes = await RfidApi.getIsRfidTokenPage({ pageNo: 1, pageSize: -1 })
  rfidTokenData.value = rfidRes.list.map(record => ({
    value: record.id,
    label: record.rfid
  }))




}
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 SegregationPointApi.addinsertIsIsolationPoint(data)
      message.success(t('common.createSuccess'))
    } else {
      await SegregationPointApi.updateIsIsolationPoint(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    pointId: undefined,
    pointCode: '',
    pointName: '',
    pointIcon: '',
    pointPicture: '',
    pointNfc: '',
    workstationId: undefined,
    lotoId: undefined,
    powerType: undefined,
    pointSerialNumber: '',
    remark: ''
  }
  autoGenFlag.value = false
  selectedImageIndex.value = -1
  formRef.value?.resetFields()
}

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


/** 选择隔离点图标 */
const selectIcon = (imageUrl: string, index: number) => {
  formData.value.pointIcon = imageUrl
  selectedImageIndex.value = index
}

/** 获取图片索引 */
const getImageIndexByIcon = (iconUrl: string) => {
  for (const [index, imageUrl] of Object.entries(imageMap.value)) {
    if (imageUrl === iconUrl) {
      return index
    }
  }
  return -1
}
</script>

<style lang="scss" scoped>
.image-grid {
  display: flex;
  flex-wrap: wrap;
}

.image-item {
  margin: 5px;
  height: 55px;
  cursor: pointer;
  border: 2px solid transparent;
  transition: border-color 0.3s;
  position: relative;

  &.selected {
    border-color: rgb(2, 86, 255);
    border-width: 2px;
  }
}
</style>
