<script setup lang="ts">
import type { CheckItem, SubItem } from './formDesign-data';

import { computed, onMounted, reactive, ref, watch } from 'vue';
import { useRoute } from 'vue-router';

import { Page } from '@vben/common-ui';
import { useAccessStore } from '@vben/stores';

import {
  Delete,
  Edit,
  Plus,
  QuestionFilled,
  Rank,
} from '@element-plus/icons-vue';
import {
  ElButton,
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElMessage,
  ElPopconfirm,
  ElRadio,
  ElRadioGroup,
  ElSpace,
} from 'element-plus';

import {
  addinspectionItemApi,
  addsubItemApi,
  deleteinspectionItemApi,
  deleteSubItemApi,
  detailsbaseApi,
  editinspectionItemApi,
  editSubItemApi,
  queryinspectionItemApilist,
  querysubItembaseApilist,
  querytagbaseApilist,
  saveApi,
} from '#/api/system/tasksettings/checktheform';
import TinymceEditor from '#/components/tinymce/src/editor.vue';
import { getUploadAction } from '#/components/upload/config';

// import { tr } from 'element-plus/lib/locale/index.js';
const accessStore = useAccessStore();
const route = useRoute();
const formId = computed(() => (route.query.id as string) || '');
// const querydata = JSON.parse((route.query.data as string) || '{}');
// console.log(querydata);
const querydata: any = ref({});
// 子项列表
const subItems = ref<SubItem[]>([]) as any;

// 检查项列表
const checkItems = ref([]) as any;

// 选中状态
const selectedSubItemId = ref<string>('');
// 查询子项列表
const querysubItemlist = async () => {
  try {
    const res = await querysubItembaseApilist({
      mainId: querydata.value.id,
      pageNum: 1,
      pageSize: 1000,
    });
    subItems.value = res.rows || [];
    if (subItems.value.length > 0 && !selectedSubItemId.value) {
      selectedSubItemId.value = subItems.value[0].id;
    }
  } catch (error) {
    console.error('查询子项列表失败:', error);
  }
};

const taglistfn = async () => {
  try {
    const res = await querytagbaseApilist();
    if (res.rows.length > 0) {
      taglist.value = res.rows;
    }
  } catch (error) {
    console.error('获取标签列表失败:', error);
  }
};

const getFormData = async () => {
  try {
    if (formId.value) {
      const res = await detailsbaseApi(Number(formId.value));
      querydata.value = res || {};
      formData.name = querydata.value.name;
      formData.isRequired = String(querydata.value?.isRequired);
    }
  } catch (error) {
    console.error('获取检查项数据失败:', error);
  }
};

const init = async () => {
  // 重置选中的子项ID，确保不会引用旧数据
  selectedSubItemId.value = '';
  await getFormData();
  await querysubItemlist();
  await taglistfn();
};

// 检测 id 变化
watch(
  () => route.query.id,
  async (newVal, oldVal) => {
    if (newVal !== oldVal) {
      await init();
    }
  },
  {
    immediate: true,
  },
);

onMounted(async () => {
  await init();
});
const queryinspectionItemlist = async (subItemId: any) => {
  try {
    const res = await queryinspectionItemApilist({
      mainId: querydata.value.id,
      subItemId,
      pageNum: 1,
      pageSize: 1000,
    });
    checkItems.value = res.rows || [];
  } catch (error) {
    console.error('查询检查项列表失败:', error);
  }
};
// 监听选中子项变化
watch(
  selectedSubItemId,
  async (newVal, oldVal) => {
    await queryinspectionItemlist(newVal);
  },
  {
    deep: true,
  },
);
// 表单数据
const formData = reactive({
  name: querydata.value?.name || '',
  isRequired: String(querydata.value?.isRequired),
});

// 编辑抽屉
const editDrawerVisible = ref(false);
const editType = ref('');
const taglist = ref<any[]>([]);
const ishasPhoto = ref(false);
// 编辑表单数据
const editForm = reactive({
  id: '',
  name: '',
  isFull: false,
  // 关联子项
  subItemId: '',
  // 检查项名称
  itemName: '',
  isRandom: '',
  subFormType: '',
  // 标签
  tag: [], // 改为数组类型，支持多选
  // 输入项
  hasInput: '',
  inputContent: '',
  // 拍照
  hasPhoto: '',
  photoPrompt: '',
  // 检查结果
  checkResult: '',
  limitScore: '',
  // 示例图
  exampleImage: '',
  // exampleImagelist: [],
  // 富文本内容
  checkDescription: '',
});

