<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="800">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="120px"
    >
      <el-row>
<!--        <el-col :span="8">-->
<!--          <el-form-item label="硬件编码" prop="hardwareCode">-->
<!--            <el-input-->
<!--              v-model="formData.hardwareCode"-->
<!--              placeholder="请输入硬件编码"-->
<!--              style="width: 100%"-->
<!--            />-->
<!--          </el-form-item>-->
<!--        </el-col>-->
<!--        <el-col :span="3">-->
<!--          <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="hardwareName">
            <el-input
              v-model="formData.hardwareName"
              placeholder="请输入硬件名称"
            />
          </el-form-item>
        </el-col>

        <el-col :span="11">
          <el-form-item label="硬件类型" prop="hardwareTypeId">
            <el-tree-select
              v-model="formData.hardwareTypeId"
              :data="hardwareTypeOption"
              :props="{ value: 'id', label: 'hardwareTypeName', children: 'children' }"
              @change="onSelectChange"
              placeholder="请选择硬件类型"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>

        <el-col :span="11">
          <el-form-item label="规格型号" prop="hardwareSpec">
            <el-input
              v-model="formData.hardwareSpec"
              placeholder="请输入规格型号"
            />
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="序列号" prop="serialNumber">
            <el-input
              v-model="formData.serialNumber"
              placeholder="请输入序列号"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="11">
          <el-form-item label="可用次数" prop="availableTimes">
            <el-input
              v-model="formData.availableTimes"
              placeholder="请输入可用次数"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="已用次数" prop="usedTimes">
            <el-input
              v-model="formData.usedTimes"
              placeholder="请输入已用次数"
              disabled
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="11">
          <el-form-item label="可用寿命" prop="availableLife">
            <el-input
              v-model="formData.availableLife"
              placeholder="请输入可用寿命"
            />
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="已用寿命" prop="usedLife">
            <el-input
              v-model="formData.usedLife"
              placeholder="请输入已用寿命"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="11">
          <el-form-item label="启用日期" prop="activationTime">
            <el-date-picker
              v-model="formData.activationTime"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="请选择启用日期"
            />

          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio label="1">
            <img src="@/assets/images/success.png" alt="" class="imgstatus" />
            在线
          </el-radio>
          <el-radio label="2">
            <img src="@/assets/images/error.png" alt="" class="imgstatus" />
            离线
          </el-radio>
          <el-radio label="3">
            <img src="@/assets/images/warn.png" alt="" class="imgstatus" />
            异常
          </el-radio>
        </el-radio-group>
      </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 { ref, reactive } from 'vue'
import { handleTree } from '@/utils/tree'
import * as HardwareApi from '@/api/hw/hardware/information/index'
import * as HardwareTypeApi from '@/api/hw/type/hardwaretype/index'

// import * as AutocodeApi from '@/api/system/autocode/rule'

defineOptions({ name: 'HardwareForm' })

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({
  hardwareId: undefined,
  hardwareCode: '',
  hardwareName: '',
  hardwareTypeId: undefined,
  hardwareTypeName: '',
  hardwareSpec: '',
  serialNumber: '',
  availableTimes: 0,
  usedTimes: 0,
  availableLife: '',
  usedLife: '',
  activationTime: '',
  status: '1'
})

const formRules = reactive({
  // hardwareCode: [{ required: true, message: '硬件编码不能为空', trigger: 'blur' }],
  hardwareName: [{ required: true, message: '硬件名称不能为空', trigger: 'blur' }],
  hardwareTypeId: [{ required: true, message: '硬件类型不能为空', trigger: 'change' }]
})

const formRef = ref() // 表单 Ref
const hardwareTypeOption = ref([]) // 硬件类型选项


const formatDateFromArray=(arr)=> {
  const [y,m,d] = arr;
  const mm = m.toString().padStart(2,'0');
  const dd = d.toString().padStart(2,'0');
  return `${y}-${mm}-${dd}`
}
/** 打开弹窗 */
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 HardwareApi.getHardwareInfo(id)
      formData.value.activationTime=formatDateFromArray(formData.value.activationTime)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

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

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    hardwareId: undefined,
    hardwareCode: '',
    hardwareName: '',
    hardwareTypeId: undefined,
    hardwareTypeName: '',
    hardwareSpec: '',
    serialNumber: '',
    availableTimes: 0,
    usedTimes: 0,
    availableLife: '',
    usedLife: '',
    activationTime: '',
    status: '1'
  }
  autoGenFlag.value = false
  formRef.value?.resetFields()
}

// 递归查找函数
const findOptionById = (options: any[], targetId: number): any => {
  for (const option of options) {
    // 检查当前节点
    if (option.id === targetId) {
      return option
    }

    // 如果有子节点，递归查找
    if (option.children && option.children.length > 0) {
      const found = findOptionById(option.children, targetId)
      if (found) {
        return found
      }
    }
  }
  return null
}
// 下拉改变函数
const onSelectChange = (selectedId: number) => {
  formData.value.hardwareTypeId = selectedId

  // 使用递归查找
  const selectedOption = findOptionById(hardwareTypeOption.value, selectedId)

  if (selectedOption) {
    formData.value.hardwareTypeName = selectedOption.hardwareTypeName
    console.log('找到匹配项:', selectedOption.hardwareTypeName)
  } else {
    console.warn('未找到匹配的选项，selectedId:', selectedId)
  }
}

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

/** 获取硬件类型树形数据 */
const getHardwareTypeTree = async () => {
  const data = { pageNo: 1, pageSize: -1 }
  const response = await HardwareTypeApi.listHardwareType(data)
  console.log(response,'数据拿到了没')
  hardwareTypeOption.value = handleTree(response.list,'id', 'parentTypeId')

}

/** 初始化 **/
onMounted(async () => {
  await getHardwareTypeTree()
})
</script>

<style scoped>
.imgstatus {
  position: relative;
  top: 1px;
  left: 0px;
}
:deep(.el-radio__inner) {
  border-radius: 2px;
}
:deep(.el-radio__input.is-checked .el-radio__inner::after) {
  content: "";
  width: 8px;
  height: 3px;
  border: 1px solid white;
  border-top: transparent;
  border-right: transparent;
  text-align: center;
  display: block;
  position: absolute;
  top: 3px;
  left: 2px;
  transform: rotate(-45deg);
  border-radius: 0pc;
  background: none;
}
</style>
