<template>
  <div class="device-type-management">
    <!-- 操作栏 -->
    <el-card class="toolbar">
      <div class="toolbar-actions">
        <el-button type="primary" :icon="Plus" @click="handleCreate">
          新建设备类型
        </el-button>
      </div>
    </el-card>

    <!-- 设备类型列表 -->
    <el-card class="table-card">
      <el-table
        :data="tableData"
        v-loading="loading"
        border
        stripe
      >
        <el-table-column prop="typeCode" label="类型编码" width="180" />
        <el-table-column prop="typeName" label="类型名称" width="180" />
        <el-table-column prop="category" label="设备分类" width="150">
          <template #default="{ row }">
            <el-tag>{{ row.category }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="250" />
        <el-table-column prop="fieldCount" label="字段数" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
              {{ row.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sortOrder" label="排序" width="100" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button link type="primary" @click="handleConfigFields(row)">
              配置字段
            </el-button>
            <el-button link type="primary" @click="handlePreview(row)">
              预览
            </el-button>
            <el-popconfirm
              title="确定删除该设备类型吗？"
              @confirm="handleDelete(row.id)"
            >
              <template #reference>
                <el-button link type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新建/编辑设备类型对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @closed="handleDialogClosed"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="类型编码" prop="typeCode">
          <el-input
            v-model="formData.typeCode"
            placeholder="请输入类型编码（如：LAPTOP）"
            :disabled="isEdit"
          />
        </el-form-item>

        <el-form-item label="类型名称" prop="typeName">
          <el-input
            v-model="formData.typeName"
            placeholder="请输入类型名称"
          />
        </el-form-item>

        <el-form-item label="设备分类" prop="category">
          <el-select
            v-model="formData.category"
            placeholder="请选择设备分类"
            style="width: 100%"
          >
            <el-option label="IT设备" value="IT设备" />
            <el-option label="办公设备" value="办公设备" />
            <el-option label="车辆" value="车辆" />
            <el-option label="家具" value="家具" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入描述"
          />
        </el-form-item>

        <el-form-item label="排序" prop="sortOrder">
          <el-input-number
            v-model="formData.sortOrder"
            :min="0"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 字段配置对话框 -->
    <el-dialog
      v-model="fieldConfigVisible"
      :title="`配置字段 - ${currentDeviceType?.typeName}`"
      width="900px"
      @closed="handleFieldConfigClosed"
    >
      <div class="field-config-container">
        <div class="field-list">
          <div class="field-header">
            <span>字段列表</span>
            <el-button type="primary" size="small" :icon="Plus" @click="handleAddField">
              添加字段
            </el-button>
          </div>

          <el-table
            :data="fields"
            border
            size="small"
          >
            <el-table-column prop="fieldName" label="字段名称" width="150" />
            <el-table-column prop="fieldCode" label="字段编码" width="150" />
            <el-table-column prop="fieldType" label="字段类型" width="120">
              <template #default="{ row }">
                <el-tag size="small">{{ getFieldTypeLabel(row.fieldType) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="isRequired" label="必填" width="80">
              <template #default="{ row }">
                <el-tag :type="row.isRequired ? 'danger' : 'info'" size="small">
                  {{ row.isRequired ? '是' : '否' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="sortOrder" label="排序" width="80" />
            <el-table-column label="操作" width="150">
              <template #default="{ row, $index }">
                <el-button link type="primary" size="small" @click="handleEditField(row)">
                  编辑
                </el-button>
                <el-button link type="danger" size="small" @click="handleDeleteField($index)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div class="field-form" v-if="showFieldForm">
          <h4>{{ editingFieldIndex >= 0 ? '编辑字段' : '添加字段' }}</h4>
          <el-form
            ref="fieldFormRef"
            :model="fieldForm"
            :rules="fieldFormRules"
            label-width="100px"
          >
            <el-form-item label="字段名称" prop="fieldName">
              <el-input v-model="fieldForm.fieldName" placeholder="请输入字段名称" />
            </el-form-item>

            <el-form-item label="字段编码" prop="fieldCode">
              <el-input
                v-model="fieldForm.fieldCode"
                placeholder="请输入字段编码（如：cpu）"
                :disabled="editingFieldIndex >= 0"
              />
            </el-form-item>

            <el-form-item label="字段类型" prop="fieldType">
              <el-select v-model="fieldForm.fieldType" placeholder="请选择字段类型">
                <el-option label="单行文本" value="text" />
                <el-option label="多行文本" value="textarea" />
                <el-option label="数字" value="number" />
                <el-option label="日期" value="date" />
                <el-option label="下拉选择" value="select" />
                <el-option label="复选框" value="checkbox" />
                <el-option label="URL链接" value="url" />
                <el-option label="邮箱" value="email" />
                <el-option label="手机号" value="phone" />
              </el-select>
            </el-form-item>

            <el-form-item label="是否必填">
              <el-switch v-model="fieldForm.isRequired" />
            </el-form-item>

            <el-form-item label="占位提示" prop="placeholder" v-if="['text', 'textarea'].includes(fieldForm.fieldType)">
              <el-input v-model="fieldForm.placeholder" placeholder="请输入占位提示" />
            </el-form-item>

            <el-form-item label="默认值" v-if="['text', 'textarea', 'number'].includes(fieldForm.fieldType)">
              <el-input v-model="fieldForm.defaultValue" placeholder="请输入默认值" />
            </el-form-item>

            <el-form-item label="选项配置" v-if="fieldForm.fieldType === 'select'">
              <div class="options-config">
                <div
                  v-for="(option, index) in fieldForm.options"
                  :key="index"
                  class="option-item"
                >
                  <el-input v-model="option.label" placeholder="显示文本" style="width: 150px" />
                  <el-input v-model="option.value" placeholder="值" style="width: 150px" />
                  <el-button
                    type="danger"
                    size="small"
                    :icon="Delete"
                    @click="handleDeleteOption(index)"
                  />
                </div>
                <el-button size="small" :icon="Plus" @click="handleAddOption">
                  添加选项
                </el-button>
              </div>
            </el-form-item>

            <el-form-item label="排序" prop="sortOrder">
              <el-input-number v-model="fieldForm.sortOrder" :min="0" />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="handleSaveField">
                保存字段
              </el-button>
              <el-button @click="showFieldForm = false">
                取消
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <template #footer>
        <el-button @click="fieldConfigVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleSaveFields">
          保存配置
        </el-button>
      </template>
    </el-dialog>

    <!-- 预览对话框 -->
    <el-dialog
      v-model="previewVisible"
      :title="`预览 - ${currentDeviceType?.typeName}`"
      width="700px"
    >
      <div class="preview-container">
        <el-form label-width="120px" disabled>
          <el-form-item
            v-for="field in currentDeviceType?.fields"
            :key="field.id"
            :label="field.fieldName"
          >
            <el-input
              v-if="field.fieldType === 'text'"
              :placeholder="field.placeholder"
            />
            <el-input
              v-else-if="field.fieldType === 'textarea'"
              type="textarea"
              :placeholder="field.placeholder"
            />
            <el-input-number
              v-else-if="field.fieldType === 'number'"
              :placeholder="field.placeholder"
            />
            <el-date-picker
              v-else-if="field.fieldType === 'date'"
              type="date"
              placeholder="选择日期"
            />
            <el-select
              v-else-if="field.fieldType === 'select'"
              :placeholder="field.placeholder"
            >
              <el-option
                v-for="option in field.options"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
            <el-checkbox v-else-if="field.fieldType === 'checkbox'">
              复选框示例
            </el-checkbox>
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <el-button @click="previewVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { Plus, Delete } from '@element-plus/icons-vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import {
  getDeviceTypeList,
  createDeviceType,
  updateDeviceType,
  deleteDeviceType,
  getDeviceTypeFields,
  addDeviceTypeField,
  updateDeviceTypeField,
  deleteDeviceTypeField
} from '@/api/device-types'
import type { DeviceType, DynamicField } from '@/types'

// 响应式数据
const loading = ref(false)
const tableData = ref<DeviceType[]>([])

// 对话框相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const dialogTitle = computed(() => isEdit.value ? '编辑设备类型' : '新建设备类型')
const submitLoading = ref(false)
const formRef = ref<FormInstance>()

const formData = reactive({
  typeCode: '',
  typeName: '',
  category: '',
  description: '',
  sortOrder: 0
})

const formRules: FormRules = {
  typeCode: [
    { required: true, message: '请输入类型编码', trigger: 'blur' },
    { pattern: /^[A-Z_]+$/, message: '类型编码只能包含大写字母和下划线', trigger: 'blur' }
  ],
  typeName: [
    { required: true, message: '请输入类型名称', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择设备分类', trigger: 'change' }
  ]
}

// 字段配置相关
const fieldConfigVisible = ref(false)
const currentDeviceType = ref<DeviceType>()
const fields = ref<DynamicField[]>([])
const showFieldForm = ref(false)
const editingFieldIndex = ref(-1)
const fieldFormRef = ref<FormInstance>()

const fieldForm = reactive({
  fieldName: '',
  fieldCode: '',
  fieldType: 'text' as DynamicField['fieldType'],
  isRequired: false,
  placeholder: '',
  defaultValue: '',
  options: [] as Array<{ label: string; value: any }>,
  sortOrder: 0
})

const fieldFormRules: FormRules = {
  fieldName: [{ required: true, message: '请输入字段名称', trigger: 'blur' }],
  fieldCode: [
    { required: true, message: '请输入字段编码', trigger: 'blur' },
    { pattern: /^[a-z_]+$/, message: '字段编码只能包含小写字母和下划线', trigger: 'blur' }
  ],
  fieldType: [{ required: true, message: '请选择字段类型', trigger: 'change' }],
  sortOrder: [{ required: true, message: '请输入排序', trigger: 'blur' }]
}

// 预览相关
const previewVisible = ref(false)

// 获取设备类型列表
const fetchDeviceTypeList = async () => {
  loading.value = true
  try {
    const { data } = await getDeviceTypeList()
    tableData.value = data
  } finally {
    loading.value = false
  }
}

// 获取字段类型标签
const getFieldTypeLabel = (type: string) => {
  const typeMap: Record<string, string> = {
    text: '单行文本',
    textarea: '多行文本',
    number: '数字',
    date: '日期',
    select: '下拉选择',
    checkbox: '复选框',
    url: 'URL链接',
    email: '邮箱',
    phone: '手机号'
  }
  return typeMap[type] || type
}

// 新建设备类型
const handleCreate = () => {
  isEdit.value = false
  dialogVisible.value = true
}

// 编辑设备类型
const handleEdit = (row: DeviceType) => {
  isEdit.value = true
  currentDeviceType.value = row
  Object.assign(formData, {
    typeCode: row.typeCode,
    typeName: row.typeName,
    category: row.category,
    description: row.description || '',
    sortOrder: row.sortOrder
  })
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate()

  submitLoading.value = true
  try {
    if (isEdit.value) {
      await updateDeviceType(currentDeviceType.value!.id, formData)
      ElMessage.success('更新成功')
    } else {
      await createDeviceType(formData)
      ElMessage.success('创建成功')
    }
    dialogVisible.value = false
    fetchDeviceTypeList()
  } finally {
    submitLoading.value = false
  }
}

// 对话框关闭
const handleDialogClosed = () => {
  formRef.value?.resetFields()
  Object.assign(formData, {
    typeCode: '',
    typeName: '',
    category: '',
    description: '',
    sortOrder: 0
  })
}

// 删除设备类型
const handleDelete = async (id: number) => {
  try {
    await deleteDeviceType(id)
    ElMessage.success('删除成功')
    fetchDeviceTypeList()
  } catch (error) {
    console.error('删除失败:', error)
  }
}

// 配置字段
const handleConfigFields = async (row: DeviceType) => {
  currentDeviceType.value = row
  try {
    const { data } = await getDeviceTypeFields(row.id)
    fields.value = data
    fieldConfigVisible.value = true
  } catch (error) {
    console.error('获取字段配置失败:', error)
  }
}

// 添加字段
const handleAddField = () => {
  editingFieldIndex.value = -1
  Object.assign(fieldForm, {
    fieldName: '',
    fieldCode: '',
    fieldType: 'text',
    isRequired: false,
    placeholder: '',
    defaultValue: '',
    options: [],
    sortOrder: fields.value.length
  })
  showFieldForm.value = true
}

// 编辑字段
const handleEditField = (row: DynamicField) => {
  const index = fields.value.findIndex(f => f.id === row.id)
  editingFieldIndex.value = index
  Object.assign(fieldForm, {
    fieldName: row.fieldName,
    fieldCode: row.fieldCode,
    fieldType: row.fieldType,
    isRequired: row.isRequired,
    placeholder: row.placeholder || '',
    defaultValue: row.defaultValue || '',
    options: row.options ? [...row.options] : [],
    sortOrder: row.sortOrder
  })
  showFieldForm.value = true
}

// 保存字段
const handleSaveField = async () => {
  if (!fieldFormRef.value) return

  await fieldFormRef.value.validate()

  const fieldData = { ...fieldForm }

  if (editingFieldIndex.value >= 0) {
    // 编辑现有字段
    const field = fields.value[editingFieldIndex.value]
    await updateDeviceTypeField(currentDeviceType.value!.id, field.id, fieldData)
    Object.assign(field, fieldData)
  } else {
    // 添加新字段
    const { data } = await addDeviceTypeField(currentDeviceType.value!.id, fieldData)
    fields.value.push(data)
  }

  ElMessage.success(editingFieldIndex.value >= 0 ? '字段更新成功' : '字段添加成功')
  showFieldForm.value = false
}

// 删除字段
const handleDeleteField = async (index: number) => {
  try {
    const field = fields.value[index]
    await deleteDeviceTypeField(currentDeviceType.value!.id, field.id)
    fields.value.splice(index, 1)
    ElMessage.success('字段删除成功')
  } catch (error) {
    console.error('删除字段失败:', error)
  }
}

// 保存字段配置
const handleSaveFields = () => {
  ElMessage.success('字段配置保存成功')
  fieldConfigVisible.value = false
  fetchDeviceTypeList()
}

// 字段配置对话框关闭
const handleFieldConfigClosed = () => {
  fields.value = []
  showFieldForm.value = false
  editingFieldIndex.value = -1
}

// 添加选项
const handleAddOption = () => {
  fieldForm.options.push({ label: '', value: '' })
}

// 删除选项
const handleDeleteOption = (index: number) => {
  fieldForm.options.splice(index, 1)
}

// 预览
const handlePreview = async (row: DeviceType) => {
  currentDeviceType.value = row
  try {
    const { data } = await getDeviceTypeFields(row.id)
    currentDeviceType.value = { ...row, fields: data }
    previewVisible.value = true
  } catch (error) {
    console.error('获取字段配置失败:', error)
  }
}

onMounted(() => {
  fetchDeviceTypeList()
})
</script>

<style scoped lang="scss">
.device-type-management {
  .toolbar {
    margin-bottom: 16px;
  }

  .table-card {
    .pagination {
      display: flex;
      justify-content: flex-end;
      margin-top: 16px;
    }
  }

  .field-config-container {
    display: flex;
    gap: 20px;
    height: 500px;

    .field-list {
      flex: 1;
      display: flex;
      flex-direction: column;

      .field-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12px;

        span {
          font-size: 16px;
          font-weight: bold;
          color: #475569;
        }
      }
    }

    .field-form {
      width: 400px;
      padding: 20px;
      background: #f8fafc;
      border-radius: 4px;
      overflow-y: auto;

      h4 {
        margin-bottom: 16px;
        color: #475569;
      }

      .options-config {
        .option-item {
          display: flex;
          gap: 10px;
          margin-bottom: 10px;
        }
      }
    }
  }

  .preview-container {
    padding: 20px;
  }
}
</style>
