<template>
  <div class="testequ-form">
    <el-dialog
      v-model="state.isShowDialog"
      destroy-on-close
      :title="props.title"
      draggable
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="900px"
    >
      <el-form :model="form" ref="formRef" size="default" label-width="120px">

        <!-- 基本信息 -->
        <div class="form-section">
          <div class="section-title">基本信息</div>

          <el-row :gutter="25">
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="设备类型" prop="equipmentType" :rules="[{ required: true, message: '请选择设备类型', trigger: ['change'] }]">
                <el-select v-model="form.equipmentType" placeholder="请选择设备类型" style="width: 100%">
                  <el-option
                    v-for="type in state.equipmentTypeOptions"
                    :key="type.value"
                    :label="type.label"
                    :value="type.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="设备编号" prop="equipmentNo" :rules="[{ required: true, message: '请输入设备编号', trigger: ['blur', 'change'] }]">
                <el-input v-model="form.equipmentNo" clearable placeholder="请输入设备编号" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="25">
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="资产编号" prop="assetNo" :rules="[{ required: true, message: '请输入资产编号', trigger: ['blur', 'change'] }]">
                <el-input v-model="form.assetNo" clearable placeholder="请输入资产编号" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="设备型号" prop="equipmenModel" :rules="[{ required: true, message: '请选择设备型号', trigger: ['change'] }]">
                <el-select
                  v-model="form.equipmenModel"
                  placeholder="请选择设备型号"
                  filterable
                  clearable
                  :loading="state.dictLoading"
                  style="width: 100%"
                >
                  <el-option
                    v-for="model in state.equipmentModelOptions"
                    :key="model.id"
                    :label="model.name"
                    :value="model.code"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="25">
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="负责人" prop="principalId" :rules="[{ required: true, message: '请选择负责人', trigger: ['change'] }]">
                <el-select
                  v-model="form.principalId"
                  placeholder="请选择设备负责人"
                  clearable
                  filterable
                  style="width: 100%"
                >
                  <el-option
                    v-for="user in state.userOptions"
                    :key="user.id"
                    :label="`${user.name} (${user.userName})`"
                    :value="user.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-form-item label="描述" prop="description">
                <el-input
                  v-model="form.description"
                  clearable
                  type="textarea"
                  :rows="3"
                  placeholder="请输入设备描述"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 配置信息 -->
        <div class="form-section">
          <div class="section-title">配置信息</div>

          <el-row :gutter="25">
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="序列号" prop="serialNumber" :rules="[{ required: true, message: '请输入序列号', trigger: ['blur', 'change'] }]">
                <el-input v-model="form.serialNumber" clearable placeholder="请输入序列号" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="私钥" prop="privateKey" :rules="[{ required: true, message: '请输入私钥', trigger: ['blur', 'change'] }]">
                <el-input v-model="form.privateKey" type="password" placeholder="请输入私钥" show-password />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onCancel" size="default">取 消</el-button>
          <el-button type="primary" @click="onSubmit" size="default" :loading="state.loading">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="TestequForm">
import { reactive, ref, getCurrentInstance, onMounted, toRefs } from 'vue'
import { TestequApi } from '/@/api/admin/TestequApi'
import { UserApi } from '/@/api/admin/User'
import { DictApi } from '/@/api/admin/Dict'
import { UserGetPageOutput, PageInputUserGetPageInput, TestequAddInput, TestequUpdateInput, DictGetListOutput } from '/@/api/admin/data-contracts'
import eventBus from '/@/utils/mitt'

// 定义父组件传过来的值
const props = defineProps({
  title: String,
})

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh'])

// 定义变量内容
const formRef = ref()
const { proxy } = getCurrentInstance() as any

// 临时类型定义
type TestequFormData = {
  id?: number
  equipmentType: number | undefined
  equipmentNo: string
  serialNumber: string
  privateKey: string
  assetNo: string
  equipmenModel: string
  principalId: number | undefined
  description: string
}

const state = reactive({
  isShowDialog: false,
  loading: false,
  dictLoading: false,
  form: {
    id: undefined,
    equipmentType: undefined,
    equipmentNo: '',
    serialNumber: '',
    privateKey: '',
    assetNo: '',
    equipmenModel: '',
    principalId: undefined,
    description: '',
  } as TestequFormData,
  userOptions: [] as Array<UserGetPageOutput>,
  equipmentModelOptions: [] as Array<DictGetListOutput>,
  equipmentTypeOptions: [
    { label: 'BGA', value: 1 },
    { label: 'Vicell', value: 3 },
    { label: 'OSMO', value: 5 },
    { label: 'Cedex', value: 7 }
  ],
})