// 表单验证规则
const editFormRules = reactive({
  name: [
    { required: true, message: '请输入名称', trigger: 'blur' },
    { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' },
  ],
  subItemId: [{ required: true, message: '请选择子项', trigger: 'blur' }],
  itemName: [{ required: true, message: '请输入检查项名称', trigger: 'blur' }],
  tag: [{ required: true, message: '请选择标签', trigger: 'blur' }],
  // hasInput: [
  //   {
  //     message: '选择"有"时必须填写',
  //     required: true,
  //     trigger: 'blur',
  //     validator: (rule: any, value: any, callback: any) => {
  //       if (value === '1' && !editForm.inputContent) {
  //         callback(new Error('请填写输入项'));
  //       } else {
  //         callback();
  //       }
  //     },
  //   },
  // ],
  // hasPhoto: [
  //   {
  //     message: '选择"有"时必须填写',
  //     required: true,
  //     trigger: 'blur',
  //     validator: (rule: any, value: any, callback: any) => {
  //       if ((value === '1' || value === '2') && !editForm.photoPrompt) {
  //         callback(new Error('请填写拍照提示'));
  //       } else {
  //         callback();
  //       }
  //     },
  //   },
  // ],
  checkResult: [
    {
      message: '选择"打分"时必须填写',
      required: true,
      trigger: 'change',
      validator: (rule: any, value: any, callback: any) => {
        if (value === '2' && !editForm.limitScore) {
          callback(new Error('请填写打分'));
        } else {
          callback();
        }
      },
    },
  ],
  // checkDescription: [
  //   { required: true, message: '请输入检查说明', trigger: 'blur' },
  // ],
});

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

// 新增子项
function addSubItem() {
  editForm.id = '';
  editForm.name = '';
  editType.value = 'addsubitems';

  editDrawerVisible.value = true;
}

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

// 删除子项
async function deleteSubItem(subItem: SubItem) {
  try {
    await deleteSubItemApi(subItem.id);
    await querysubItemlist();
  } catch (error) {
    console.error('删除子项失败:', error);
  }
}

// 新增检查项
function addCheckItem() {
  editType.value = 'addcheck';
  editDrawerVisible.value = true;
  editForm.id = '';
  editForm.name = '';
  // 关联子项
  editForm.subItemId = selectedSubItemId.value || '';
  // 检查项名称
  editForm.itemName = '';
  editForm.isRandom = '';
  // 标签
  editForm.tag = [];
  // 输入项
  editForm.hasInput = '';
  editForm.inputContent = '';
  // 拍照
  ishasPhoto.value = false;
  editForm.hasPhoto = '';
  editForm.photoPrompt = '';
  // 检查结果
  editForm.checkResult = '';
  editForm.limitScore = '';
  // 示例图
  editForm.exampleImage = '';
  // editForm.exampleImagelist = [];
  // 富文本内容
  editForm.checkDescription = '';
}

// 编辑检查项
function editCheckItem(checkItem: any) {
  console.log(checkItem);
  ishasPhoto.value = checkItem?.hasPhoto == '2';

  editType.value = 'check';
  editDrawerVisible.value = true;

  editForm.id = checkItem?.id || '';
  editForm.subItemId = checkItem?.subItemId || '';
  editForm.isRandom = checkItem?.isRandom == '1';
  editForm.itemName = checkItem?.itemName || '';
  editForm.tag = checkItem?.tag?.split(',') || [];
  editForm.hasInput = String(checkItem?.hasInput) || '';
  editForm.inputContent = checkItem?.inputContent || '';
  editForm.hasPhoto =
    checkItem?.hasPhoto == '2' ? '1' : String(checkItem?.hasPhoto);
  editForm.photoPrompt = checkItem?.photoPrompt || '';
  editForm.checkResult = String(checkItem?.checkResult) || '';
  editForm.limitScore = checkItem?.limitScore || '';
  // fileList.value = checkItem?.exampleImagelist|| [];
  // fileList.value = checkItem?.exampleImage
  //   .split(',')
  //   .map((item: any, index: number) => {
  //     return {
  //       name: item,
  //       response: {
  //         fileName: item,
  //         url: item,
  //       },
  //       status: 'success',
  //       uid: index + Math.random().toString(36).substring(2),
  //     };
  //   });
  editForm.checkDescription = checkItem?.checkDescription || '';
}

// 保存编辑
function saveEdit() {
  if (!editFormRef.value) return;
  editFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      switch (editType.value) {
        case 'addcheck': {
          // console.log(editForm);
          // console.log(fileList.value);
          // 新增检查项
          try {
            await addinspectionItemApi({
              mainId: querydata.value?.id,
              subItemId: editForm?.subItemId || '',
              isRandom: editForm?.isRandom === true ? '1' : '0',
              itemName: editForm?.itemName || '',
              tag: editForm?.tag.join(','),
              hasInput: editForm?.hasInput || '',
              inputContent: editForm?.inputContent || '',
              hasPhoto:
                ishasPhoto.value === true
                  ? (editForm.hasPhoto = '2')
                  : editForm?.hasPhoto,
              photoPrompt: editForm?.photoPrompt || '',
              checkResult: editForm?.isFull ? '3' : editForm?.checkResult || '',
              limitScore: editForm?.limitScore || '',
              exampleImage: fileList.value
                .map((file: any) => file?.response?.data?.fileName)
                .join(';'),
              // exampleImagelist: fileList.value,
              checkDescription: editForm?.checkDescription || '',
            });
            await queryinspectionItemlist(selectedSubItemId.value);
          } catch (error) {
            console.error('新增检查项失败:', error);
          }

          break;
        }
        case 'addsubitems': {
          // 新增子项
          try {
            await addsubItemApi({
              mainId: querydata.value.id,
              name: editForm.name,
            });
            await querysubItemlist();
          } catch (error) {
            console.error('新增子项失败:', error);
          }

          break;
        }
        case 'check': {
          // 编辑检查项
          const index = checkItems.value.findIndex(
            (item: any) => item.id === editForm.id,
          );
          if (index !== -1) {
            try {
              await editinspectionItemApi({
                id: checkItems.value[index].id,
                mainId: querydata.value?.id,
                subItemId: editForm?.subItemId || '',
                isRandom: editForm?.isRandom === true ? '1' : '0',
                itemName: editForm?.itemName || '',
                tag: editForm?.tag?.join(','),
                hasInput: editForm?.hasInput || '',
                inputContent: editForm?.inputContent || '',
                hasPhoto:
                  ishasPhoto.value === true
                    ? (editForm.hasPhoto = '2')
                    : editForm?.hasPhoto,
                photoPrompt: editForm?.photoPrompt || '',
                checkResult: editForm?.isFull
                  ? '3'
                  : editForm?.checkResult || '',
                limitScore: editForm?.limitScore || '',
                exampleImage: fileList.value
                  .map((file: any) => file?.response?.data?.fileName)
                  .join(';'),
                checkDescription: editForm?.checkDescription || '',
              });
              await queryinspectionItemlist(selectedSubItemId.value);
            } catch (error) {
              console.error('编辑检查项失败:', error);
            }
          }

          break;
        }
        case 'sub': {
          // 编辑子项
          const index = subItems.value.findIndex(
            (item) => item.id === editForm.id,
          );
          if (index !== -1) {
            try {
              await editSubItemApi({
                id: editForm.id,
                name: editForm.name,
              });
              await querysubItemlist();
              ElMessage.success('编辑子项成功');
            } catch (error) {
              console.error('编辑子项失败:', error);
            }
          }

          break;
        }
        // No default
      }
      editDrawerVisible.value = false;
    } else {
      console.log('表单验证失败');
      return false;
    }
  });
}

