<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRoute } from 'vue-router';

import { Page, useVbenForm } from '@vben/common-ui';
import { ElButton, ElInput, ElRadio, ElRadioGroup, ElSpace, ElPopconfirm, ElDialog, ElForm, ElFormItem } from 'element-plus';
import { Plus, Edit, Delete, Drag } from '@element-plus/icons-vue';

import type { SubItem, CheckItem } from './formDesign-data';
import { mockSubItems, mockCheckItems, mockFormData } from './formDesign-data';

const route = useRoute();

// 表单数据
const formData = reactive({
  formName: route.query.formName as string || mockFormData.formName,
  isRequired: mockFormData.isRequired,
});

// 子项列表
const subItems = ref<SubItem[]>(mockSubItems);

// 检查项列表
const checkItems = ref<CheckItem[]>(mockCheckItems);

// 编辑弹出框
const editDialogVisible = ref(false);
const editType = ref<'sub' | 'check'>('sub');
const editForm = reactive({
  id: '',
  name: '',
  isRequired: true,
});

// 表单验证规则
const editFormRules = reactive({
  name: [
    { required: true, message: '请输入名称', trigger: 'blur' },
    { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
  ]
});

// 表单引用
const editFormRef = ref<any>(null);

// 被编辑的原始项
const editedItem = ref<any>(null);

// 新增子项
function addSubItem() {
  const newSubItem: SubItem = {
    id: `sub${Date.now()}`,
    name: '新子项',
    order: subItems.value.length + 1,
  };
  subItems.value.push(newSubItem);
}

// 编辑子项
function editSubItem(subItem: SubItem) {
  editType.value = 'sub';
  editedItem.value = subItem;
  editForm.id = subItem.id;
  editForm.name = subItem.name;
  editDialogVisible.value = true;
}

// 删除子项
function deleteSubItem(subItem: SubItem) {
  subItems.value = subItems.value.filter(item => item.id !== subItem.id);
}

// 新增检查项
function addCheckItem() {
  const newCheckItem: CheckItem = {
    id: `check${Date.now()}`,
    name: '新检查项',
    isRequired: true,
    order: checkItems.value.length + 1,
  };
  checkItems.value.push(newCheckItem);
}

// 编辑检查项
function editCheckItem(checkItem: CheckItem) {
  editType.value = 'check';
  editedItem.value = checkItem;
  editForm.id = checkItem.id;
  editForm.name = checkItem.name;
  editForm.isRequired = checkItem.isRequired;
  editDialogVisible.value = true;
}

// 保存编辑
function saveEdit() {
  if (!editFormRef.value) return;
  
  editFormRef.value.validate((valid: boolean) => {
    if (valid) {
      if (editType.value === 'sub') {
        // 更新子项
        const subItem = subItems.value.find(item => item.id === editForm.id);
        if (subItem) {
          subItem.name = editForm.name;
        }
      } else {
        // 更新检查项
        const checkItem = checkItems.value.find(item => item.id === editForm.id);
        if (checkItem) {
          checkItem.name = editForm.name;
          checkItem.isRequired = editForm.isRequired;
        }
      }
      editDialogVisible.value = false;
      console.log('编辑保存成功');
    } else {
      console.log('表单验证失败');
      return false;
    }
  });
}

// 删除检查项
function deleteCheckItem(checkItem: CheckItem) {
  checkItems.value = checkItems.value.filter(item => item.id !== checkItem.id);
}

// 保存表单
function saveForm() {
  // 模拟保存操作
  console.log('保存表单:', formData);
  console.log('保存子项:', subItems.value);
  console.log('保存检查项:', checkItems.value);
}

// 拖拽开始
function onDragStart(event: DragEvent, item: any, type: 'sub' | 'check') {
  if (event.dataTransfer) {
    event.dataTransfer.setData('itemId', item.id);
    event.dataTransfer.setData('itemType', type);
  }
}

// 拖拽结束
function onDragEnd(event: DragEvent) {
  if (event.dataTransfer) {
    event.dataTransfer.clearData();
  }
}

// 拖拽进入
function onDragEnter(event: DragEvent) {
  event.preventDefault();
}

// 拖拽覆盖
function onDragOver(event: DragEvent) {
  event.preventDefault();
}

// 拖拽放置
function onDrop(event: DragEvent, targetItem: any, type: 'sub' | 'check') {
  event.preventDefault();
  if (event.dataTransfer) {
    const itemId = event.dataTransfer.getData('itemId');
    const itemType = event.dataTransfer.getData('itemType');
    
    if (itemType !== type) return;
    
    // 实现真实的拖拽排序逻辑
    let items = type === 'sub' ? subItems.value : checkItems.value;
    
    // 找到被拖拽元素和目标元素的索引
    const draggedIndex = items.findIndex(item => item.id === itemId);
    const targetIndex = items.findIndex(item => item.id === targetItem.id);
    
    if (draggedIndex === -1 || targetIndex === -1) return;
    
    // 移动元素
    const [draggedItem] = items.splice(draggedIndex, 1);
    items.splice(targetIndex, 0, draggedItem);
    
    // 更新所有元素的order属性
    items.forEach((item, index) => {
      item.order = index + 1;
    });
    
    console.log('拖拽排序完成:', itemId, '到', targetItem.id);
  }
}
</script>

<template>
  <Page :auto-content-height="true">
    <div class="flex h-full gap-4">
      <!-- 左侧子项 -->
      <div class="w-64 bg-white rounded-lg shadow p-4">
        <div class="flex justify-between items-center mb-4">
          <h3 class="text-lg font-semibold">子项</h3>
          <ElButton
            type="primary"
            size="small"
            @click="addSubItem"
          >
            <template #icon>
              <Plus />
            </template>
            新增子项
          </ElButton>
        </div>
        <div class="space-y-2">
          <div
            v-for="subItem in subItems"
            :key="subItem.id"
            class="flex items-center justify-between p-2 border rounded drag-item"
            draggable="true"
            @dragstart="onDragStart($event, subItem, 'sub')"
            @dragend="onDragEnd($event)"
            @dragenter="onDragEnter($event)"
            @dragover="onDragOver($event)"
            @drop="onDrop($event, subItem, 'sub')"
          >
            <div class="flex items-center gap-2">
              <Drag class="text-gray-400" />
              <span>{{ subItem.name }}</span>
            </div>
            <ElSpace>
              <ElButton
                size="small"
                type="primary"
                plain
                @click="editSubItem(subItem)"
              >
                <template #icon>
                  <Edit />
                </template>
                编辑
              </ElButton>
              <ElPopconfirm title="确认删除" @confirm="deleteSubItem(subItem)">
                <template #reference>
                  <ElButton
                    size="small"
                    type="danger"
                    plain
                  >
                    <template #icon>
                      <Delete />
                    </template>
                    删除
                  </ElButton>
                </template>
              </ElPopconfirm>
            </ElSpace>
          </div>
        </div>
      </div>

      <!-- 右侧检查项 -->
      <div class="flex-1 bg-white rounded-lg shadow p-4">
        <div class="mb-6">
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 mb-1">检查表名称</label>
            <ElInput v-model="formData.formName" placeholder="请输入检查表名称" />
          </div>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 mb-1">是否必检</label>
            <ElRadioGroup v-model="formData.isRequired">
              <ElRadio :label="true">必检</ElRadio>
              <ElRadio :label="false">非必检</ElRadio>
            </ElRadioGroup>
          </div>
          <div class="flex items-center gap-2">
            <ElButton type="primary" @click="saveForm">保存</ElButton>
            <ElButton type="success" @click="addCheckItem">新增项</ElButton>
            <ElButton type="info" disabled>编辑过后必须要保存</ElButton>
          </div>
        </div>

        <div class="mb-4">
          <h3 class="text-lg font-semibold">检查项</h3>
        </div>

        <div class="space-y-3">
          <div
            v-for="checkItem in checkItems"
            :key="checkItem.id"
            class="flex items-start justify-between p-3 border rounded drag-item"
            draggable="true"
            @dragstart="onDragStart($event, checkItem, 'check')"
            @dragend="onDragEnd($event)"
            @dragenter="onDragEnter($event)"
            @dragover="onDragOver($event)"
            @drop="onDrop($event, checkItem, 'check')"
          >
            <div class="flex items-start gap-3">
              <Drag class="text-gray-400 mt-1" />
              <div class="space-y-1">
                <div class="text-sm text-gray-500">{{ checkItem.id }}</div>
                <div class="text-sm">{{ checkItem.name }}</div>
              </div>
            </div>
            <ElSpace>
              <ElButton
                size="small"
                type="primary"
                plain
                @click="editCheckItem(checkItem)"
              >
                <template #icon>
                  <Edit />
                </template>
                编辑
              </ElButton>
              <ElPopconfirm title="确认删除" @confirm="deleteCheckItem(checkItem)">
                <template #reference>
                  <ElButton
                    size="small"
                    type="danger"
                    plain
                  >
                    <template #icon>
                      <Delete />
                    </template>
                    删除
                  </ElButton>
                </template>
              </ElPopconfirm>
            </ElSpace>
          </div>
        </div>
      </div>
    </div>
  <!-- 编辑弹出框 -->
<ElDialog
  v-model="editDialogVisible"
  :title="editType === 'sub' ? '编辑子项' : '编辑检查项'"
  width="500px"
>
  <ElForm
    ref="editFormRef"
    :model="editForm"
    :rules="editFormRules"
    label-width="80px"
  >
    <ElFormItem label="名称">
      <ElInput v-model="editForm.name" placeholder="请输入名称" />
    </ElFormItem>
    <ElFormItem v-if="editType === 'check'" label="是否必检">
      <ElRadioGroup v-model="editForm.isRequired">
        <ElRadio :label="true">必检</ElRadio>
        <ElRadio :label="false">非必检</ElRadio>
      </ElRadioGroup>
    </ElFormItem>
  </ElForm>
  <template #footer>
    <ElSpace>
      <ElButton @click="editDialogVisible = false">取消</ElButton>
      <ElButton type="primary" @click="saveEdit">保存</ElButton>
    </ElSpace>
  </template>
</ElDialog>

</Page>
</template>

<style scoped lang="scss">
/* 移除与Tailwind CSS冲突的基础类名定义 */

/* 使用更具体的选择器来定义组件特定样式 */

/* 拖拽项样式 */
.drag-item {
  cursor: move;
  
  &:hover {
    background-color: #f9fafb;
  }
}
</style>