const { form } = toRefs(state)

onMounted(() => {
  getUserOptions()
  getEquipmentModelOptions()
})

// 打开弹窗
const openDialog = async (row?: any) => {
  resetForm()

    // 确保字典数据已加载
  if (state.equipmentModelOptions.length === 0) {
    state.dictLoading = true
    await getEquipmentModelOptions()
    state.dictLoading = false
  }

  // 确保用户数据已加载
  if (state.userOptions.length === 0) {
    await getUserOptions()
  }

  if (row && row.id) {
    // 编辑模式，获取详情
    try {
      const res = await new TestequApi().get({ id: row.id })
      if (res?.success && res.data) {
        state.form = {
          id: res.data.id,
          equipmentType: res.data.equipmentType,
          equipmentNo: res.data.equipmentNo || '',
          serialNumber: res.data.serialNumber || '',
          privateKey: res.data.privateKey || '',
          assetNo: res.data.assetNo || '',
          equipmenModel: res.data.equipmenModel || '',
          principalId: res.data.principalId,
          description: res.data.description || '',
        }
      }
    } catch (error: any) {
      // 静默处理错误
      if (error.response?.status === 500) {
        proxy.$modal.msgError('服务器内部错误，请检查后台服务')
      } else {
        proxy.$modal.msgError(`获取详情失败: ${error.response?.data?.msg || error.message}`)
      }
      return
    }
  }

  state.isShowDialog = true
}

// 关闭弹窗
const closeDialog = () => {
  state.isShowDialog = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  state.form = {
    id: undefined,
    equipmentType: undefined,
    equipmentNo: '',
    serialNumber: '',
    privateKey: '',
    assetNo: '',
    equipmenModel: '',
    principalId: undefined,
    description: '',
  }
}

// 获取用户选项
const getUserOptions = async () => {
  try {
    const userPageInput = {
      currentPage: 1,
      pageSize: 1000, // 获取足够多的数据
      filter: {
        orgId: null,
      }
    } as PageInputUserGetPageInput

    const res = await new UserApi().getPage(userPageInput)
    if (res?.success) {
      state.userOptions = res.data?.list ?? []
    }
  } catch (error) {
    // 静默处理错误
  }
}

// 获取设备型号字典选项
const getEquipmentModelOptions = async () => {
  try {
    const res = await new DictApi().getList(['TESTINGEQU'])

    if (res?.success && res.data) {
      // 注意：API返回的key是小写的 testingequ
      state.equipmentModelOptions = res.data['testingequ'] || []
    }
  } catch (error) {
    // 静默处理错误
  }
}

// 取消
const onCancel = () => {
  closeDialog()
}

// 提交
const onSubmit = () => {
  formRef.value.validate(async (valid: boolean) => {
    if (!valid) return false

    state.loading = true
    try {
      let res = {} as any
      if (state.form.id) {
        res = await new TestequApi().update(state.form as TestequUpdateInput, { showSuccessMessage: true })
      } else {
        res = await new TestequApi().add(state.form as TestequAddInput, { showSuccessMessage: true })
      }

      if (res?.success) {
        closeDialog()
        emit('refresh')
        eventBus.emit('refreshTestequ' as keyof MittType<any>)
      }
    } catch (error: any) {
      // 静默处理错误
      proxy.$modal.msgError('操作失败')
    } finally {
      state.loading = false
    }
  })
}

// 暴露变量
defineExpose({
  openDialog,
  closeDialog,
})
</script>

<style scoped lang="scss">
.form-section {
  margin-bottom: 24px;

  &:last-child {
    margin-bottom: 0;
  }
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 2px solid #f0f0f0;
  position: relative;

  &:before {
    content: '';
    position: absolute;
    left: 0;
    bottom: -2px;
    width: 40px;
    height: 2px;
    background: #409eff;
  }
}

:deep(.el-form-item) {
  margin-bottom: 18px;
}

:deep(.el-switch__label) {
  font-size: 13px;
}
</style>