// 删除检查项s
async function deleteCheckItem(checkItem: CheckItem) {
  try {
    await deleteinspectionItemApi(checkItem.id);
    await queryinspectionItemlist(selectedSubItemId.value);
  } catch (error) {
    console.error('删除检查项失败:', error);
  }
}

// 保存表单
async function saveForm() {
  try {
    await saveApi({
      id: querydata.value.id,
      name: formData.name,
      isRequired: formData.isRequired,
      subItems: subItems.value,
      items: checkItems.value,
    });
  } catch (error) {
    console.error('保存检查表单信息失败:', error);
  }
}

// 拖拽开始
function onDragStart(event: DragEvent, item: any, type: 'check' | 'sub') {
  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();
}

// 拖拽放置
async function onDrop(
  event: DragEvent,
  targetItem: any,
  type: 'check' | 'sub',
) {
  event.preventDefault();
  if (event.dataTransfer) {
    const itemId = event.dataTransfer.getData('itemId');
    const itemType = event.dataTransfer.getData('itemType');

    if (itemType !== type) return;

    // 实现真实的拖拽排序逻辑
    const items = type === 'sub' ? subItems.value : checkItems.value;

    // 找到被拖拽元素和目标元素的索引（确保id类型一致）
    const draggedIndex = items.findIndex(
      (item) => String(item.id) === String(itemId),
    );
    const targetIndex = items.findIndex(
      (item) => String(item.id) === String(targetItem.id),
    );

    if (draggedIndex === -1 || targetIndex === -1) {
      console.error('未找到拖拽元素或目标元素', {
        itemId,
        targetItemId: targetItem.id,
        items,
      });
      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,
      '新顺序:',
      items.map((item) => ({
        id: item.id,
        name: item.name,
        order: item.order,
      })),
    );

    // 保存排序结果到后端（只处理子项）
    if (type === 'sub') {
      const updatePromises = items.map(async (item) => {
        try {
          await editSubItemApi({
            id: item.id,
            name: item.name,
            sortOrder: item.order, // 添加order参数保存顺序
          });
          console.log(`保存子项顺序成功: ${item.name}, order: ${item.order}`);
        } catch (error) {
          console.error(`保存子项顺序失败: ${item.name}`, error);
        }
      });
      await Promise.all(updatePromises);
      await querysubItemlist();
    } else {
      checkItems.value = items.map((item) => {
        return {
          ...item,
          sortOrder: item.order,
        };
      });
    }
  }
}

// 子项点击事件
async function handleSubItemClick(subItem: SubItem) {
  selectedSubItemId.value = subItem.id;
}
const fileList = ref([]) as any;

const dialogImageUrl = ref('');
const dialogVisible = ref(false);

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};
// 抽屉打开后处理函数
function handleDrawerOpen() {
  console.log('抽屉打开后处理函数');

  const drawerContent = document.querySelector('.el-drawer__body');
  if (drawerContent) {
    drawerContent.scrollTop = 0;
  }
}
</script>

<template>
  <Page :auto-content-height="true">
    <div class="flex h-full gap-4">
      <!-- 左侧子项 -->
      <div class="w-64 rounded-lg bg-white p-4 shadow">
        <div class="mb-4 flex items-center justify-between">
          <h3 class="text-lg font-semibold">子项</h3>
          <ElButton type="primary" size="small" @click="addSubItem">
            <template #icon>
              <Plus />
            </template>
            新增子项
          </ElButton>
        </div>
        <!-- 表格表头 -->
        <div
          class="flex items-center justify-between rounded-t-lg border-b bg-gray-50 p-3"
        >
          <div class="min-w-0 flex-1">
            <div class="text-sm font-medium text-gray-500">子项</div>
          </div>
          <div class="flex items-center"></div>
        </div>

        <!-- 表格内容 -->
        <div class="max-h-[calc(100vh-300px)] space-y-0 overflow-y-auto">
          <div
            v-for="subItem in subItems"
            :key="subItem.id"
            class="drag-item flex items-center justify-between border-x border-b p-3 last:rounded-b-lg"
            :class="{ 'selected-item': selectedSubItemId === subItem.id }"
            draggable="true"
            @click="handleSubItemClick(subItem)"
            @dragstart="onDragStart($event, subItem, 'sub')"
            @dragend="onDragEnd($event)"
            @dragenter="onDragEnter($event)"
            @dragover="onDragOver($event)"
            @drop="onDrop($event, subItem, 'sub')"
          >
            <div class="min-w-0 flex-1 truncate">
              {{ subItem.name }}
            </div>
            <ElSpace>
              <div class="cursor-move text-gray-400">
                <Rank />
              </div>
              <ElButton
                size="small"
                type="primary"
                circle
                @click="editSubItem(subItem)"
              >
                <template #icon>
                  <Edit />
                </template>
              </ElButton>
              <ElPopconfirm title="确认删除" @confirm="deleteSubItem(subItem)">
                <template #reference>
                  <ElButton size="small" type="danger" circle>
                    <template #icon>
                      <Delete />
                    </template>
                  </ElButton>
                </template>
              </ElPopconfirm>
            </ElSpace>
          </div>
        </div>
      </div>

      <!-- 右侧检查项 -->
      <div class="flex-1 rounded-lg bg-white p-4 shadow">
        <div class="mb-6">
          <div class="mb-4">
            <label class="mb-1 block text-sm font-medium text-gray-700"
              >检查表名称</label
            >
            <ElInput v-model="formData.name" placeholder="请输入检查表名称" />
          </div>
          <div class="mb-4">
            <label class="mb-1 block text-sm font-medium text-gray-700"
              >是否必检</label
            >
            <ElRadioGroup v-model="formData.isRequired">
              <ElRadio label="必检" value="1" />
              <ElRadio label="非必检" value="0" />
            </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="flex items-center justify-between rounded-t-lg border-b bg-gray-50 p-3"
        >
          <div class="grid min-w-0 flex-1 grid-cols-[80px_1fr] gap-4">
            <div class="text-sm font-medium text-gray-500">ID</div>
            <div class="text-sm font-medium text-gray-500">检查项</div>
          </div>
          <div class="flex items-center">
            <!-- 表头不需要操作按钮 -->
          </div>
        </div>

        <!-- 表格内容 -->
        <div class="max-h-[calc(100vh-450px)] space-y-0 overflow-y-auto">
          <div
            v-for="checkItem in checkItems"
            :key="checkItem.id"
            class="drag-item flex items-center justify-between border-x border-b p-3 last:rounded-b-lg"
            draggable="true"
            @dragstart="onDragStart($event, checkItem, 'check')"
            @dragend="onDragEnd($event)"
            @dragenter="onDragEnter($event)"
            @dragover="onDragOver($event)"
            @drop="onDrop($event, checkItem, 'check')"
          >
            <div class="grid min-w-0 flex-1 grid-cols-[80px_1fr] gap-4">
              <div class="truncate text-sm text-gray-500">
                {{ checkItem.id }}
              </div>
              <div class="truncate text-sm">
                {{ checkItem?.itemName }}
              </div>
            </div>
            <ElSpace>
              <div class="cursor-move text-gray-400">
                <Rank />
              </div>
              <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>
    <!-- 编辑抽屉 -->
    <ElDrawer
      v-model="editDrawerVisible"
      @open="handleDrawerOpen"
      :title="
        editType === 'sub'
          ? '编辑子项'
          : editType === 'addsubitems'
            ? '新增子项'
            : editType === 'check'
              ? '编辑检查项'
              : editType === 'addcheck'
                ? '新增检查项'
                : ''
      "
      size="600px"
      direction="rtl"
    >
      <ElForm
        ref="editFormRef"
        :model="editForm"
        :rules="editFormRules"
        label-width="80px"
      >
        <ElFormItem
          v-if="editType === 'addsubitems' || editType === 'sub'"
          prop="name"
          label="名称"
        >
          <ElInput v-model="editForm.name" placeholder="请输入名称" />
        </ElFormItem>
        <ElFormItem
          v-if="editType === 'addcheck' || editType === 'check'"
          label="检查表"
        >
          <ElInput :value="formData.name" disabled placeholder="空" />
        </ElFormItem>
        <ElFormItem
          v-if="editType === 'addcheck' || editType === 'check'"
          prop="subItemId"
          label="关联子项"
        >
          <el-select
            v-model="editForm.subItemId"
            placeholder="请选择关联子项"
            style="width: 100%"
            disabled
          >
            <el-option
              v-for="item in subItems"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </ElFormItem>

        <ElFormItem
          v-if="editType === 'addcheck' || editType === 'check'"
          prop="itemName"
          label="检查项名称"
          style="white-space: nowrap"
        >
          <div
            style="width: 100%; display: flex; align-items: center; gap: 4px"
          >
            <el-icon style="font-size: 16px"><QuestionFilled /></el-icon>
            <ElInput
              v-model="editForm.itemName"
              placeholder="请输入检查项名称"
            />
            <el-checkbox
              v-if="editForm?.checkResult === '2'"
              v-model="editForm.isFull"
              label="非满即零"
              size="large"
            />
          </div>
        </ElFormItem>

        <ElFormItem
          v-if="editType === 'addcheck' || editType === 'check'"
          prop="tag"
          label="标签"
        >
          <el-select
            v-model="editForm.tag"
            placeholder="请选择标签"
            style="width: 100%"
            multiple
          >
            <el-option
              v-for="item in taglist"
              :key="item.id"
              :label="item.tagName"
              :value="String(item.id)"
            />
          </el-select>
        </ElFormItem>
        <ElFormItem
          v-if="editType === 'addcheck' || editType === 'check'"
          prop="hasInput"
          label="输入项"
        >
          <div
            style="display: flex; align-items: center; width: 100%; gap: 8px"
          >
            <el-icon style="font-size: 16px"><QuestionFilled /></el-icon>

            <div style="flex: 0.4">
              <ElRadioGroup v-model="editForm.hasInput">
                <ElRadio value="0" size="large">无</ElRadio>
                <ElRadio value="1" size="large">有</ElRadio>
              </ElRadioGroup>
            </div>
            <ElInput
              style="flex: 1"
              v-model="editForm.inputContent"
              placeholder="请输入项提示"
              :disabled="editForm.hasInput !== '1'"
            />
          </div>
        </ElFormItem>
        <ElFormItem
          v-if="editType === 'addcheck' || editType === 'check'"
          prop="hasPhoto"
          label="拍照"
        >
          <div
            style="display: flex; align-items: center; width: 100%; gap: 8px"
          >
            <el-icon style="font-size: 16px"><QuestionFilled /></el-icon>

            <div style="flex: 0.5">
              <ElRadioGroup
                v-model="editForm.hasPhoto"
                @change="
                  (val) => {
                    val == '0' ? (ishasPhoto = false) : '';
                  }
                "
              >
                <ElRadio value="0" size="large">无</ElRadio>
                <ElRadio value="1" size="large">有</ElRadio>
              </ElRadioGroup>
            </div>
            <ElInput
              style="flex: 1; margin-right: 4px"
              v-model="editForm.photoPrompt"
              placeholder="请输入拍照提示"
              :disabled="editForm.hasPhoto !== '1'"
            />
            <el-checkbox
              v-model="ishasPhoto"
              @change="
                (val) => {
                  val === true ? (editForm.hasPhoto = '1') : '';
                }
              "
              label="必拍"
              size="large"
            />
          </div>
        </ElFormItem>
        <ElFormItem
          v-if="editType === 'addcheck' || editType === 'check'"
          prop="checkResult"
          label="检查结果"
        >
          <div
            style="display: flex; align-items: center; width: 100%; gap: 8px"
          >
            <el-icon style="font-size: 16px"><QuestionFilled /></el-icon>

            <div style="flex: 1">
              <ElRadioGroup v-model="editForm.checkResult">
                <ElRadio value="0" size="large">无</ElRadio>
                <ElRadio value="1" size="large">正常/异常</ElRadio>
                <ElRadio value="2" size="large">打分</ElRadio>
              </ElRadioGroup>
            </div>
            <ElInput
              style="flex: 0.6"
              v-model="editForm.limitScore"
              placeholder="请输入打分"
              :disabled="editForm.checkResult !== '2'"
            />
            <ElCheckbox
              v-model="editForm.isRandom"
              label="非满即零"
              size="large"
            />
          </div>
        </ElFormItem>
        <ElFormItem
          v-if="editType === 'addcheck' || editType === 'check'"
          label="示例图"
        >
          <el-icon style="font-size: 16px"><QuestionFilled /></el-icon>

          <el-upload
            v-model:file-list="fileList"
            :action="getUploadAction()"
            :headers="{ Authorization: `Bearer ${accessStore.accessToken}` }"
            :limit="3"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :disabled="fileList.length >= 3"
          >
            <template #default>
              <el-icon><Plus /></el-icon>
            </template>
          </el-upload>

          <ElDialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </ElDialog>
        </ElFormItem>
        <!-- prop="checkDescription" -->
        <ElFormItem
          v-if="editType === 'addcheck' || editType === 'check'"
          label="检查说明"
        >
          <TinymceEditor v-model="editForm.checkDescription" :height="300" />
        </ElFormItem>
      </ElForm>
      <template #footer>
        <ElSpace>
          <ElButton @click="editDrawerVisible = false">取消</ElButton>
          <ElButton type="primary" @click="saveEdit">确认</ElButton>
        </ElSpace>
      </template>
    </ElDrawer>
  </Page>
</template>

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

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

/* 拖拽项样式 */
.drag-item {
  cursor: move;

  &:hover:not(.selected-item) {
    background-color: #f9fafb;
  }
}

/* 选中项样式 */
.selected-item {
  background-color: #e0f2fe;
}

/* 确保拖拽图标能接收鼠标事件 */
.cursor-move {
  cursor: move;
  pointer-events: all;
}

/* 确保点击事件不影响拖拽功能 */
.drag-item {
  user-select: none;
}

/* 阻止按钮点击事件影响拖拽 */
.drag-item .el-button {
  pointer-events: auto;
}

/* 减小表单label字号 */
:deep(.el-form-item__label) {
  font-size: 12px;
}
</style>
